Skip to main content
The CodeAgent provides a Jupyter notebook-like interface where the LLM writes Python code that gets executed in a persistent namespace with browser control functions available.

Overview

Unlike the standard Agent which uses predefined actions, CodeAgent gives the LLM the ability to write and execute Python code directly. This provides more flexibility for complex automation tasks that require custom logic, data processing, or multi-step workflows.

Basic Example

Constructor

CodeAgent

str
required
The task description for the agent to complete.
BaseChatModel | None
The language model to use. If not provided, defaults to ChatBrowserUse().Note: CodeAgent currently only works with ChatBrowserUse.
BrowserSession | None
Browser session instance. If not provided, a new browser will be created automatically.
Tools | None
Custom tools registry. If not provided, uses default CodeAgentTools() which includes browser control functions.
BaseChatModel | None
Separate LLM model for page content extraction. Useful for using a faster/cheaper model for extraction.
FileSystem | None
File system instance for file operations. Defaults to FileSystem(base_dir='./').
list[str] | None
List of file paths the agent can access.
dict[str, str | dict[str, str]] | None
Dictionary containing sensitive data that should be handled carefully.
int
default:"100"
Maximum number of execution steps before terminating.
int
default:"8"
Maximum consecutive errors before auto-termination.
int
default:"0"
Maximum number of times to run the validator agent to verify task completion.
bool
default:"True"
Whether to include screenshots in LLM messages for visual context.
bool
default:"False"
Whether to calculate and track token costs.
bool | None
Enable the in-browser demo panel for live logging and visualization.

Methods

run

Execute the agent to complete the task.
int | None
Optional override for maximum number of steps. Uses constructor value if not provided.
Returns: NotebookSession - A notebook session containing all executed code cells, outputs, and browser states.

close

Close the browser session.

How CodeAgent Differs from Agent

Agent (Standard)

  • Uses predefined actions (click, type, navigate, etc.)
  • LLM selects actions from a fixed set
  • Structured, predictable behavior
  • Best for straightforward automation tasks

CodeAgent

  • LLM writes custom Python code
  • Full programming flexibility
  • Access to Python libraries (json, csv, re, etc.)
  • Persistent namespace across cells
  • Best for complex logic, data processing, custom workflows

Available Functions in Namespace

The CodeAgent executes code in a namespace with browser control functions available:

Browser Navigation

Element Interaction

Information Retrieval

JavaScript Execution

Task Completion

The done() function must be called to mark the task as complete. Without it, the agent will continue until max_steps is reached.

Code Execution Features

Persistent Namespace

Variables persist across code cells, just like Jupyter notebooks:

Top-Level Await

You can use await at the top level without wrapping in async functions:

Multiple Code Block Types

The LLM can generate multiple types of code blocks:
Non-Python blocks are injected as string variables in the namespace for reference.

Result Object

The run() method returns a NotebookSession object:

NotebookSession Properties

  • cells - List of executed code cells with outputs
  • execution_count - Current execution count
  • _complete_history - Complete execution history with metadata
  • _usage_summary - Token usage and cost summary

Cell Properties

  • source - The Python code that was executed
  • output - Captured stdout output
  • error - Error message if execution failed
  • status - Execution status: SUCCESS, ERROR, or RUNNING
  • execution_count - Cell execution number
  • browser_state - Browser state text at time of execution
  • cell_type - Cell type: CODE or MARKDOWN

Advanced Examples

Data Extraction with Processing

The agent will write code similar to:

Form Filling with Validation

Multi-Page Workflow

Error Handling

Consecutive Error Limit

The agent tracks consecutive errors and terminates after max_failures (default: 8):

Validation

Enable task completion validation to ensure the agent actually completed the task:
If validation fails, the agent receives feedback and continues working.

Best Practices

1. Clear Task Descriptions

Be specific about what you want:

2. Use Sensitive Data Parameter

Keep credentials safe:

3. Enable Vision for Visual Tasks

4. Set Appropriate Limits

5. Track Costs

Comparison with Standard Agent

Troubleshooting

Agent Doesn’t Call done()

Make sure your task is clear about when to finish:

Variables Not Persisting

Variables should persist automatically. If they don’t, check for:
  • Syntax errors in code
  • Scope issues with function definitions

Browser State Not Updating

The browser state is fetched before each LLM call. If you need to force a refresh:

Token Limit Errors

If you hit token limits:
  1. Reduce max_steps
  2. Use page_extraction_llm with a smaller model
  3. Disable use_vision if screenshots aren’t needed