Create an AI agent with function calling

By Ryze AI Team

This tutorial builds a minimal agent that can call a weather function to answer questions, using the OpenAI function calling API.

1. Define tools

tools = [{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Get current weather for a city",
    "parameters": {
      "type": "object",
      "properties": {"city": {"type": "string"}},
      "required": ["city"]
    }
  }
}]

2. Implement the tool

import json
def get_weather(city):
    # call a weather API here
    return {"city": city, "temp_c": 18, "condition": "cloudy"}

3. Agent loop

from openai import OpenAI
client = OpenAI()
messages = [{"role": "user", "content": "What is the weather in Berlin?"}]
for _ in range(10):
    r = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
    msg = r.choices[0].message
    messages.append(msg)
    if not msg.tool_calls:
        print(msg.content)
        break
    for tc in msg.tool_calls:
        args = json.loads(tc.function.arguments)
        result = get_weather(**args)
        messages.append({"role": "tool", "tool_call_id": tc.id, "content": json.dumps(result)})

4. How it works

The model decides whether to call a tool. If it does, you execute it and feed the result back as a tool message. The loop continues until the model produces a normal reply. The cap of ten iterations prevents infinite loops.

5. Safety and robustness

Validate arguments before calling tools. Wrap tool execution in try/except and return an error message the model can read. Require confirmation for any mutating action. Log every call. For read-only tools, run automatically; for anything that changes state, ask the user first.

Docs: OpenAI function calling.