# Tool calling

> Describe your own functions to the model, run the calls it asks for and send the results back; the OpenAI tools format works on Lykia as it is.

With tool calling, you tell the model which functions it may use. When the model needs one of them to answer, it replies with a call request instead of text. **Your code** runs the call, sends the result back, and the model finishes its answer using that result. Lykia never runs a function itself; requests and responses use OpenAI's `tools` format.

## Pick a model that supports tools

Not every model can call tools. A model can when `tools` appears in its `supported_parameters` in the catalog, and you can filter the catalog for exactly those models:

```bash
# Models whose supported_parameters include "tools"
curl "https://api.getlykia.com/v1/models?supported_parameters=tools" \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

What happens when you send `tools` to a model without support depends on the model and the provider, so choose from this list up front. If you use [model fallbacks](https://www.getlykia.com/en/docs/guides/model-fallbacks), make sure the backups support `tools` as well.

## Define your tools

Tools go in the `tools` array of the request. Each one has a name, a description that helps the model decide when to use it, and a JSON Schema for its arguments.

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [{ "role": "user", "content": "What is the weather like in Izmir right now?" }],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Current weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "city": { "type": "string", "description": "City name, e.g. Izmir" },
              "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
            },
            "required": ["city"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'
```

**Response (200)**

```json
{
  "id": "gen-1795373697-1Re1biw4kD3isWXZ",
  "object": "chat.completion",
  "created": 1795373697,
  "model": "openai/gpt-4o-mini",
  "provider": "openai",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_Qy3Lw8xV2nRk5mTb",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"Izmir\"}"
            }
          }
        ]
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 82,
    "completion_tokens": 18,
    "total_tokens": 100,
    "cost": 0.000023,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.000023,
      "platform_fee": 0,
      "is_byok": false
    },
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "system_fingerprint": "fp_560af6e559"
}
```

When the model decides to call a tool, `finish_reason` is `"tool_calls"` and the message carries a `tool_calls` array. Each call has an `id`, the function name and its arguments as a JSON string. `content` is usually `null` in this case.

- `tools` (array) — The tools the model may call.
  - `type` (string, required) — `"function"`.
  - `function.name` (string, required) — The function name: letters, digits, underscores and dashes.
  - `function.description` (string) — What the function does. The model reads this when choosing a tool, so keep it short and specific.
  - `function.parameters` (object) — JSON Schema for the arguments.
- `tool_choice` (string | object) — `"auto"` (the model decides), `"none"` (no tool calls), `"required"` (at least one call) or a specific tool: `{ "type": "function", "function": { "name": "get_weather" } }`.
- `parallel_tool_calls` (boolean) — Lets the model call more than one tool in a single response.

## Run the call and send the result back

The loop looks like this:

1. Send the user's message along with the `tools` array.
2. If the response contains `tool_calls`, append the assistant message to the conversation exactly as you received it.
3. For each call, parse the arguments as JSON, run your function, and append the result as a message with `role: "tool"`, putting the call's `id` in `tool_call_id`.
4. Send the whole conversation again with the same `tools`. The model either asks for another call or writes its answer using the results.

**Python**

```python
import json
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name, e.g. Izmir"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["city"],
            },
        },
    }
]


def get_weather(city: str, unit: str = "celsius") -> dict:
    # Replace with a real weather lookup.
    return {"city": city, "temperature": 21, "unit": unit, "conditions": "sunny"}


messages = [{"role": "user", "content": "What is the weather like in Izmir right now?"}]

while True:
    completion = client.chat.completions.create(model="openai/gpt-4o-mini", messages=messages, tools=tools)
    message = completion.choices[0].message
    if not message.tool_calls:
        print(message.content)
        break

    # Keep the assistant turn that asked for the tools, then answer each call.
    messages.append(message.model_dump(exclude_none=True))
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const tools: OpenAI.Chat.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "Current weather for a city",
      parameters: {
        type: "object",
        properties: {
          city: { type: "string", description: "City name, e.g. Izmir" },
          unit: { type: "string", enum: ["celsius", "fahrenheit"] },
        },
        required: ["city"],
      },
    },
  },
];

function getWeather(city: string, unit = "celsius") {
  // Replace with a real weather lookup.
  return { city, temperature: 21, unit, conditions: "sunny" };
}

const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
  { role: "user", content: "What is the weather like in Izmir right now?" },
];

for (;;) {
  const completion = await client.chat.completions.create({ model: "openai/gpt-4o-mini", messages, tools });
  const message = completion.choices[0].message;
  if (!message.tool_calls?.length) {
    console.log(message.content);
    break;
  }

  // Keep the assistant turn that asked for the tools, then answer each call.
  messages.push(message);
  for (const call of message.tool_calls) {
    if (call.type !== "function") continue;
    const args = JSON.parse(call.function.arguments);
    const result = getWeather(args.city, args.unit);
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
}
```

> **Warning:** Treat the arguments a model produces like user input. Validate them before running anything, and ask the user to confirm before a tool writes to a database, spends money or sends an email.

## Practical notes

- **Every round trip is a separate request.** A conversation with tool calls takes several requests, and each is billed. The tool definitions and the growing message history count as prompt tokens every time.
- **Cap the loop.** A model can keep asking for tools. Add a maximum number of rounds to the loop above before you ship it.
- **Arguments arrive in pieces when streaming.** With `stream: true`, join the `tool_calls[].function.arguments` pieces by `index` and parse the JSON only once the stream has finished. See [Streaming](https://www.getlykia.com/en/docs/guides/streaming).
- **Keep results small.** Tool results go back to the model as tokens; return only the fields it needs.

## Next steps

- [Structured outputs](https://www.getlykia.com/en/docs/guides/structured-outputs): make the answer itself match a JSON Schema.
- [Models](https://www.getlykia.com/en/docs/models): read model capabilities from `supported_parameters`.
- [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions): reference for `tools` and `tool_choice`.
