بتل کد Battle Codeدارد باز می‌شود…

جواب «Send the Result Back» چالش 4 از جلسه‌ی 69

سؤال

یک چرخه‌ی کامل: جواب اول مدل یک درخواست ابزار است. ابزار را اجرا کن، پیام مدل را با tool_calls و بعد یک پیام با نقش tool، همان tool_call_id و نتیجه به عنوان content به messages اضافه کن و مدل را دوباره صدا بزن. متن جواب نهایی را چاپ کن. خروجی:
The weather in Tabriz is sunny, 18 degrees.

راهنما

result = get_weather(**json.loads(call["function"]["arguments"]))؛ messages.append({"role": "assistant", "content": None, "tool_calls": reply["tool_calls"]})؛ messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})؛ reply = fake_model(messages).

یک جواب درست

import json

WEATHER = {"Tabriz": "sunny, 18 degrees", "Rasht": "rainy, 12 degrees"}


def get_weather(city):
    return WEATHER.get(city, "unknown")


def fake_model(messages):
    # A pretend model: asks for the weather tool, then answers from its result.
    last = messages[-1]
    if last["role"] == "tool":
        return {"role": "assistant", "content": "The weather in Tabriz is " + last["content"] + ".", "tool_calls": None}
    return {"role": "assistant", "content": None, "tool_calls": [
        {"id": "call_1", "function": {"name": "get_weather", "arguments": '{"city": "Tabriz"}'}}]}


messages = [{"role": "user", "content": "What is the weather in Tabriz today?"}]
reply = fake_model(messages)
call = reply["tool_calls"][0]
args = json.loads(call["function"]["arguments"])
result = get_weather(**args)
messages.append({"role": "assistant", "content": None, "tool_calls": reply["tool_calls"]})
messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})
reply = fake_model(messages)
print(reply["content"])

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن