How to use code execution tool in LangChain
Quick answer
Use LangChain's
PythonREPLTool or PythonAstREPLTool to execute Python code dynamically within chains. Instantiate the tool, then integrate it with an Agent or AgentExecutor to run code snippets as part of your AI workflow.PREREQUISITES
Python 3.8+pip install langchain>=0.2.0OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install LangChain and OpenAI Python SDK, and set your OpenAI API key as an environment variable.
pip install langchain openai Step by step
This example shows how to use LangChain's PythonREPLTool to execute Python code dynamically within an agent.
import os
from langchain.agents import initialize_agent, Tool
from langchain.agents.agent_types import AgentType
from langchain_openai import ChatOpenAI
from langchain.tools.python.tool import PythonREPLTool
# Set up the LLM client
llm = ChatOpenAI(model_name="gpt-4o", temperature=0)
# Initialize the Python code execution tool
python_tool = PythonREPLTool()
# Wrap the tool for the agent
tools = [Tool(name="python", func=python_tool.run, description="Executes Python code")]
# Initialize the agent with the tool
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# Example prompt to execute Python code
response = agent.run("Calculate the factorial of 5 using Python code.")
print(response) output
Executing Python code... 120
Common variations
- Use
PythonAstREPLToolfor safer, AST-based code execution. - Run code execution asynchronously by integrating with async LangChain agents.
- Combine code execution with other tools like web search or calculators in multi-tool agents.
Troubleshooting
- If code execution fails, check Python syntax and runtime errors in the output.
- Ensure your environment has necessary Python packages installed for the code you run.
- Verbose mode helps trace the agent's reasoning and tool usage.
Key Takeaways
- Use LangChain's PythonREPLTool to execute Python code dynamically within AI agents.
- Integrate code execution tools with OpenAI models like gpt-4o for powerful automation.
- Enable verbose mode to debug and understand code execution steps in agents.