On this tutorial, we introduce TinyDev class implementation, a minimal but highly effective AI code era software that makes use of the Gemini API to remodel easy app concepts into complete, structured functions. Designed to run effortlessly in Pocket book, TinyDev follows a clear three-phase workflow—Plan → Recordsdata → Code—to make sure consistency, performance, and modular design. Whether or not constructing an internet interface, a Python backend, or a utility script, TinyDev permits customers to explain their mission in pure language & obtain ready-to-run code recordsdata, routinely generated and saved in an organized listing. This makes it an excellent start line for fast prototyping or studying how AI can help in growth duties.
import google.generativeai as genai
import os
import json
import re
from pathlib import Path
from typing import Listing, Dict
We start by importing important libraries required for the TinyDev code generator. google.generativeai is used to work together with the Gemini API, whereas customary libraries like os, json, and re help file dealing with and textual content processing. Path and kind hints from typing guarantee clear file operations and higher code readability.
class TinyDev:
"""
TinyDev: A light-weight AI code generator impressed by smol-dev
Makes use of Gemini API to generate full functions from easy prompts
Follows the confirmed three-phase workflow: Plan → Recordsdata → Code
"""
def __init__(self, api_key: str, mannequin: str = "gemini-1.5-flash"):
genai.configure(api_key=api_key)
self.mannequin = genai.GenerativeModel(mannequin)
self.generation_config = {
'temperature': 0.1,
'top_p': 0.8,
'max_output_tokens': 8192,
}
def plan(self, immediate: str) -> str:
"""
Section 1: Generate mission plan and shared dependencies
Creates the inspiration for constant code era
"""
planning_prompt = f"""As an AI developer, you’re constructing a software that routinely generates code tailor-made to the person’s wants.
this system you might be writing is predicated on the next description:
{immediate}
the recordsdata we write can be generated by a python script. the purpose is for us to all work collectively to write down a program that may write the code for the person.
since we're working collectively, we have to perceive what our shared dependencies are. this consists of:
- import statements all of us want to make use of
- variable names which can be shared between recordsdata
- capabilities which can be known as from one file to a different
- some other shared state
that is essentially the most crucial a part of the method, if we do not get this proper, the generated code is not going to work correctly.
please output a markdown file known as shared_dependencies.md that lists all the shared dependencies.
the dependencies must be organized as:
1. shared variables (globals, constants)
2. shared capabilities (perform signatures)
3. shared lessons (class names and key strategies)
4. shared imports (modules to import)
5. shared DOM component ids (if net mission)
6. shared file paths/names
be EXHAUSTIVE in your evaluation. each file should be capable of import or reference these shared objects."""
response = self.mannequin.generate_content(
planning_prompt,
generation_config=self.generation_config
)
return response.textual content
def specify_file_paths(self, immediate: str, shared_deps: str) -> Listing[str]:
"""
Section 2: Decide what recordsdata should be created
"""
files_prompt = f"""As an AI developer, you’re constructing a software that routinely generates code tailor-made to the person’s wants.
this system:
{immediate}
the shared dependencies:
{shared_deps}
Based mostly on this system description and shared dependencies, return a JSON array of the filenames that must be written.
Solely return the JSON array, nothing else. The JSON must be an array of strings representing file paths.
For instance, for a easy net app you would possibly return:
["index.html", "styles.css", "script.js"]
For a Python mission you would possibly return:
["main.py", "utils.py", "config.py", "requirements.txt"]
JSON array:"""
response = self.mannequin.generate_content(
files_prompt,
generation_config=self.generation_config
)
strive:
json_match = re.search(r'[.*?]', response.textual content, re.DOTALL)
if json_match:
recordsdata = json.masses(json_match.group())
return [f for f in files if isinstance(f, str)]
else:
traces = [line.strip() for line in response.text.split('n') if line.strip()]
recordsdata = []
for line in traces:
if '.' in line and never line.startswith('#'):
file = re.sub(r'[^w-_./]', '', line)
if file:
recordsdata.append(file)
return recordsdata[:10]
besides Exception as e:
print(f"Error parsing recordsdata: {e}")
return ["main.py", "README.md"]
def generate_code_sync(self, immediate: str, shared_deps: str, filename: str) -> str:
"""
Section 3: Generate code for particular person recordsdata
"""
code_prompt = f"""As an AI developer, you’re constructing a software that routinely generates code tailor-made to the person’s wants..
this system:
{immediate}
the shared dependencies:
{shared_deps}
Please write the file {filename}.
Keep in mind that your job is to write down the code for {filename} ONLY. Don't write some other recordsdata.
the code must be totally useful. that means:
- all imports must be right
- all variable references must be right
- all perform calls must be right
- the code must be syntactically right
- the code must be logically right
Be sure to implement each a part of the performance described in this system description.
DO NOT embrace ``` code fences in your response. Return solely the uncooked code.
Right here is the code for {filename}:"""
response = self.mannequin.generate_content(
code_prompt,
generation_config=self.generation_config
)
code = response.textual content
code = re.sub(r'^```[w]*n', '', code, flags=re.MULTILINE)
code = re.sub(r'n```$', '', code, flags=re.MULTILINE)
return code.strip()
def create_app(self, immediate: str, output_dir: str = "/content material/generated_app") -> Dict:
"""
Important workflow: Remodel a easy immediate into a whole software
"""
print(f"🚀 TinyDev workflow beginning...")
print(f"📝 Immediate: {immediate}")
print("n📋 Step 1: Planning shared dependencies...")
shared_deps = self.plan(immediate)
print("✅ Dependencies deliberate")
print("n📁 Step 2: Figuring out file construction...")
file_paths = self.specify_file_paths(immediate, shared_deps)
print(f"📄 Recordsdata to generate: {file_paths}")
Path(output_dir).mkdir(dad and mom=True, exist_ok=True)
print(f"n⚡ Step 3: Producing {len(file_paths)} recordsdata...")
outcomes = {
'immediate': immediate,
'shared_deps': shared_deps,
'recordsdata': {},
'output_dir': output_dir
}
with open(Path(output_dir) / "shared_dependencies.md", 'w') as f:
f.write(shared_deps)
for filename in file_paths:
print(f" 🔧 Producing {filename}...")
strive:
code = self.generate_code_sync(immediate, shared_deps, filename)
file_path = Path(output_dir) / filename
file_path.mother or father.mkdir(dad and mom=True, exist_ok=True)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(code)
outcomes['files'][filename] = code
print(f" ✅ {filename} created ({len(code)} chars)")
besides Exception as e:
print(f" ❌ Error producing {filename}: {e}")
outcomes['files'][filename] = f"# Error: {e}"
readme = f"""# Generated by TinyDev (Gemini-Powered)
## Unique Immediate
{immediate}
## Generated Recordsdata
{chr(10).be a part of(f'- {f}' for f in file_paths)}
## About TinyDev
TinyDev is impressed by smol-ai/developer however makes use of free Gemini API.
It follows the confirmed three-phase workflow: Plan → Recordsdata → Code
## Utilization
Verify particular person recordsdata for particular utilization directions.
Generated on: {os.popen('date').learn().strip()}
"""
with open(Path(output_dir) / "README.md", 'w') as f:
f.write(readme)
print(f"n🎉 Full! Generated {len(outcomes['files'])} recordsdata in {output_dir}")
return outcomes
The TinyDev class encapsulates the complete logic of an AI-powered code generator utilizing the Gemini API. It implements a structured three-phase workflow: first, it analyzes the person immediate to generate shared dependencies (plan); subsequent, it identifies which recordsdata are wanted for the applying (specify_file_paths); and eventually, it generates useful code for every file individually (generate_code_sync). The create_app technique brings every part collectively by orchestrating the complete app era pipeline and saving the outcomes, together with code recordsdata and an in depth README, right into a specified output listing, providing a whole, ready-to-use software scaffold from a single immediate.
def demo_tinydev():
"""Demo the TinyDev code generator"""
api_key = "Use Your API Key right here"
if api_key == "YOUR_GEMINI_API_KEY_HERE":
print("❌ Please set your Gemini API key!")
print("Get one free at: https://makersuite.google.com/app/apikey")
return None
tiny_dev = TinyDev(api_key)
demo_prompts = [
"a simple HTML/JS/CSS tic tac toe game",
"a Python web scraper that gets the latest news from multiple sources",
"a responsive landing page for a local coffee shop with contact form",
"a Flask REST API for managing a todo list",
"a JavaScript calculator with a modern UI"
]
print("🤖 TinyDev - AI Code Generator")
print("=" * 50)
print("Impressed by smol-ai/developer, powered by Gemini API")
print(f"Out there demo tasks:")
for i, immediate in enumerate(demo_prompts, 1):
print(f"{i}. {immediate}")
demo_prompt = demo_prompts[0]
print(f"n🎯 Working demo: {demo_prompt}")
strive:
outcomes = tiny_dev.create_app(demo_prompt)
print(f"n📊 Outcomes Abstract:")
print(f" 📝 Immediate: {outcomes['prompt']}")
print(f" 📁 Output: {outcomes['output_dir']}")
print(f" 📄 Recordsdata: {len(outcomes['files'])}")
print(f"n📋 Generated Recordsdata:")
for filename in outcomes['files'].keys():
print(f" - {filename}")
if outcomes['files']:
preview_file = listing(outcomes['files'].keys())[0]
preview_code = outcomes['files'][preview_file]
print(f"n👁️ Preview of {preview_file}:")
print("-" * 40)
print(preview_code[:400] + "..." if len(preview_code) > 400 else preview_code)
print("-" * 40)
print(f"n💡 This makes use of the identical confirmed workflow as smol-ai/developer!")
print(f"📂 Verify {outcomes['output_dir']} for all generated recordsdata")
return outcomes
besides Exception as e:
print(f"❌ Demo failed: {e}")
return None
The demo_tinydev() perform showcases TinyDev’s capabilities by operating a predefined demo utilizing one among a number of pattern prompts, corresponding to producing a Tic Tac Toe sport or a Python information scraper. It initializes the TinyDev class with a Gemini API key, selects the primary immediate from an inventory of mission concepts, and guides the person by way of the complete code era pipeline, together with planning shared dependencies, defining file construction, and producing code. After execution, it summarizes the output, previews a pattern file, and factors to the listing the place the whole app has been saved.
def interactive_tinydev():
"""Interactive model the place you'll be able to strive your personal prompts"""
api_key = enter("🔑 Enter your Gemini API key: ").strip()
if not api_key:
print("❌ API key required!")
return
tiny_dev = TinyDev(api_key)
print("n🎮 Interactive TinyDev Mode")
print("Sort your app concepts and watch them come to life!")
whereas True:
immediate = enter("n💭 Describe your app (or 'give up'): ").strip()
if immediate.decrease() in ['quit', 'exit', 'q']:
print("👋 Goodbye!")
break
if immediate:
strive:
outcomes = tiny_dev.create_app(immediate, f"/content material/app_{hash(immediate) % 10000}")
print(f"✅ Success! Verify {outcomes['output_dir']}")
besides Exception as e:
print(f"❌ Error: {e}")
print("🎬 TinyDev - AI Code Generator Prepared!")
print("Impressed by smol-ai/developer, powered by free Gemini API")
print("nTo run demo: demo_tinydev()")
print("To strive interactive mode: interactive_tinydev()")
The interactive_tinydev() perform permits customers to generate functions from their customized prompts in actual time. After coming into a legitimate Gemini API key, customers can describe any app thought, and TinyDev will develop the whole mission, code, construction, and supporting recordsdata routinely. The method continues in a loop till the person varieties ‘give up’. This interactive mode permits hands-on experimentation and fast prototyping from pure language descriptions.
Lastly, calling demo_tinydev() runs a predefined demonstration of TinyDev utilizing a pattern app immediate. It walks by way of the complete workflow, planning, file construction creation, and code era, to showcase how the software routinely builds a whole software from a easy thought.
In conclusion, TinyDev class demonstrates the potential of utilizing AI to automate software scaffolding with outstanding accuracy and effectivity. By breaking down the code era course of into intuitive phases, it ensures that outputs are logically sound, well-structured, and aligned with the person’s intent. Whether or not you’re exploring new app concepts or searching for to speed up growth, TinyDev gives a light-weight and user-friendly answer powered by the Gemini fashions. It’s a sensible software for builders seeking to combine AI into their workflow with out pointless complexity or overhead.
Take a look at the Pocket book right here. All credit score for this analysis goes to the researchers of this mission. Additionally, be happy to observe us on Twitter and don’t neglect to affix our 100k+ ML SubReddit and Subscribe to our E-newsletter.
Sana Hassan, a consulting intern at Marktechpost and dual-degree scholar at IIT Madras, is captivated with making use of expertise and AI to deal with real-world challenges. With a eager curiosity in fixing sensible issues, he brings a contemporary perspective to the intersection of AI and real-life options.