Skip to content

Agent

MaxStepsReached

Bases: Exception

Raised when the maximum number of steps per agent run is reached.

CodeActAgentResponse dataclass

CodeActAgentResponse(text: str, usage: CodeActModelUsage)

A response from an single interaction with a code action agent.

text instance-attribute

text: str

The final response text to the user.

usage instance-attribute

Accumulated model usage during this interaction.

CodeActAgentTurn

CodeActAgentTurn(iter: AsyncIterator[CodeActModelTurn | CodeExecution | CodeActAgentResponse], trace_name: str, trace_input: dict[str, Any], trace_session_id: str | None = None)

A single interaction with the code action agent.

An interaction consists of a sequence of model interaction and code execution pairs, continuing until the code action model provides a final response or the maximum number of steps is reached.

Source code in freeact/agent.py
def __init__(
    self,
    iter: AsyncIterator[CodeActModelTurn | CodeExecution | CodeActAgentResponse],
    trace_name: str,
    trace_input: dict[str, Any],
    trace_session_id: str | None = None,
):
    self._iter = iter
    self._response: CodeActAgentResponse | None = None
    self._trace_name = trace_name
    self._trace_input = trace_input
    self._trace_session_id = trace_session_id

response async

response() -> CodeActAgentResponse

Retrieves the final response from the code action agent for this interaction. Waits until the sequence of model interactions and code executions is complete.

Returns:

Type Description
CodeActAgentResponse

The final response from the code action model as CodeActAgentResponse object.

Raises:

Type Description
MaxStepsReached

If the interaction exceeds the maximum number of steps without completion.

Source code in freeact/agent.py
async def response(self) -> CodeActAgentResponse:
    """Retrieves the final response from the code action agent for this
    interaction. Waits until the sequence of model interactions and code
    executions is complete.

    Returns:
        The final response from the code action model as `CodeActAgentResponse`
            object.

    Raises:
        MaxStepsReached: If the interaction exceeds the maximum number of
            steps without completion.
    """
    if self._response is None:
        async for _ in self.stream():
            pass
    return self._response  # type: ignore

stream async

Streams the sequence of model interaction and code execution pairs as they occur:

  • CodeActModelTurn: The current interaction with the code action model
  • CodeExecution: The current execution of a code action in the code execution environment

The sequence continues until the model provides a final response. Once the stream is consumed, response is immediately available without waiting and contains the final response text and accumulated usage statistics.

Raises:

Type Description
MaxStepsReached

If the interaction exceeds the maximum number of steps without completion.

Source code in freeact/agent.py
async def stream(self) -> AsyncIterator[CodeActModelTurn | CodeExecution]:
    """Streams the sequence of model interaction and code execution pairs
    as they occur:

    - `CodeActModelTurn`: The current interaction with the code action model
    - `CodeExecution`: The current execution of a code action in the code
      execution environment

    The sequence continues until the model provides a final response. Once
    the stream is consumed, [`response`][freeact.agent.CodeActAgentTurn.response]
    is immediately available without waiting and contains the final response
    text and accumulated usage statistics.

    Raises:
        MaxStepsReached: If the interaction exceeds the maximum number of
            steps without completion.
    """
    async with tracing.trace(
        name=self._trace_name,
        input=self._trace_input,
        session_id=self._trace_session_id,
    ) as trace:
        async for elem in self._iter:
            match elem:
                case CodeActAgentResponse() as response:
                    self._response = response
                    await trace.update(output=response.text)
                case _:
                    yield elem

CodeActAgent

CodeActAgent(model: CodeActModel, executor: CodeExecutor)

An agent that iteratively generates and executes code actions to process user queries.

The agent implements a loop that:

  1. Generates code actions using a CodeActModel
  2. Executes the code using a CodeExecutor
  3. Provides execution feedback to the CodeActModel
  4. Continues until the model generates a final response.

A single interaction with the agent is initiated with its run method. The agent maintains conversational state and can have multiple interactions with the user.

Parameters:

Name Type Description Default
model CodeActModel

Model instance for generating code actions

required
executor CodeExecutor

Executor instance for executing code actions

required
Source code in freeact/agent.py
def __init__(self, model: CodeActModel, executor: CodeExecutor):
    self.model = model
    self.executor = executor
    self._trace_session_id = tracing.create_session_id()

run

run(user_query: str, max_steps: int = 30, step_timeout: float = 120, **kwargs) -> CodeActAgentTurn

Initiates an interaction with the agent from a user query. The query is processed through a sequence of model interaction and code execution steps, driven by interacting with the returned CodeActAgentTurn object.

Parameters:

Name Type Description Default
user_query str

The user query (a question, instruction, etc.)

required
max_steps int

Maximum number of steps before raising MaxStepsReached

30
step_timeout float

Timeout in seconds per code execution step

120
**kwargs

Additional keyword arguments passed to the model

{}

Returns:

Name Type Description
CodeActAgentTurn CodeActAgentTurn

An object for retrieving the agent's processing steps and response.

Raises:

Type Description
MaxStepsReached

If the interaction exceeds max_steps without completion.

Source code in freeact/agent.py
def run(
    self,
    user_query: str,
    max_steps: int = 30,
    step_timeout: float = 120,
    **kwargs,
) -> CodeActAgentTurn:
    """Initiates an interaction with the agent from a user query. The query
    is processed through a sequence of model interaction and code execution
    steps, driven by interacting with the returned `CodeActAgentTurn` object.

    Args:
        user_query: The user query (a question, instruction, etc.)
        max_steps: Maximum number of steps before raising `MaxStepsReached`
        step_timeout: Timeout in seconds per code execution step
        **kwargs: Additional keyword arguments passed to the model

    Returns:
        CodeActAgentTurn: An object for retrieving the agent's processing steps
            and response.

    Raises:
        MaxStepsReached: If the interaction exceeds `max_steps` without completion.
    """

    trace_name = "Agent run"
    trace_input = {
        "user_query": user_query,
        "max_steps": max_steps,
        "step_timeout": step_timeout,
        **kwargs,
    }
    iter = self._stream(
        user_query=user_query,
        max_steps=max_steps,
        step_timeout=step_timeout,
        **kwargs,
    )
    return CodeActAgentTurn(iter, trace_name, trace_input, self._trace_session_id)