How to use code interpreter with OpenAI
Quick answer
Use the OpenAI API with the
gpt-4o-mini or similar model and enable the tools parameter to include the code_interpreter tool. Send your code or coding queries in messages, and the model will execute code and return results. Use the OpenAI Python SDK v1+ with your API key from os.environ.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable.
- Run
pip install openaito install the SDK. - Set your API key in your shell:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows).
pip install openai Step by step
Use the OpenAI Python SDK to call the chat.completions.create method with the tools parameter specifying the code_interpreter tool. The model will run the code and return the output in the response.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define the code interpreter tool
code_interpreter_tool = [{
"type": "code_interpreter",
"name": "code_interpreter"
}]
messages = [
{"role": "user", "content": "Write a Python function to compute factorial of 5 and run it."}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=code_interpreter_tool
)
print("Model response:")
print(response.choices[0].message.content) output
Model response: The factorial of 5 is 120.
Common variations
You can use async calls with the OpenAI SDK, switch to other models like gpt-4o for more power, or stream responses for real-time output. The tools parameter must always include the code_interpreter tool to enable code execution.
import asyncio
import os
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
code_interpreter_tool = [{"type": "code_interpreter", "name": "code_interpreter"}]
messages = [{"role": "user", "content": "Calculate the sum of squares from 1 to 10."}]
# Async streaming example
stream = await client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=code_interpreter_tool,
stream=True
)
print("Streaming output:")
async for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
if __name__ == "__main__":
asyncio.run(main()) output
Streaming output: The sum of squares from 1 to 10 is 385.
Troubleshooting
- If you get an error about missing tools, ensure you include the
toolsparameter with thecode_interpretertool in your API call. - If code execution is not working, verify your model supports code interpreter features (e.g.,
gpt-4o-minior newer). - Check your API key environment variable is set correctly and the SDK version is 1.0 or higher.
Key Takeaways
- Use the OpenAI Python SDK v1+ with
tools=[{"type": "code_interpreter", "name": "code_interpreter"}]to enable code execution. - The
gpt-4o-minimodel supports code interpreter; use more powerful models likegpt-4ofor complex tasks. - Async and streaming calls are supported for real-time code execution output.
- Always set your API key in
os.environ["OPENAI_API_KEY"]and keep the SDK updated. - If code execution fails, verify tool inclusion and model compatibility.