Code Interpreter
The Python Code Interpreter Tool enables agents to dynamically execute Python code, making them useful for solving mathematical problems, running computations, and handling errors. This guide covers how to integrate the Python Interpreter Tool into an agent and use it for automated code execution.
Creating a Python Code Interpreter Agent
To enable Python execution, create an agent with the Python Interpreter Tool:
from aixplain.factories import AgentFactory
from aixplain.enums import Function, Supplier
agent = AgentFactory.create(
name="Python Developer",
description="A Python developer agent. If you get an error from a tool, try to fix it.",
tools=[
AgentFactory.create_python_interpreter_tool()
]
)
Executing Python Code
Once the agent is created, you can pass any query requiring Python computation:
response = agent.run("Solve the equation $\\frac{v^2}{2} + 7v - 16 = 0$ to find the value of $v$.")
print(response["data"]["output"])
response["data"]["intermediate_steps"]
Handling Errors and Installing Dependencies
To ensure smooth execution, the agent can automatically fix errors and install missing Python libraries when needed.
Enhanced Python Developer Agent
This version includes an additional instruction to install missing packages:
from aixplain.factories import AgentFactory
from aixplain.enums import Function, Supplier
dev_agent = AgentFactory.create(
name="Python Developer",
description="""
A Python developer agent. If you get an error from a tool, try to fix it.
For any package, you can use os.system('pip install package_name').
You must install the package in the same code where you use it.
""",
tools=[
AgentFactory.create_python_interpreter_tool()
]
)
print(dev_agent.name, dev_agent.id)
Running Python-Based Queries
The agent can process multiple types of tasks, including retrieving external information:
import json
response = dev_agent.run("How is the friendship paradox explained on Wikipedia? Use the Wikipedia Python library.")
print(response.data["output"])
print(json.dumps(response.data["intermediate_steps"], indent=4))
If the wikipedia
package is not installed, the agent will automatically install it and return the relevant information.
The Python Code Interpreter Tool allows agents to execute Python code dynamically, making them capable of problem-solving, automation, and knowledge retrieval. By integrating error handling and dependency management, aiXplain agents can ensure smooth execution across a variety of tasks.