Skip to content

[FEATURE] CodeAgent #2194

@emilmont

Description

@emilmont

Problem Statement

I would like Strands to allow the initialisation of an agent capable of executing a complex action plan as a single code-execution action.

The basic approach has been described in the paper: "Executable Code Actions Elicit Better LLM Agents". In this paper it has been described as: "use executable code to consolidate LLM agents’ actions into a unified action space (CodeAct)".

From our past AWS prototyping activities, we have collected additional practical requirements.

Given a set of library functions providing a given functionality, these are common requirements:

  1. Add a set of libraries to the allow-list of libraries that can be imported by a sandboxed environment.
  2. A snippet of initialisation code that should be run after the environment initialisation. For example, for matplotlib we might want to setup a non-interactive backend (matplotlib.use('Agg')).
  3. Custom usage-instructions to be added in the system prompt.
  4. A list of Domain Specific Code that should be fully imported in the execution environment, and should be fully documented in the System Prompt.

Proposed Solution

We propose the following implementation, used in these two projects:

Quick Start

from strands_code_agent import CodeAgent

agent = CodeAgent(system_prompt="You are a helpful data analyst.")

response = agent("What is 2 ** 10?")

The agent receives a python_repl tool automatically and solves tasks by writing and executing Python code.

CodeAgent

CodeAgent extends the Strands Agent with a built-in Python REPL and automatic system-prompt enrichment.

Parameter Type Description
system_prompt str | None Base system prompt, extended with coding instructions.
tools list | None Additional tools alongside the built-in Python REPL.
toolkits list[Toolkit] | None Toolkits that configure the REPL environment (see below).
tmp_dir bool If True (default), creates a temp directory and documents its path in the prompt.
**kwargs Forwarded to the Strands Agent base class (e.g. model, callback_handler).

Toolkit

A Toolkit bundles everything the REPL needs for a specific domain. Each field influences the CodeAgent in a specific way:

Parameter Type Effect on PythonInterpreter Effect on System Prompt
libraries list[str] | None Added to authorized_imports — the REPL will only allow imports from this allowlist.
initialization_code str | None Prepended to state_initialization — runs before every Agent snippet. Documented so the agent knows which symbols are pre-loaded.
usage_instructions str | None Appended as-is, giving the agent guidance on how to use the libraries.
domain_specific_code list | None Auto-imported in state_initialization (modules added to authorized_imports). Full signature + docstring of each symbol is documented so the agent can use them.

Example

from strands_code_agent.toolkits import Toolkit

VISUALIZATION_TOOLKIT = Toolkit(
    # 1. libraries → PythonInterpreter.authorized_imports
    #    Allows the REPL to import these modules.
    libraries=["matplotlib", "matplotlib.pyplot", "seaborn"],

    # 2. initialization_code → PythonInterpreter.state_initialization + System Prompt
    #    Runs before user code; also shown in the prompt so the agent
    #    knows plt and sns are already available.
    initialization_code="""
import matplotlib
matplotlib.use('Agg')  # Use non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
""",

    # 3. usage_instructions → System Prompt only
    #    Tells the agent how to behave with these libraries.
    usage_instructions="Do not try to show any matplotlib image: the python_repl tool executes the code in a sub-process without a GUI.",
)

Built-in Toolkits

The library ships with ready-to-use toolkits:

from strands_code_agent.toolkits import (
    VISUALIZATION_TOOLKIT,  # matplotlib + seaborn (non-interactive backend)
    NUMPY,                  # numpy
    PANDAS,                 # pandas
    DATETIME,               # datetime
)

Domain-Specific Code

Pass your own functions or classes via domain_specific_code. The CodeAgent will:

  1. Auto-import them in PythonInterpreter.state_initialization (their modules are added to authorized_imports).
  2. Document each symbol's full signature and docstring in the System Prompt, so the agent knows how to call them.
from strands_code_agent import CodeAgent, Toolkit

def calculate_roi(investment: float, returns: float) -> float:
    """Calculate return on investment as a percentage."""
    return (returns - investment) / investment * 100


agent = CodeAgent(
    system_prompt="You are a finance assistant.",
    toolkits=[
        Toolkit(domain_specific_code=[calculate_roi])
    ],
)

response = agent("What is the ROI if I invest 1000 and get back 1250?")

Combining Toolkits

from strands_code_agent import CodeAgent
from strands_code_agent.toolkits import PANDAS, VISUALIZATION_TOOLKIT

agent = CodeAgent(
    system_prompt="You are a data analyst.",
    toolkits=[PANDAS, VISUALIZATION_TOOLKIT],
)

Use Case

The following are two projects using this CodeAgent library:

  1. Data Analyst operating on 1,775 from the UK ONS and OECD:
  1. Geospatial Analyst analysing Sentinel-2 and LandSat data:

Alternatives Solutions

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions