Developer Tools

Code Debugging Agent

Build an autonomous debugging agent that reads your code and error output, hypothesizes root causes, proposes fixes, and iterates until the tests pass — powered by OneInfer's LLM.

OneInfer Chat APITool CallingPythonsubprocess

Step-by-step guide

1

Define the debugging tools

python
import openai
import subprocess
import json

client = openai.OpenAI(
    api_key="your-oneinfer-api-key",
    base_url="https://api.oneinfer.ai/v1"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read the contents of a source file.",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string"}},
                "required": ["path"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "write_file",
            "description": "Write updated code to a file.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {"type": "string"},
                    "content": {"type": "string"}
                },
                "required": ["path", "content"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "run_tests",
            "description": "Run the test suite and return the output.",
            "parameters": {
                "type": "object",
                "properties": {"command": {"type": "string", "description": "e.g. 'pytest tests/'"}},
                "required": ["command"]
            }
        }
    }
]
2

Implement the tool handlers

python
def execute_tool(name: str, args: dict) -> str:
    if name == "read_file":
        try:
            return open(args["path"]).read()
        except FileNotFoundError:
            return f"Error: {args['path']} not found"

    elif name == "write_file":
        with open(args["path"], "w") as f:
            f.write(args["content"])
        return f"Written {len(args['content'])} chars to {args['path']}"

    elif name == "run_tests":
        result = subprocess.run(
            args["command"].split(),
            capture_output=True, text=True, timeout=60
        )
        output = result.stdout + result.stderr
        return output[:3000]  # Truncate very long output

    return "Unknown tool"
3

Run the autonomous debugging loop

python
def debug_agent(error_description: str, max_iterations: int = 5) -> str:
    messages = [
        {
            "role": "system",
            "content": (
                "You are an expert debugging agent. Given a bug report, you will: "
                "1) Read relevant files, 2) Identify the root cause, 3) Apply a fix, "
                "4) Run tests to verify. Keep iterating until tests pass or max attempts reached."
            )
        },
        {"role": "user", "content": f"Bug report: {error_description}\n\nPlease debug and fix this issue."}
    ]

    for iteration in range(max_iterations):
        response = client.chat.completions.create(
            model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
            messages=messages,
            tools=tools,
            tool_choice="auto"
        )
        msg = response.choices[0].message

        if not msg.tool_calls:
            return msg.content  # Agent is done

        messages.append(msg)
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)
            result = execute_tool(call.function.name, args)
            print(f"[{call.function.name}] → {result[:200]}")
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": result
            })

    return "Max iterations reached without resolution."

# Example usage
report = debug_agent(
    "TypeError: 'NoneType' object is not subscriptable in src/parser.py line 47. "
    "Test file is tests/test_parser.py"
)
print(report)