pythonintermediate
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
pythonPress β/Ctrl + Shift + C to copy
from openai import OpenAI
import json
client = OpenAI()
# Define available tools
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
]
def get_weather(city: str, units: str = "celsius") -> dict:
# Simulated API call
return {"city": city, "temp": 22, "units": units, "condition": "sunny"}
# Chat with tool use
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
# Handle tool call
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
result = get_weather(**args)
# Send result back
messages.append(response.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
final = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(final.choices[0].message.content)Use Cases
- AI agents
- Chatbots with actions
- Automated workflows
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
#openai#tool-calling
pythonintermediate
OpenAI Function Calling with Pydantic
Define type-safe tools for OpenAI function calling using Pydantic models and auto-serialization.
Best for: structured tool calling
#openai#function-calling
typescriptbeginner
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.
Best for: AI art generation
#openai#dall-e
typescriptbeginner
Content Moderation with OpenAI
Check user input for harmful content using the OpenAI Moderation API before processing.
Best for: user input safety
#openai#moderation