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.
MarkdownBu sayfada
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:
# 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) 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.
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"
}'{
"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.
toolsarrayModelin çağırabileceği araçlar.
typestringzorunlu"function".
function.namestringzorunluFonksiyonun adı; harf, rakam, alt çizgi ve tire.
function.descriptionstringFonksiyonun ne yaptığı. Model aracı seçerken buna bakar; kısa ve net yazın.
function.parametersobjectArgümanların JSON Schema'sı.
tool_choicestring | 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_callsbooleanModelin 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:
- Kullanıcının mesajını ve
toolsdizisini gönderin. - Yanıtta
tool_callsvarsa asistan mesajını olduğu gibi mesaj geçmişine ekleyin. - 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ınid'sinitool_call_idalanına yazarak ekleyin. - Geçmişin tamamını ve aynı
toolsdizisini yeniden gönderin. Model ya yeni bir araç çağrısı ister ya da sonucu kullanarak yanıtını yazar.
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)})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) });
}
}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
toolstanı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: truekullanıyorsanıztool_calls[].function.argumentsparçalarınıindex'e göre birleştirin ve JSON'u ancak akış bitince ayrıştırın. Bkz. Akış (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: Yanıtın kendisini bir JSON Schema'ya uydurun.
- Modeller:
supported_parametersile model yeteneklerini okuyun. POST /chat/completions:toolsvetool_choicealanlarının başvurusu.