pythonintermediate

OpenAI Function Calling / Tool Use

Let GPT call your functions by defining tool schemas and handling responses.

python
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.