ExamplescriptadvancedRunnabletool-agent
Function Calling
Runnable example (advanced) for script using openai, python-dotenv.
Key Facts
- Level
- advanced
- Runtime
- Python • OpenAI API
- Pattern
- Inspectable flow with visible system boundaries
- Interaction
- Live sandbox • Script
- Updated
- 14 March 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
function-calling.py
python
import json
import openai
from dotenv import load_dotenv
from tools import add
load_dotenv("../.env")
"""
This is a simple example to demonstrate that MCP simply enables a new way to call functions.
"""
# Define tools for the model
tools = [
{
"type": "function",
"function": {
"name": "add",
"description": "Add two numbers together",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer", "description": "First number"},
"b": {"type": "integer", "description": "Second number"},
},
"required": ["a", "b"],
},
},
}
]
# Call LLM
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Calculate 25 + 17"}],
tools=tools,
)
# Handle tool calls
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
tool_name = tool_call.function.name
tool_args = json.loads(tool_call.function.arguments)
# Execute directly
result = add(**tool_args)
# Send result back to model
final_response = openai.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Calculate 25 + 17"},
response.choices[0].message,
{"role": "tool", "tool_call_id": tool_call.id, "content": str(result)},
],
)
print(final_response.choices[0].message.content)
Related principles
- P6visibilityExpose meaningful operational state, not internal complexityPresent the state of the system in language and structures that are relevant to the user, rather than exposing low-level internals that do not support action or understanding.Open principle →
- P7trustEstablish trust through inspectabilityUsers should be able to examine how a result was produced when confidence, accountability, or decision quality is important.Open principle →
- P8trustMake hand-offs, approvals, and blockers explicitWhen the system cannot proceed, the reason should be immediately visible, along with any action required from the user or another dependency.Open principle →
- P9orchestrationRepresent delegated work as a system, not merely as a conversationWhere work involves multiple steps, agents, dependencies, or concurrent activities, it should be represented as a structured system rather than solely as a message stream.Open principle →