Open Source Coding Agent

TinyCodeAgent

Build your own Cursor alternative or automate complex tasks with AI-powered coding. Features GPT-5 & Claude-4 support, sandboxed file operations, enhanced shell tools, TodoWrite task management, and secure execution environments (Seatbelt/Modal).

MIT License
Python 3.8+
GPT-5 & Claude-4
Sandboxed File Tools
Enhanced Shell Tool

Get Started in Minutes

Install TinyCodeAgent and start building with AI

Installation

pip install tinyagent-py

Basic Usage

import asyncio
from tinyagent import TinyCodeAgent

async def main():
    # Initialize with new features
    agent = TinyCodeAgent(
        model="gpt-4o-mini",  # or "gpt-5", "claude-4"
        api_key="your-api-key",
        provider="seatbelt",  # or "modal" for cloud
        
        # Enable new tools
        enable_file_tools=True,      # read_file, write_file, update_file, glob, grep
        enable_shell_tool=True,      # Enhanced bash tool
        enable_todo_write=True,      # Task management
        
        # Auto git checkpoints
        auto_git_checkpoint=True,
        
        # Rich terminal UI
        ui="rich"
    )
    
    try:
        result = await agent.run("""
        I need to analyze and refactor a Python project:
        1. Use glob to find all Python files
        2. Use grep to identify functions needing refactoring  
        3. Create a refactoring plan with todos
        4. Implement improvements with file operations
        """)
        print(result)
    finally:
        await agent.close()

asyncio.run(main())

Works with Any LLM Model

Powered by LiteLLM - choose the best model for your coding tasks

OpenAI

gpt-5, gpt-4o, gpt-4o-mini, gpt-4, gpt-3.5-turbo

Anthropic

claude-4, claude-3-5-sonnet, claude-3-opus, claude-3-haiku

Google

gemini-pro, gemini-1.5-pro, gemini-1.5-flash

Others

Moonshot Kimi-k2, Cohere, Llama, and 100+ more

Model Switching Examples

GPT-5 (Latest & Best)

agent = TinyCodeAgent(
  model="gpt-5",
  api_key="your-openai-key"
)

Claude-4 (Latest & Advanced)

agent = TinyCodeAgent(
  model="claude-4",
  api_key="your-anthropic-key"
)

Gemini 1.5 Pro (Large Context)

agent = TinyCodeAgent(
  model="gemini-1.5-pro",
  api_key="your-gemini-key"
)

Moonshot Kimi (Cost Effective)

agent = TinyCodeAgent(
  model="moonshot/moonshot-v1-8k",
  api_key="your-moonshot-key"
)

Enhanced Coding Features

Advanced file operations, shell tools, task management, and the latest AI models

Sandboxed File Tools

Native read_file, write_file, update_file, glob, grep tools with provider sandbox security

Enhanced Shell Tool

Improved bash tool with safety validation, platform-specific tips, and provider-backed execution

TodoWrite Tool

Built-in task management system for tracking complex workflows and organizing progress

Auto Git Checkpoints

Automatic version control after shell commands with descriptive commit messages

Universal Tool Hooks

Control any tool execution via before_tool_execution/after_tool_execution callbacks

Provider System

Pluggable execution backends: Seatbelt (local sandbox), Modal.com (cloud), with unified API

GPT-5 & Claude-4 Ready

Latest AI models including GPT-5, Claude-4, with 100+ models via LiteLLM

Secure Code Execution

Run AI-generated code safely in sandboxed environments

Sandboxed Execution

import asyncio
from tinyagent import TinyCodeAgent
from tinyagent.code_agent.tools.file_tools import ProductionApprovalHook

async def main():
    # Enhanced security with file operation controls
    agent = TinyCodeAgent(
        model="gpt-4o-mini",
        api_key="your-api-key",
        provider="modal",  # Cloud execution
        
        # Provider-specific config
        provider_config={
            "pip_packages": ["pandas", "matplotlib", "seaborn"],
            "bypass_shell_safety": False  # Strict for cloud
        },
        
        # Enhanced tools
        enable_file_tools=True,
        enable_shell_tool=True,
        enable_todo_write=True,
        
        authorized_imports=["pandas", "matplotlib.*", "seaborn.*"]
    )
    
    # Add file operation approval hook
    approval_hook = ProductionApprovalHook()
    agent.add_callback(approval_hook)
    
    try:
        result = await agent.run("""
        Comprehensive data analysis workflow:
        1. Use glob to find all CSV files in project
        2. Read and analyze sales data with file tools
        3. Create visualizations with enhanced shell commands
        4. Track progress with todos
        """)
        print(result)
    finally:
        await agent.close()

asyncio.run(main())

Stateful Python Environment

Maintain context across multiple code executions

Persistent Sessions

import asyncio
import os
from tinyagent.code_agent import TinyCodeAgent

async def main():
    # Code agent with persistent variables and environment
    agent = TinyCodeAgent(
        model="o4-mini",
        api_key=os.environ['OPENAI_API_KEY'],
        provider="modal",
        user_variables={
            "database_url": "postgresql://user:pass@localhost/mydb",
            "api_keys": {"aws": "key123", "stripe": "sk_123"}
        }
    )
    
    try:
        # Variables persist across runs - analyze quarterly data
        await agent.run("""
        import pandas as pd
        df_q1 = pd.read_csv('sales_q1.csv')
        total_q1 = df_q1['revenue'].sum()
        print(f'Q1 Revenue: ${total_q1:,.2f}')
        """)
        
        # Previous variables still available
        await agent.run("""
        df_q2 = pd.read_csv('sales_q2.csv') 
        total_q2 = df_q2['revenue'].sum()
        growth = ((total_q2 - total_q1) / total_q1) * 100
        print(f'Q2 Growth: {growth:.1f}%')
        """)
    finally:
        await agent.close()

asyncio.run(main())

Computer Interaction Examples

Build Cursor alternatives and automate complex computer tasks

Build Your Own Cursor Alternative

import asyncio
import os
from tinyagent.code_agent import TinyCodeAgent

async def main():
    # AI-powered code editor alternative
    agent = TinyCodeAgent(
        model="o4-mini",
        api_key=os.environ['OPENAI_API_KEY'],
        provider="modal",
        pip_packages=["black", "mypy", "flake8"],
        default_workdir=os.getcwd()
    )
    
    try:
        # Intelligent code editing and refactoring
        result = await agent.run("""
        I have a Python Flask API in 'app.py' that needs improvement:
        
        1. Read the current file and analyze its structure
        2. Add proper type hints to all functions
        3. Implement error handling for database operations
        4. Add input validation for API endpoints
        5. Format with black and check with flake8
        6. Create comprehensive docstrings
        7. Save the improved version
        
        Show me a summary of changes made.
        """)
        print(result)
    finally:
        await agent.close()

asyncio.run(main())

Accounting Data Analysis with GradioUI

import asyncio
import os
import pandas as pd
from tinyagent.code_agent import TinyCodeAgent
from tinyagent.hooks.gradio_callback import GradioCallback
from tinyagent.hooks.logging_manager import LoggingManager
import logging

async def main():
    # Configure for accounting data analysis
    agent = TinyCodeAgent(
        model="o4-mini",
        api_key=os.environ['OPENAI_API_KEY'],
        pip_packages=["pandas"],
        provider_config={
            "pip_packages": ["gradio"]
        }
    )
    
    # Setup Gradio UI with logging
    log_manager = LoggingManager(default_level=logging.INFO)
    gradio_ui = GradioCallback(
        show_thinking=True,
        show_tool_calls=True
    )
    agent.add_callback(gradio_ui)
    
    # Load bank account data
    df = pd.read_csv("Corporate_account_2022-04-15-2025-06-15.csv", 
                     encoding='latin1', delimiter=';')
    
    # Pass dataframe to Python environment
    agent.set_user_variables(dict(df=df))
    
    try:
        result = await agent.run("""
        df is an export of a bank account for my company.
        I need to extract all payments to AWS (Amazon Web Services):
        - Total amount of payments to AWS
        - Total payments to AWS in each year
        - List transactions that might be typos or worth reviewing
        
        You have access to df variable in your python environment.
        """, max_turns=20)
        print(result)
    finally:
        await agent.close()

asyncio.run(main())

Restaurant Research Automation (Real Story)

Real Story: A friend needed restaurant data from a legacy website that couldn't be filtered by Google Maps reviews or pricing. TinyCodeAgent extracted the data and enriched it with Google Maps API in just 10 lines!

# Real-world example: Restaurant research automation
# Extract data from website + Google Maps API analysis in 10 lines
from tinyagent import TinyCodeAgent
import os
import asyncio

agent = TinyCodeAgent(
    model="o4-mini",
    api_key=os.environ.get("OPENAI_API_KEY"),
    ui="jupyter",
    authorized_imports=["json","pandas","requests"],
    local_execution=True,
)

async def run_example(page_content):
    GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY")

    response = await agent.run(f"""
    Extract restaurant data from this Toronto website source:
    1. Get names, addresses, phone numbers
    2. Use Google Maps API for reviews/ratings  
    3. Sort by quality (reviews + rating combination)
    4. Export to CSV
    
    API Key: {GOOGLE_MAPS_API_KEY}
    
    <page_source>
    Restaurant Name | Address | Telephone
    1 Kitchen | 550 Wellington St W | 416-601-3533
    12 Tables | 1552 Avenue Rd | 416-590-7819
    612 Harlowe | 612 Richmond St W | 416-637-9998
    # ... more restaurants
    </page_source>
    """)
    
    # Agent automatically creates 'df' variable with results
    df = agent.code_provider._globals_dict['df']
    df.to_csv("restaurants_analyzed.csv")
    
asyncio.run(run_example(page_content))

Perfect For

Ideal use cases for TinyCodeAgent

🖥️ Computer Interaction

  • • Build custom AI code editors (Cursor alternatives)
  • • Automate complex spreadsheet operations
  • • Create intelligent file management systems
  • • Develop AI-powered desktop applications

📊 Data Analysis

  • • Automated data cleaning and preprocessing
  • • Statistical analysis and visualization
  • • Machine learning model development
  • • Report generation with charts and insights

⚡ Prototyping

  • • Rapid API development and testing
  • • Algorithm implementation and optimization
  • • Database schema design and queries
  • • Integration testing and validation

🤖 Automation

  • • Workflow automation scripts
  • • System administration tasks
  • • Data pipeline development
  • • Testing and quality assurance

Start Coding with AI Today

Build, test, and deploy code with the power of AI. TinyCodeAgent makes it secure and simple.