Skip to main content

Overview

The GeneralCoder agent is an AI-powered coding assistant that can generate, execute, and debug Python code based on natural language task descriptions. It uses a multi-agent system with a coder agent and an executor agent.

Class Definition

class GeneralCoder:
    def __init__(
        self,
        llm_config: dict[str, any],
        code_execution_config: dict[str, any],
        connection_id: Optional[str] = None,
        send_message_function: Optional[callable] = None,
        agent_history: list = None
    )

Parameters

llm_config
dict
required
LLM configuration dictionary containing model settings.Required fields:
  • model: Model name (e.g., “gpt-4”, “claude-3”)
  • api_key: API key for the LLM service
  • base_url: API endpoint URL
Optional fields:
  • temperature: Generation temperature (0-1)
  • max_tokens: Maximum tokens per response
  • timeout: Request timeout in seconds
code_execution_config
dict
required
Configuration for code execution environment.Required fields:
  • work_dir: Working directory for code execution
  • use_docker: Whether to use Docker (bool)
Example:
{
    "work_dir": "coding/workspace",
    "use_docker": False
}
connection_id
str
Connection identifier for tracking purposes
send_message_function
callable
Callback function to send messages during execution
agent_history
list
Previous agent conversation history for context

Methods

create_code_tool

async def create_code_tool(
    task_description: str,
    context: Optional[str | dict] = None,
    required_libraries: Optional[list] = None,
) -> Union[str, dict]
Generate and execute code based on a task description.
task_description
str
required
Detailed description of the task to accomplish. Should describe what needs to be done, not provide code.Example:
"Calculate the maximum drawdown of NVIDIA stock in 2024 and create a visualization"
context
str | dict
Additional context or background information for the task.Can include:
  • User’s original question
  • Necessary data paths
  • Previous results or findings
  • Constraints or requirements
Example:
{
    "original_query": "Analyze NVIDIA performance",
    "data_path": "./data/stock_prices.csv",
    "time_range": "2024-01-01 to 2024-12-31"
}
required_libraries
list
List of Python libraries that might be needed.Example:
["pandas", "matplotlib", "numpy", "yfinance"]
result
str | dict
Execution result. Returns:
  • String: Simple execution result
  • Dictionary: Contains execution_result and file_summary if files were created
Dictionary structure:
{
    "execution_result": "Task completed successfully...",
    "file_summary": {
        "code_files": [{"filename": "analysis.py", "description": "..."}],
        "data_files": [{"filename": "results.csv", "description": "..."}],
        "image_files": [{"filename": "chart.png", "description": "..."}]
    }
}
Example:
import asyncio
from src.services.agents.agent_general_coder import GeneralCoder

# Initialize the coder
llm_config = {
    "model": "gpt-4",
    "api_key": "your-api-key"
}

code_config = {
    "work_dir": "coding/analysis",
    "use_docker": False
}

coder = GeneralCoder(
    llm_config=llm_config,
    code_execution_config=code_config
)

# Execute a coding task
result = await coder.create_code_tool(
    task_description="Download Tesla stock data for 2024 and calculate daily returns",
    context="Analyze TSLA stock performance for investment research",
    required_libraries=["yfinance", "pandas"]
)

print(result)

initiate_agents

def initiate_agents(**kwargs)
Initialize the internal coder and executor agents. Called automatically during __init__. Creates:
  • general_coder: Assistant agent for code generation
  • coder_excute: User proxy agent for code execution

update_system_message

def update_system_message()
Update the coder agent’s system message with current context and file information. This method:
  • Adds file path handling instructions
  • Includes available local files from Task_description.json
  • Adds code quality requirements
  • Updates modular programming guidelines
Automatically called before each create_code_tool execution.

register_toolkits

def register_toolkits()
Register additional tools for the agents (currently not used by default).

Code Quality Guidelines

The GeneralCoder enforces several best practices:

Modular Programming

  • Break complex tasks into separate files
  • Create dedicated files for data acquisition, processing, analysis, and visualization
  • Execute files sequentially or in parallel as appropriate

File Descriptions

Always add descriptions to created files:
from src.services.functional.coding import CodingUtils as cu

# Save data with description
cu.insert_file_description_to_file(
    'stock_data.csv',
    'NVIDIA stock data from 2024-01-01 to 2024-12-31'
)

# Save code with description
cu.insert_file_description_to_file(
    'analysis.py',
    'Script to calculate maximum drawdown and generate charts'
)

Path Handling

  • Use relative filenames, not full paths
  • Files are automatically saved in the configured work_dir
  • Example: Use data.csv instead of coding/workspace/data.csv

Conversation Settings

The agent uses these settings for code generation:
  • Max turns: 50 conversation rounds
  • Summary method: reflection_with_llm
  • Termination: Triggered by “TERMINATE” keyword

File Summarization

After task completion, the agent automatically:
  1. Analyzes the conversation history
  2. Identifies all created files
  3. Categorizes them as code, data, or images
  4. Generates descriptions for each file
  5. Filters out failed execution sessions

Advanced Usage

With Context from Previous Steps

result = await coder.create_code_tool(
    task_description="Create a correlation heatmap of the stock data",
    context={
        "previous_result": "Stock data downloaded to stock_data.csv",
        "data_path": "stock_data.csv",
        "columns": ["Open", "High", "Low", "Close", "Volume"]
    },
    required_libraries=["pandas", "seaborn", "matplotlib"]
)

Accessing Created Files

result = await coder.create_code_tool(
    task_description="Analyze sales data and create visualizations"
)

if isinstance(result, dict):
    print("Execution:", result["execution_result"])
    
    files = result.get("file_summary", {})
    
    # Access created files
    for code_file in files.get("code_files", []):
        print(f"Code: {code_file['filename']} - {code_file['description']}")
    
    for data_file in files.get("data_files", []):
        print(f"Data: {data_file['filename']} - {data_file['description']}")
    
    for image_file in files.get("image_files", []):
        print(f"Image: {image_file['filename']} - {image_file['description']}")

Error Handling

The agent includes automatic error handling:
  • Failed code execution sessions are filtered from history
  • Errors are reported in the execution result
  • Only successful file operations are included in summaries

Notes

  • The agent expects tasks in natural language, not code snippets
  • Code is generated based on the task description and context
  • All file paths are relative to the configured work_dir
  • The agent can handle multiple files and complex workflows
  • Failed executions are automatically retried with fixes

Build docs developers (and LLMs) love