Python SDK¶
PatchPal can be used programmatically from Python scripts or a REPL, giving you full agent capabilities with an easy-to-use Python SDK (Software Development Kit). PatchPal supports both human-in-the-loop workflows (default) and fully autonomous operation through Autopilot mode. By default, users maintain control through interactive permission prompts, making it ideal for code assistance, debugging, and automation tasks that benefit from human oversight. For fully autonomous iterative development, see the Autopilot documentation.
Complete API Reference
For detailed API documentation with all parameters, return types, and method signatures, see the API Reference section.
Basic Usage¶
from patchpal.agent import create_agent
# Create an agent (uses default model or PATCHPAL_MODEL env var)
agent = create_agent()
# Or specify a model explicitly
agent = create_agent(model_id="anthropic/claude-sonnet-4_5")
# Run the agent on a task
response = agent.run("List all Python files in this directory")
print(response)
# Continue the conversation (history is maintained)
response = agent.run("Now read the main agent file")
print(response)
Using Local Models Without Function Calling
For local models that struggle with native function calling (especially smaller Ollama models), use create_react_agent() instead:
from patchpal import create_react_agent
agent = create_react_agent(model_id="ollama_chat/llama3.2")
response = agent.run("List Python files")
Adding Custom Tools¶
Custom tools can be used in three ways:
- Global tools: Place
.pyfiles in~/.patchpal/tools/(auto-discovered at startup) - Repository-specific tools: Place
.pyfiles in<repo>/.patchpal/tools/(auto-discovered at startup) - Python API: Pass functions directly to
create_agent(custom_tools=[...])
All methods use the same tool schema auto-generation from Python functions with type hints and docstrings:
from patchpal.agent import create_agent
def calculator(x: int, y: int, operation: str = "add") -> str:
"""Perform basic arithmetic operations.
Args:
x: First number
y: Second number
operation: Operation to perform (add, subtract, multiply, divide)
Returns:
Result as a string
"""
if operation == "add":
return f"{x} + {y} = {x + y}"
elif operation == "subtract":
return f"{x} - {y} = {x - y}"
elif operation == "multiply":
return f"{x} * {y} = {x * y}"
elif operation == "divide":
if y == 0:
return "Error: Cannot divide by zero"
return f"{x} / {y} = {x / y}"
return "Unknown operation"
def get_weather(city: str, units: str = "celsius") -> str:
"""Get weather information for a city.
Args:
city: Name of the city
units: Temperature units (celsius or fahrenheit)
Returns:
Weather information string
"""
# Your implementation here (API call, etc.)
return f"Weather in {city}: 22°{units[0].upper()}, Sunny"
# Create agent with custom tools
agent = create_agent(
model_id="anthropic/claude-sonnet-4-5",
custom_tools=[calculator, get_weather]
)
# Use the agent - it will call your custom tools when appropriate
response = agent.run("What's 15 multiplied by 23?")
print(response)
response = agent.run("What's the weather in Paris?")
print(response)
Key Points: - Custom tools are automatically converted to LLM tool schemas - Functions should have type hints and Google-style docstrings - The agent will call your functions when appropriate - Tool execution follows the same permission system as built-in tools
Limiting Available Tools¶
You can control which built-in tools the agent has access to using the enabled_tools parameter. This is useful for creating specialized agents or restricting capabilities for security.
from patchpal.agent import create_agent
# Read-only analysis agent (cannot modify files)
read_only_agent = create_agent(
enabled_tools=["read_file", "read_lines", "code_structure", "get_repo_map"]
)
# Lightweight read-only agent with search (uses optional tools)
lightweight_agent = create_agent(
enabled_tools=["read_file", "read_lines", "find", "grep"]
)
# Code editor agent (no shell access)
editor_agent = create_agent(
enabled_tools=["read_file", "read_lines", "edit_file", "write_file"]
)
# Research assistant (web + reading only)
research_agent = create_agent(
enabled_tools=["read_file", "web_search", "web_fetch"]
)
# Minimal agent with custom tools
def my_calculator(x: int, y: int) -> str:
"""Add two numbers."""
return str(x + y)
minimal_agent = create_agent(
enabled_tools=["read_file"], # Only this built-in tool
custom_tools=[my_calculator] # Plus custom tools (always added)
)
Available Built-in Tools:
- read_file, read_lines, write_file, edit_file - File operations
- code_structure, get_repo_map - Code analysis
- run_shell - Shell command execution
- grep - Pattern search in files (disabled by default; shell commands preferred for most cases)
- find - Find files by glob pattern (disabled by default; faster than get_repo_map for simple file finding)
- web_search, web_fetch - Web access (if ENABLE_WEB=true)
- list_skills, use_skill - Skills system
- todo_add, todo_list, todo_complete, etc. - Task management
- ask_user - User interaction
Note: The grep and find tools are disabled by default (not included in the agent's tool list) but can be enabled via enabled_tools. They're useful for lightweight read-only agents that need search and navigation without run_shell access or expensive code parsing (get_repo_map).
See Configuration for the complete list and CLI usage via PATCHPAL_ENABLED_TOOLS environment variable.
Advanced Usage¶
from patchpal.agent import PatchPalAgent
# Create agent with custom configuration
agent = PatchPalAgent(model_id="anthropic/claude-sonnet-4-5")
# Set custom max iterations for complex tasks
response = agent.run("Refactor the entire codebase", max_iterations=200)
# Access conversation history
print(f"Messages in history: {len(agent.messages)}")
# Check context window usage
stats = agent.context_manager.get_usage_stats(agent.messages)
print(f"Token usage: {stats['total_tokens']:,} / {stats['context_limit']:,}")
print(f"Usage: {stats['usage_percent']}%")
# Manually trigger compaction if needed
if agent.context_manager.needs_compaction(agent.messages):
agent._perform_auto_compaction()
# Track API costs (cumulative token counts across session)
print(f"Total LLM calls: {agent.total_llm_calls}")
print(f"Cumulative input tokens: {agent.cumulative_input_tokens:,}")
print(f"Cumulative output tokens: {agent.cumulative_output_tokens:,}")
print(f"Total tokens: {agent.cumulative_input_tokens + agent.cumulative_output_tokens:,}")
Use Cases¶
- Interactive debugging: Use in Jupyter notebooks for hands-on debugging with agent assistance
- Automation scripts: Build scripts that use the agent for complex tasks with human oversight
- Custom workflows: Integrate PatchPal into your own tools and pipelines
- Code review assistance: Programmatic code analysis with permission controls
- Batch processing: Process multiple tasks programmatically while maintaining control
- Testing and evaluation: Test agent behavior with different prompts and configurations
Key Features¶
- Human-in-the-loop design: Permission prompts ensure human oversight (unlike fully autonomous frameworks)
- Stateful conversations: Agent maintains full conversation history
- Custom tools: Add your own Python functions (via CLI auto-discovery or API parameter) with automatic schema generation
- Automatic context management: Auto-compaction works the same as CLI
- All built-in tools available: File operations, git, web search, skills, etc.
- Model flexibility: Works with any LiteLLM-compatible model
- Token tracking: Monitor API usage and costs in real-time
- Environment variables respected: All
PATCHPAL_*settings apply
PatchPal vs. Other Agent Frameworks¶
PatchPal is designed to support both human-in-the-loop workflows (default) and fully autonomous operation via Autopilot mode:
| Feature | PatchPal (Interactive) | PatchPal (Autopilot) | Autonomous Frameworks |
|---|---|---|---|
| Design Philosophy | Human oversight & control | Autonomous iteration | Autonomous execution |
| Permission System | Interactive prompts for sensitive operations | Disabled (sandbox only) | Typically no prompts |
| Primary Use Case | Code assistance, debugging, interactive tasks | Iterative development, batch tasks | Automated workflows, batch processing |
| Safety Model | Write boundary protection, command blocking | Sandboxed environments required | Varies by framework |
| Custom Tools | Yes, with automatic schema generation | Yes, same tools as interactive | Yes (varies by framework) |
| Best For | Developers who want AI assistance with control | Throwaway projects, rapid prototyping | Automation, research, agent benchmarks |
The Python API uses the same agent implementation as the CLI, so you get the complete feature set including permissions, safety guardrails, and context management.