Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      8 Key Questions Every CEO Should Ask Before Hiring a Node.js Development Company in 2025

      July 11, 2025

      Vibe Loop: AI-native reliability engineering for the real world

      July 10, 2025

      Docker Compose gets new features for building and running agents

      July 10, 2025

      Why Enterprises Are Choosing AI-Driven React.js Development Companies in 2025

      July 10, 2025

      This discounted SSD fixed my gaming handheld’s biggest weakness — Extra storage space for Steam Deck, ASUS ROG Ally, and Lenovo Legion Go

      July 11, 2025

      These are the 5 Prime Day deals I’d buy if I weren’t about to have a baby

      July 11, 2025

      OpenAI’s $6.5 billion purchase fuels Sam Altman’s quest to build next-gen computers for “transcendentally good” AI — The biggest tech disruption since the iPhone?

      July 11, 2025

      Don’t miss out on the best ROG Ally accessory deals going on now — Improve your gaming handheld PC with a microSD card, power bank, dock, and more

      July 11, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Regolith – A JavaScript library immune to ReDoS attacks

      July 11, 2025
      Recent

      Regolith – A JavaScript library immune to ReDoS attacks

      July 11, 2025

      Create Your Own Redux: Build a Custom State Management in React

      July 11, 2025

      Perficient Nagpur Celebrates Contentstack Implementation Certification Success!

      July 11, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      This discounted SSD fixed my gaming handheld’s biggest weakness — Extra storage space for Steam Deck, ASUS ROG Ally, and Lenovo Legion Go

      July 11, 2025
      Recent

      This discounted SSD fixed my gaming handheld’s biggest weakness — Extra storage space for Steam Deck, ASUS ROG Ally, and Lenovo Legion Go

      July 11, 2025

      These are the 5 Prime Day deals I’d buy if I weren’t about to have a baby

      July 11, 2025

      OpenAI’s $6.5 billion purchase fuels Sam Altman’s quest to build next-gen computers for “transcendentally good” AI — The biggest tech disruption since the iPhone?

      July 11, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»Building AI-Powered Applications Using the Plan → Files → Code Workflow in TinyDev

    Building AI-Powered Applications Using the Plan → Files → Code Workflow in TinyDev

    June 15, 2025

    In this tutorial, we introduce TinyDev class implementation, a minimal yet powerful AI code generation tool that utilizes the Gemini API to transform simple app ideas into comprehensive, structured applications. Designed to run effortlessly in Notebook, TinyDev follows a clean three-phase workflow—Plan → Files → Code—to ensure consistency, functionality, and modular design. Whether building a web interface, a Python backend, or a utility script, TinyDev allows users to describe their project in natural language & receive ready-to-run code files, automatically generated and saved in an organized directory. This makes it an ideal starting point for rapid prototyping or learning how AI can assist in development tasks.

    Copy CodeCopiedUse a different Browser
    import google.generativeai as genai
    import os
    import json
    import re
    from pathlib import Path
    from typing import List, Dict

    We begin by importing essential libraries required for the TinyDev code generator. google.generativeai is used to interact with the Gemini API, while standard libraries like os, json, and re support file handling and text processing. Path and type hints from typing ensure clean file operations and better code readability.

    Copy CodeCopiedUse a different Browser
    class TinyDev:
       """
       TinyDev: A lightweight AI code generator inspired by smol-dev
       Uses Gemini API to generate complete applications from simple prompts
       Follows the proven three-phase workflow: Plan → Files → Code
       """
      
       def __init__(self, api_key: str, model: str = "gemini-1.5-flash"):
           genai.configure(api_key=api_key)
           self.model = genai.GenerativeModel(model)
           self.generation_config = {
               'temperature': 0.1,
               'top_p': 0.8,
               'max_output_tokens': 8192,
           }
      
       def plan(self, prompt: str) -> str:
           """
           Phase 1: Generate project plan and shared dependencies
           Creates the foundation for consistent code generation
           """
           planning_prompt = f"""As an AI developer, you’re building a tool that automatically generates code tailored to the user’s needs.
    
    
    the program you are writing is based on the following description:
    {prompt}
    
    
    the files we write will be generated by a python script. the goal is for us to all work together to write a program that will write the code for the user.
    
    
    since we are working together, we need to understand what our shared dependencies are. this includes:
    - import statements we all need to use
    - variable names that are shared between files
    - functions that are called from one file to another
    - any other shared state
    
    
    this is the most critical part of the process, if we don't get this right, the generated code will not work properly.
    
    
    please output a markdown file called shared_dependencies.md that lists all of the shared dependencies.
    
    
    the dependencies should be organized as:
    1. shared variables (globals, constants)
    2. shared functions (function signatures)
    3. shared classes (class names and key methods)
    4. shared imports (modules to import)
    5. shared DOM element ids (if web project)
    6. shared file paths/names
    
    
    be EXHAUSTIVE in your analysis. every file must be able to import or reference these shared items."""
    
    
           response = self.model.generate_content(
               planning_prompt,
               generation_config=self.generation_config
           )
           return response.text
    
    
       def specify_file_paths(self, prompt: str, shared_deps: str) -> List[str]:
           """
           Phase 2: Determine what files need to be created
           """
           files_prompt = f"""As an AI developer, you’re building a tool that automatically generates code tailored to the user’s needs.
    
    
    the program:
    {prompt}
    
    
    the shared dependencies:
    {shared_deps}
    
    
    Based on the program description and shared dependencies, return a JSON array of the filenames that should be written.
    
    
    Only return the JSON array, nothing else. The JSON should be an array of strings representing file paths.
    
    
    For example, for a simple web app you might return:
    ["index.html", "styles.css", "script.js"]
    
    
    For a Python project you might return:
    ["main.py", "utils.py", "config.py", "requirements.txt"]
    
    
    JSON array:"""
    
    
           response = self.model.generate_content(
               files_prompt,
               generation_config=self.generation_config
           )
          
           try:
               json_match = re.search(r'[.*?]', response.text, re.DOTALL)
               if json_match:
                   files = json.loads(json_match.group())
                   return [f for f in files if isinstance(f, str)]
               else:
                   lines = [line.strip() for line in response.text.split('n') if line.strip()]
                   files = []
                   for line in lines:
                       if '.' in line and not line.startswith('#'):
                           file = re.sub(r'[^w-_./]', '', line)
                           if file:
                               files.append(file)
                   return files[:10] 
           except Exception as e:
               print(f"Error parsing files: {e}")
               return ["main.py", "README.md"]
    
    
       def generate_code_sync(self, prompt: str, shared_deps: str, filename: str) -> str:
           """
           Phase 3: Generate code for individual files
           """
           code_prompt = f"""As an AI developer, you’re building a tool that automatically generates code tailored to the user’s needs..
    
    
    the program:
    {prompt}
    
    
    the shared dependencies:
    {shared_deps}
    
    
    Please write the file {filename}.
    
    
    Remember that your job is to write the code for {filename} ONLY. Do not write any other files.
    
    
    the code should be fully functional. meaning:
    - all imports should be correct
    - all variable references should be correct 
    - all function calls should be correct
    - the code should be syntactically correct
    - the code should be logically correct
    
    
    Make sure to implement every part of the functionality described in the program description.
    
    
    DO NOT include ``` code fences in your response. Return only the raw code.
    
    
    Here is the code for {filename}:"""
    
    
           response = self.model.generate_content(
               code_prompt,
               generation_config=self.generation_config
           )
          
           code = response.text
           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, prompt: str, output_dir: str = "/content/generated_app") -> Dict:
           """
           Main workflow: Transform a simple prompt into a complete application
           """
           print(f"🚀 TinyDev workflow starting...")
           print(f"📝 Prompt: {prompt}")
          
           print("n📋 Step 1: Planning shared dependencies...")
           shared_deps = self.plan(prompt)
           print("✅ Dependencies planned")
          
           print("n📁 Step 2: Determining file structure...")
           file_paths = self.specify_file_paths(prompt, shared_deps)
           print(f"📄 Files to generate: {file_paths}")
          
           Path(output_dir).mkdir(parents=True, exist_ok=True)
          
           print(f"n⚡ Step 3: Generating {len(file_paths)} files...")
           results = {
               'prompt': prompt,
               'shared_deps': shared_deps,
               'files': {},
               '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"  🔧 Generating {filename}...")
               try:
                   code = self.generate_code_sync(prompt, shared_deps, filename)
                  
                   file_path = Path(output_dir) / filename
                   file_path.parent.mkdir(parents=True, exist_ok=True)
                  
                   with open(file_path, 'w', encoding='utf-8') as f:
                       f.write(code)
                  
                   results['files'][filename] = code
                   print(f"  ✅ {filename} created ({len(code)} chars)")
                  
               except Exception as e:
                   print(f"  ❌ Error generating {filename}: {e}")
                   results['files'][filename] = f"# Error: {e}"
          
           readme = f"""# Generated by TinyDev (Gemini-Powered)
    
    
    ## Original Prompt
    {prompt}
    
    
    ## Generated Files
    {chr(10).join(f'- {f}' for f in file_paths)}
    
    
    ## About TinyDev
    TinyDev is inspired by smol-ai/developer but uses free Gemini API.
    It follows the proven three-phase workflow: Plan → Files → Code
    
    
    ## Usage
    Check individual files for specific usage instructions.
    
    
    Generated on: {os.popen('date').read().strip()}
    """
          
           with open(Path(output_dir) / "README.md", 'w') as f:
               f.write(readme)
          
           print(f"n🎉 Complete! Generated {len(results['files'])} files in {output_dir}")
           return results

    The TinyDev class encapsulates the full logic of an AI-powered code generator using the Gemini API. It implements a structured three-phase workflow: first, it analyzes the user prompt to generate shared dependencies (plan); next, it identifies which files are needed for the application (specify_file_paths); and finally, it generates functional code for each file individually (generate_code_sync). The create_app method brings everything together by orchestrating the full app generation pipeline and saving the results, including code files and a detailed README, into a specified output directory, offering a complete, ready-to-use application scaffold from a single prompt.

    Copy CodeCopiedUse a different Browser
    def demo_tinydev():
       """Demo the TinyDev code generator"""
      
       api_key = "Use Your API Key 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("Inspired by smol-ai/developer, powered by Gemini API")
       print(f"Available demo projects:")
      
       for i, prompt in enumerate(demo_prompts, 1):
           print(f"{i}. {prompt}")
      
       demo_prompt = demo_prompts[0] 
       print(f"n🎯 Running demo: {demo_prompt}")
      
       try:
           results = tiny_dev.create_app(demo_prompt)
          
           print(f"n📊 Results Summary:")
           print(f"  📝 Prompt: {results['prompt']}")
           print(f"  📁 Output: {results['output_dir']}")
           print(f"  📄 Files: {len(results['files'])}")
          
           print(f"n📋 Generated Files:")
           for filename in results['files'].keys():
               print(f"  - {filename}")
          
           if results['files']:
               preview_file = list(results['files'].keys())[0]
               preview_code = results['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 uses the same proven workflow as smol-ai/developer!")
           print(f"📂 Check {results['output_dir']} for all generated files")
          
           return results
          
       except Exception as e:
           print(f"❌ Demo failed: {e}")
           return None

    The demo_tinydev() function showcases TinyDev’s capabilities by running a predefined demo using one of several sample prompts, such as generating a Tic Tac Toe game or a Python news scraper. It initializes the TinyDev class with a Gemini API key, selects the first prompt from a list of project ideas, and guides the user through the full code generation pipeline, including planning shared dependencies, defining file structure, and generating code. After execution, it summarizes the output, previews a sample file, and points to the directory where the complete app has been saved.

    Copy CodeCopiedUse a different Browser
    def interactive_tinydev():
       """Interactive version where you can try your own prompts"""
       api_key = input("🔑 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("Type your app ideas and watch them come to life!")
      
       while True:
           prompt = input("n💭 Describe your app (or 'quit'): ").strip()
          
           if prompt.lower() in ['quit', 'exit', 'q']:
               print("👋 Goodbye!")
               break
          
           if prompt:
               try:
                   results = tiny_dev.create_app(prompt, f"/content/app_{hash(prompt) % 10000}")
                   print(f"✅ Success! Check {results['output_dir']}")
               except Exception as e:
                   print(f"❌ Error: {e}")
    
    
    print("🎬 TinyDev - AI Code Generator Ready!")
    print("Inspired by smol-ai/developer, powered by free Gemini API")
    print("nTo run demo: demo_tinydev()")
    print("To try interactive mode: interactive_tinydev()")

    The interactive_tinydev() function allows users to generate applications from their custom prompts in real time. After entering a valid Gemini API key, users can describe any app idea, and TinyDev will develop the complete project, code, structure, and supporting files automatically. The process continues in a loop until the user types ‘quit’. This interactive mode enables hands-on experimentation and rapid prototyping from natural language descriptions.

    Copy CodeCopiedUse a different Browser
    demo_tinydev()

    Finally, calling demo_tinydev() runs a predefined demonstration of TinyDev using a sample app prompt. It walks through the full workflow, planning, file structure creation, and code generation, to showcase how the tool automatically builds a complete application from a simple idea.

    In conclusion, TinyDev class demonstrates the potential of using AI to automate application scaffolding with remarkable accuracy and efficiency. By breaking down the code generation process into intuitive phases, it ensures that outputs are logically sound, well-structured, and aligned with the user’s intent. Whether you’re exploring new app ideas or seeking to accelerate development, TinyDev provides a lightweight and user-friendly solution powered by the Gemini models. It’s a practical tool for developers looking to integrate AI into their workflow without unnecessary complexity or overhead.


    Check out the Notebook here. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter.

    The post Building AI-Powered Applications Using the Plan → Files → Code Workflow in TinyDev appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleOThink-R1: A Dual-Mode Reasoning Framework to Cut Redundant Computation in LLMs
    Next Article AI-Generated Ad Created with Google’s Veo3 Airs During NBA Finals, Slashing Production Costs by 95%

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    July 11, 2025
    Machine Learning

    Build an MCP application with Mistral models on AWS

    July 10, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    A Brief Introduction to Web Components

    Development

    US infrastructure could crumble under cyberattack, ex-NSA advisor warns

    Security

    CVE-2025-4122 – Netgear JWNR2000 Command Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    3AM ransomware attack poses as a call from IT support to compromise networks

    Development

    Highlights

    CVE-2025-4499 – Simple Hospital Management System Buffer Overflow

    May 10, 2025

    CVE ID : CVE-2025-4499

    Published : May 10, 2025, 12:15 p.m. | 3 hours, 24 minutes ago

    Description : A vulnerability classified as critical was found in code-projects Simple Hospital Management System 1.0. Affected by this vulnerability is the function Add of the component Add Information. The manipulation of the argument x[i].name/x[i].disease leads to stack-based buffer overflow. The attack needs to be approached locally. The exploit has been disclosed to the public and may be used.

    Severity: 5.3 | MEDIUM

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    Canonical Announce Big Changes to Ubuntu Summit

    May 27, 2025

    CVE-2025-53637 – Meshtastic Code Injection Vulnerability

    July 10, 2025

    Iran-Linked BladedFeline Hits Iraqi and Kurdish Targets with Whisper and Spearal Malware

    June 5, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.