Build agents that write and execute Python code using dspy.CodeAct. Useful for computation, data analysis, and multi-step logic better expressed as code than tool calls.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through building DSPy agents that solve problems by generating and running Python code, rather than calling tools through a fixed interface.
Ask the user before writing code:
max_iters choice.dspy.CodeAct is a DSPy module that creates agents which write Python code to accomplish tasks. Instead of selecting from a predefined set of tool calls (like ReAct), CodeAct generates executable code snippets that use provided tools as Python functions.
The agent works in a loop:
CodeAct inherits from both ReAct and ProgramOfThought, combining reasoning-and-acting with code generation.
| ReAct | CodeAct | |
|---|---|---|
| How it acts | Calls tools by name with arguments | Writes Python code that calls tools |
| Composition | One tool call per step | Can chain multiple tool calls, use loops, variables, conditionals in a single step |
| Data manipulation | Limited to what tools return | Can transform, filter, aggregate data in code |
| Best for | Simple tool orchestration | Complex computation, data processing, multi-step logic |
| Overhead | Lower -- just picks a tool | Higher -- generates and executes code |
Rule of thumb: If your agent needs to do math, transform data, or chain several operations together, CodeAct is a better fit. If it just needs to look things up and combine results, ReAct is simpler.
Use CodeAct when the agent needs computation, data transformation, or multi-step logic — see the decision table at the bottom of this skill for scenario-by-scenario guidance.
Avoid CodeAct when:
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# Define tools as pure functions with type hints and docstrings
def factorial(n: int) -> int:
"""Calculate the factorial of n."""
if n <= 1:
return 1
return n * factorial(n - 1)
def fibonacci(n: int) -> int:
"""Return the nth Fibonacci number."""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Create the CodeAct agent
agent = dspy.CodeAct(
"question -> answer",
tools=[factorial, fibonacci],
max_iters=5,
)
result = agent(question="What is the factorial of 10 plus the 15th Fibonacci number?")
print(result.answer)
dspy.CodeAct(
signature, # str or dspy.Signature -- defines input/output fields
tools, # list[callable] -- pure functions the agent can call in code
max_iters=5, # int -- max generate-execute cycles before stopping
interpreter=None, # PythonInterpreter or None -- custom interpreter (creates one if None)
)
signature -- same as any DSPy module. Defines what the agent receives and what it should produce.tools -- a list of Python functions. Must be pure functions (not callable objects or class instances). All dependencies must be self-contained within each function -- tools cannot import external libraries or reference outside state.max_iters -- safety limit on how many code-generation-and-execution cycles the agent runs. Default is 5. Increase for complex multi-step tasks, decrease for simple ones.interpreter -- optionally pass a pre-configured dspy.PythonInterpreter. If None, CodeAct creates a fresh one. The interpreter runs code in a sandboxed Deno-based environment.CodeAct is strict about what tools it accepts:
# OK -- pure function
def search(query: str) -> str:
"""Search for information."""
return "results..."
# OK -- function with multiple parameters
def lookup(table: str, key: str) -> str:
"""Look up a value in a table."""
return "value..."
# NOT OK -- callable object (will be rejected)
class MyTool:
def __call__(self, query: str) -> str:
return "results..."
# NOT OK -- tool that imports external libraries
def analyze(data: str) -> str:
"""Analyze data."""
import pandas as pd # This will fail in the sandbox
return str(pd.read_csv(data))
Rules for tools:
CodeAct runs generated code in a sandboxed Deno-based Python interpreter, not your system's Python. This means:
The sandbox provides security boundaries, but your tool functions themselves run in your normal Python process. If a tool accesses a database or API, that access is real.
Tool functions are the trust boundary. The sandbox constrains the generated glue code, but tool functions execute with full privileges. Keep tool functions minimal and validate their inputs.
Set max_iters appropriately. A runaway agent burns tokens. Start with max_iters=5 and increase only if you see the agent running out of steps on legitimate tasks.
Validate outputs. Use dspy.Refine as a wrapper to check that the agent's answer meets your requirements via a reward function.
Don't expose dangerous operations as tools. If you pass a tool that deletes files or sends emails, the agent can and will call it. Only expose tools you're comfortable with the agent using autonomously.
class SafeCodeAgent(dspy.Module):
def __init__(self, tools):
self.agent = dspy.CodeAct(
"task -> result",
tools=tools,
max_iters=5,
)
def forward(self, task):
return self.agent(task=task)
def non_empty_reward(args, pred):
if len(pred.result.strip()) > 0:
return 1.0
return 0.0 # Agent must produce a non-empty result
validated_agent = dspy.Refine(
module=SafeCodeAgent(tools=[]),
N=3,
reward_fn=non_empty_reward,
threshold=1.0,
)
Wrap CodeAct in a dspy.Module to add pre-processing, post-processing, or combine it with other DSPy modules:
class AnalysisAgent(dspy.Module):
def __init__(self):
self.planner = dspy.ChainOfThought("task -> plan")
self.executor = dspy.CodeAct(
"task, plan -> result",
tools=[compute_stats, format_table],
max_iters=8,
)
self.summarize = dspy.ChainOfThought("task, result -> summary")
def forward(self, task):
plan = self.planner(task=task)
execution = self.executor(task=task, plan=plan.plan)
return self.summarize(task=task, result=execution.result)
CodeAct agents are optimizable like any DSPy module:
def task_metric(example, prediction, trace=None):
return prediction.answer.strip() == example.answer.strip()
# BootstrapFewShot works well -- the agent learns from successful code traces
optimizer = dspy.BootstrapFewShot(metric=task_metric, max_bootstrapped_demos=4)
optimized = optimizer.compile(agent, trainset=trainset)
# MIPROv2 can also tune the instructions for code generation
optimizer = dspy.MIPROv2(metric=task_metric, auto="medium")
optimized = optimizer.compile(agent, trainset=trainset)
# Save and load
optimized.save("optimized_codeact.json")
After building, run a concrete test and inspect the generated code:
result = agent(question="What is the factorial of 10 plus the 15th Fibonacci number?")
print(result.answer) # should be a computed number, not vague prose
dspy.inspect_history(n=1) # see the code the agent generated and executed
If the agent produces reasoning text instead of executing code, check that all tools have type hints and docstrings — these are required for the agent to understand how to call them.
| Scenario | Use |
|---|---|
| Look up facts and combine them | ReAct |
| Calculate, aggregate, or transform data | CodeAct |
| Simple API calls (weather, stock price) | ReAct |
| Multi-step data processing pipeline | CodeAct |
| Tasks where approach varies per input | CodeAct |
| Quick prototype with many tools | ReAct |
| Math-heavy or logic-heavy problems | CodeAct |
| Tasks needing external libraries in tools | ReAct (more flexible tool format) |
__call__), not bound methods, not lambdas. If you need to wrap state, define a closure that captures the state and pass the inner function.import pandas between tool calls, it fails. Move all library usage inside the tool function itself, not in the generated code.tools list. Claude often defines helper functions but forgets to register them.max_iters too low for complex tasks. The default max_iters=5 is fine for simple computation, but data analysis tasks that fetch multiple sources and process results often need 8-10 iterations. Watch for "max iterations reached" and increase accordingly.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-react and /ai-taking-actions/dspy-program-of-thought/ai-taking-actions/ai-coordinating-agents/dspy-modules/dspy-signatures/ai-do if you do not have it — it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
/dspy-api-skills:dspy-codeactfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time.Other plugins' skills for the same job