Your first Python agent¶
Here you connect Code Mode to a language model from your own Python code. The result is a small program that answers a question using your tools.
Before you start: finish Your first run, so that you have
library_server.py and mcp.json in a folder, and have an API key for a model provider.
1. Install a model SDK¶
Any OpenAI-compatible API works, which covers OpenAI, the Vercel AI Gateway, OpenRouter, Azure, GitHub Models and local models through Ollama. Install the extra for it:
For Anthropic's API, install codemode-mcp[anthropic] and use run_anthropic in place of
run_openai below.
2. Put your key in the environment¶
Keep keys out of your code. Set one for the provider you use:
On Windows PowerShell, write $env:OPENAI_API_KEY = "...".
3. Write the agent¶
Save this as agent.py in the same folder:
import asyncio
from codemode_mcp import CodeMode
from codemode_mcp.agent import run_openai
async def main():
async with CodeMode.from_config("mcp.json") as cm:
result = await run_openai(
cm,
"Which book in the library has the best average rating?",
model="gpt-4.1-mini",
)
print(result.text)
print(f"{result.turns} model turns, {len(result.tool_calls)} tool call(s)")
asyncio.run(main())
import asyncio
import os
from codemode_mcp import CodeMode
from codemode_mcp.agent import run_openai
async def main():
async with CodeMode.from_config("mcp.json") as cm:
result = await run_openai(
cm,
"Which book in the library has the best average rating?",
model="openai/gpt-4.1-mini",
base_url="https://ai-gateway.vercel.sh/v1",
api_key=os.environ["AI_GATEWAY_API_KEY"],
)
print(result.text)
print(f"{result.turns} model turns, {len(result.tool_calls)} tool call(s)")
asyncio.run(main())
import asyncio
from codemode_mcp import CodeMode
from codemode_mcp.agent import run_openai
async def main():
async with CodeMode.from_config("mcp.json") as cm:
result = await run_openai(
cm,
"Which book in the library has the best average rating?",
model="llama3.1",
base_url="http://localhost:11434/v1",
api_key="ollama",
)
print(result.text)
print(f"{result.turns} model turns, {len(result.tool_calls)} tool call(s)")
asyncio.run(main())
Run it:
The model should answer that The Left Hand of Darkness has the best average, 4.8. Larger
models usually get there with a single run_code call. Smaller ones often look at a book or
two first and then write the loop, so expect anywhere from one to five calls.
4. See the script the model wrote¶
result.tool_calls holds every call the model made, with its arguments and output. Add
this inside main() to print the code:
import json
for call in result.tool_calls:
if call["name"] == "run_code":
print(json.loads(call["arguments"])["code"])
print("returned:", call["output"])
5. What run_openai does for you¶
It is a short loop, and you can write your own when you need more control or use another framework. Three things are all you need:
| You need | Call |
|---|---|
| The tool definitions to give the model | cm.tools("openai"), or "anthropic", "openai-responses", "mcp" |
| A short instruction for the system prompt | cm.system_prompt |
| To execute a tool call the model made | await cm.call(name, arguments) |
The full loop, with examples for other providers, is in Python library & LLMs.
6. Try it without writing code¶
The same thing is available from the terminal, which is handy for a quick test:
codemode-mcp chat -m gpt-4.1-mini "Which book has the best average rating?"
codemode-mcp -v chat -m gpt-4.1-mini # interactive, printing each script and result
Add --base-url and --api-key-env for other providers, for example
--base-url https://ai-gateway.vercel.sh/v1 --api-key-env AI_GATEWAY_API_KEY -m openai/gpt-4.1-mini.
Measure it on your own task¶
To compare classic tool calling and Code Mode on a prompt of yours, with the same model and the provider's own token counts:
Benchmarks describes the method and its limits.
Next: How it works.