# Araç çağırma

> Modele kendi fonksiyonlarınızı tanıtın, modelin istediği çağrıları çalıştırıp sonucu geri gönderin; OpenAI tools biçimi Lykia'da olduğu gibi çalışır.

Araç çağırmada modele hangi fonksiyonları çağırabileceğini söylersiniz. Model bir soruyu yanıtlamak için bu fonksiyonlardan birine ihtiyaç duyarsa metin yerine bir çağrı isteği döner; çağrıyı **sizin kodunuz** çalıştırır, sonucu modele gönderir ve model yanıtı bu sonuçla tamamlar. Lykia hiçbir fonksiyonu kendisi çalıştırmaz; istek ve yanıtlar OpenAI'ın `tools` biçimindedir.

## Aracı destekleyen bir model seçin

Her model araç çağırmayı desteklemez. Katalogda bir modelin `supported_parameters` listesinde `tools` varsa model araç alabilir. Bu modelleri doğrudan süzebilirsiniz:

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

Desteklemeyen bir modele `tools` gönderirseniz ne olacağı modele ve sağlayıcıya bağlıdır; modeli baştan bu listeden seçin. Yedek model kullanıyorsanız ([Yedek modeller](https://www.getlykia.com/docs/guides/model-fallbacks)) yedeklerin de `tools` desteklediğinden emin olun.

## Araçları tanımlayın

Araçlar istekteki `tools` dizisinde tanımlanır. Her aracın adı, modelin ne zaman kullanacağını anlamasına yardım eden bir açıklaması ve argümanlarını anlatan bir JSON Schema'sı vardır.

**İstek**

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"
  }'
```

**Yanıt (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"
}
```

Model aracı çağırmaya karar verdiğinde yanıtta `finish_reason` `"tool_calls"` olur ve `message.tool_calls` dizisi gelir. Her çağrının bir `id`'si, fonksiyon adı ve JSON dizgisi olarak argümanları vardır. `content` bu durumda genellikle `null`'dır.

- `tools` (array) — Modelin çağırabileceği araçlar.
  - `type` (string, zorunlu) — `"function"`.
  - `function.name` (string, zorunlu) — Fonksiyonun adı; harf, rakam, alt çizgi ve tire.
  - `function.description` (string) — Fonksiyonun ne yaptığı. Model aracı seçerken buna bakar; kısa ve net yazın.
  - `function.parameters` (object) — Argümanların JSON Schema'sı.
- `tool_choice` (string | object) — `"auto"` (model karar verir), `"none"` (araç çağırmaz), `"required"` (en az bir araç çağırır) ya da belirli bir araç: `{ "type": "function", "function": { "name": "get_weather" } }`.
- `parallel_tool_calls` (boolean) — Modelin tek yanıtta birden fazla araç çağırmasına izin verir.

## Çağrıyı çalıştırıp sonucu gönderin

Döngü şöyle işler:

1. Kullanıcının mesajını ve `tools` dizisini gönderin.
2. Yanıtta `tool_calls` varsa asistan mesajını olduğu gibi mesaj geçmişine ekleyin.
3. Her çağrı için argümanları JSON olarak ayrıştırın, fonksiyonunuzu çalıştırın ve sonucu `role: "tool"` olan bir mesajla, çağrının `id`'sini `tool_call_id` alanına yazarak ekleyin.
4. Geçmişin tamamını ve aynı `tools` dizisini yeniden gönderin. Model ya yeni bir araç çağrısı ister ya da sonucu kullanarak yanıtını yazar.

**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) });
  }
}
```

> **Dikkat:** Modelin ürettiği argümanlar kullanıcı girdisi gibidir. Fonksiyonu çalıştırmadan önce argümanları doğrulayın; veritabanına yazan, para harcayan ya da e-posta gönderen araçlarda kullanıcı onayı isteyin.

## Pratik notlar

- **Her tur ayrı bir istektir.** Araç çağrılı bir konuşma birkaç istekten oluşur ve her biri ayrı faturalanır. Her istekte `tools` tanımları ve büyüyen mesaj geçmişi istem token'larına eklenir.
- **Döngüye sınır koyun.** Model art arda araç çağırmayı sürdürebilir. Canlıya çıkmadan önce örnekteki döngüye bir tur sınırı ekleyin.
- **Akışta argümanlar parça parça gelir.** `stream: true` kullanıyorsanız `tool_calls[].function.arguments` parçalarını `index`'e göre birleştirin ve JSON'u ancak akış bitince ayrıştırın. Bkz. [Akış (streaming)](https://www.getlykia.com/docs/guides/streaming).
- **Sonucu kısa tutun.** Araç sonucu da modele token olarak gider; yalnız modelin ihtiyacı olan alanları döndürün.

## Sonraki adımlar

- [Yapılandırılmış çıktılar](https://www.getlykia.com/docs/guides/structured-outputs): Yanıtın kendisini bir JSON Schema'ya uydurun.
- [Modeller](https://www.getlykia.com/docs/models): `supported_parameters` ile model yeteneklerini okuyun.
- [`POST /chat/completions`](https://www.getlykia.com/docs/api-reference/chat-completions): `tools` ve `tool_choice` alanlarının başvurusu.
