Skip to main content

A lightweight Python coding agent that writes, executes, and iterates on code through natural language instructions

Project description

Agentic Python Coder

Python 3.13 License: Apache 2.0 UV LangGraph

A Python coding agent using the ReAct framework with a persistent IPython kernel. Works as a CLI tool or as a Python library for integration into your own applications.

For details on architecture and constraint modelling applications, see [Szeider 2025, arxiv-2508.07468].

Installation

Prerequisites

  • Python 3.13
  • UV package manager: curl -LsSf https://astral.sh/uv/install.sh | sh
  • OpenRouter API key from openrouter.ai

CLI Installation

# Install as CLI tool
uv tool install agentic-python-coder

# Set up API key
mkdir -p ~/.config/coder
echo 'OPENROUTER_API_KEY="your-key-here"' > ~/.config/coder/.env

Library Installation

# Add to your project
uv add agentic-python-coder

# Or with pip
uv pip install agentic-python-coder

API key options:

  • Pass directly: solve_task(..., api_key="sk-or-...")
  • Environment variable: export OPENROUTER_API_KEY="sk-or-..."
  • Config file: ~/.config/coder/.env (same as CLI)

Quick Start

CLI Usage

# Simple task
coder "Create a function that calculates factorial"

# Task from file
coder --task problem.md

# Initialize example templates (one-time)
coder --init

# With packages and project template
coder --with cpmpy --project coder-examples/cpmpy/cpmpy.md "Solve 8-queens"

Library Usage

import agentic_python_coder as coder

# High-level: run a complete task
messages, stats, log_path = coder.solve_task(
    "Write a fibonacci function",
    working_directory="/tmp/workspace",
    model="sonnet45",
    quiet=True,  # Suppress console output
)

# Get the final response
response = coder.get_final_response(messages)
print(response)

API Reference

solve_task() — High-Level API

Run a complete coding task end-to-end. Recommended for most use cases.

from agentic_python_coder import solve_task

messages, stats, log_path = solve_task(
    task="Your task description",
    working_directory=".",           # Where to run and save files
    model=None,                      # Model name: "sonnet45", "opus45", or JSON file
    system_prompt=None,              # Custom system prompt (string)
    system_prompt_path=None,         # Path to system prompt file
    project_prompt=None,             # Domain-specific context
    with_packages=None,              # ["pandas", "numpy"] for dynamic install
    api_key=None,                    # Override API key
    todo=False,                      # Enable todo_write tool
    quiet=False,                     # Suppress console output
    save_log=True,                   # Save conversation log
    task_basename=None,              # Base name for output files
    step_limit=None,                 # Max agent steps (default: 200)
)

Returns: (messages, stats, log_path)

  • messages: List of agent messages
  • stats: Dict with tool_usage, token_consumption, execution_time_seconds
  • log_path: Path to saved log file (or None if save_log=False)

create_coding_agent() / run_agent() — Low-Level API

For custom workflows, multi-turn conversations, or fine-grained control.

from agentic_python_coder import create_coding_agent, run_agent, get_final_response

# Create agent
agent = create_coding_agent(
    working_directory="/tmp/workspace",
    system_prompt="You are a Python expert.",
    model="deepseek31",
    with_packages=["pandas"],
)

# Run one or more turns
messages, stats = run_agent(agent, "Load data.csv", quiet=True)
messages2, stats2 = run_agent(agent, "Now plot column A", quiet=True)

# Extract response
print(get_final_response(messages2))

get_openrouter_llm() — LLM Access

Get a configured LangChain LLM instance for custom use.

from agentic_python_coder import get_openrouter_llm, list_available_models

# Get LLM by model name
llm = get_openrouter_llm(model="sonnet45")

# See available models
print(list_available_models())
# ['deepseek31', 'gemini25', 'gpt5', 'grok41', 'opus45', 'qwen3', 'sonnet45']

# Use a custom model JSON file
llm = get_openrouter_llm(model="./mymodel.json")

CLI Reference

Basic Commands

# Inline task
coder "your task"

# Task from file (creates {basename}_code.py and {basename}.jsonl)
coder --task problem.md

# Specify working directory
coder --dir results/test1 "your task"

# Interactive mode
coder -i

Options

Flag Description
--version, -V Show version and exit
--init [TEMPLATE] Initialize example templates (cpmpy, clingo, regex, or all)
--task, -t FILE Load task from markdown file
--model MODEL Model name or JSON file (default: sonnet45)
--project, -p FILE Project template for domain-specific prompts
--with PACKAGE Add packages dynamically (repeatable)
--dir, -d DIR Working directory
--api-key KEY Override API key
--todo Enable task tracking tool
--quiet, -q Suppress console output
--step-limit N Max agent steps (default: 200)
-i, --interactive Interactive conversation mode

Model Selection

# Built-in models (versioned names)
coder --model sonnet45 "task"   # Claude Sonnet 4.5 (default)
coder --model opus45 "task"     # Claude Opus 4.5
coder --model deepseek31 "task" # DeepSeek v3.1
coder --model grok41 "task"     # X.AI Grok 4.1
coder --model qwen3 "task"      # Qwen3 Coder
coder --model gemini25 "task"   # Gemini Pro 2.5
coder --model gpt5 "task"       # GPT-5

# Custom model (JSON file)
coder --model ./mymodel.json "task"

Project Templates

Domain-specific templates improve results. First, initialize the examples:

# Initialize all example templates (creates coder-examples/ directory)
coder --init

# Or initialize only specific templates
coder --init cpmpy

Then use them:

# Constraint programming
coder --with cpmpy --project coder-examples/cpmpy/cpmpy.md "Solve 8-queens"

# Run a sample task
coder --with cpmpy --project coder-examples/cpmpy/cpmpy.md \
      --task coder-examples/cpmpy/sample_tasks/n_queens.md

# Answer Set Programming
coder --with clingo --project coder-examples/clingo/clingo.md "Model bird flight"

Interactive Mode

Interactive mode (-i) maintains a persistent session for multi-turn conversations:

# Start interactive session
coder -i

# With project template
coder -i --project coder-examples/cpmpy/cpmpy.md --with cpmpy

Features:

  • Persistent IPython kernel (state preserved across turns)
  • Type exit or quit to end session
  • Cumulative statistics shown on exit
  • Conversation log saved to log.jsonl

Example session:

$ coder -i
Interactive mode - working in: /path/to/dir
Type 'exit' or 'quit' to stop.

You: Load data.csv and show the columns
Agent working...
[Agent loads file, displays columns]

You: Plot the 'sales' column
Agent working...
[Agent creates plot using existing dataframe]

You: exit
Goodbye!
Log saved to: log.jsonl

Configuration

API Key

The agent looks for API key in order:

  1. --api-key flag or api_key parameter
  2. ~/.config/coder/.env file
  3. OPENROUTER_API_KEY environment variable
# Recommended: one-time setup
mkdir -p ~/.config/coder
echo 'OPENROUTER_API_KEY="sk-or-v1-..."' > ~/.config/coder/.env

Environment Variables

Variable Description
OPENROUTER_API_KEY API key for OpenRouter
CODER_VERBOSE Show detailed model configuration
CODER_WITH_PACKAGES Comma-separated packages (internal use)

How It Works

  1. Task is parsed and sent to the LLM
  2. Agent reasons about approach using ReAct framework
  3. Code executes in persistent IPython kernel (state preserved)
  4. Errors detected and fixed automatically
  5. Solution refined until complete

Output Files

  • Inline tasks: solution.py + log.jsonl
  • File tasks: {basename}_code.py + {basename}.jsonl

Security Notice

This is experimental software. The agent executes code automatically.

  • Run in a VM or container for untrusted inputs
  • Code executes in the working directory
  • Use isolated environments for sensitive projects

License

Apache License 2.0 - see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agentic_python_coder-2.1.0.tar.gz (79.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agentic_python_coder-2.1.0-py3-none-any.whl (68.0 kB view details)

Uploaded Python 3

File details

Details for the file agentic_python_coder-2.1.0.tar.gz.

File metadata

File hashes

Hashes for agentic_python_coder-2.1.0.tar.gz
Algorithm Hash digest
SHA256 18167fa45a6cf92b85a3d2abcd8951d746c840546105c20b5197c62b5f74be54
MD5 0011739f407aa12abadc31533821c237
BLAKE2b-256 3a602ff0dd46e9a1baa01e7271486696575e7cd15d155180734aeeb882186d41

See more details on using hashes here.

File details

Details for the file agentic_python_coder-2.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agentic_python_coder-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 11a58c692d2593aba770a2c6139c2b77a0c13366b530e7d7acd7eb87590c275e
MD5 75370c3fdc1dfc85f3444b77a73aed11
BLAKE2b-256 64ad340fc308b87f53ff5f926e0f7d87ece1f8f1271212d431df7e6e900ac6eb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page