api.models

turn · Stoppgründe

turn.stopReason

Warum das Modell aufgehört hat. Es ist das Feld, auf dem die Schleife verzweigt, und das, das eine fertige Antwort von einem abgeschnittenen erzählt.

tool_use · end_turnbranch on it, not on the text
Using Python?

Switch any code block to Python: the choice applies to every page. Python SDK guide and resource reference.

Die beiden, die du sehen wirst

Reason wird abgesetztBedeutungZu tun
tool_useEs entschied sich, Werkzeuge zu rufen. toolCalls ist besiedelt.Führen Sie sie aus, fügen Sie die Ergebnisse an, rufen Sie erneut an.
end_turnDie Antwort ist der Inhalt.Gib den Inhalt an denjenigen, der gefragt hat.
const turn = await api.models.turn({ model, messages, tools });

if (turn.stopReason === "tool_use") {
  // there is work to do before there is an answer
} else {
  return turn.message.content;
}
turn = api.models.turn(model=model, messages=messages, tools=tools)

if turn["stopReason"] == "tool_use":
    pass  # there is work to do before there is an answer
else:
    answer = turn["message"]["content"]
Zweig auf stopReason, nie auf, ob ToolCalls leer ist

Eine Wendung kann Text und Werkzeugaufrufe auf einmal tragen — das Modell sagt, was es tun wird, dann tut es. Testen des Textes zuerst macht Ihre Schleife stoppen einen Schritt früh und verlieren die Arbeit.

Als es an der Decke anhielt

Eine Wende kann auch enden, weil sie nicht mehr aus dem Raum lief, sondern weil sie beendet war. Das ist kein Fehler - man bekommt eine gültige Antwort, die eine unvollständige Antwort enthält, was gerade der gefährliche Fall ist, weil nichts wirft.

// Treat anything that is neither of the two as « did not finish »
const DONE = new Set(["end_turn", "tool_use"]);

if (!DONE.has(turn.stopReason)) {
  // Typically the output ceiling. Raise maxOutputTokens, lower thinking,
  // or ask for something shorter — but do not use the text as if it were whole.
  throw new Error(`the turn did not finish: ${turn.stopReason}`);
}
# Treat anything that is neither of the two as « did not finish »
DONE = {"end_turn", "tool_use"}

if turn["stopReason"] not in DONE:
    # Typically the output ceiling. Raise max_output_tokens, lower thinking,
    # or ask for something shorter — but do not use the text as if it were whole.
    raise RuntimeError(f"the turn did not finish: {turn['stopReason']}")

Die übliche Ursache ist maxOutputTokens, und auf einem Denkmodell wird die Argumentation von derselben Decke ausgegeben — siehe denkbar .

Eine Schleife, die endet

tool_use kann wiederholen. Die Anzahl der Schritte wird begrenzt und der Aufwand wird gebunden – eine Schleife mit keiner kann laufen, bis etwas anderes sie stoppt.

const MAX_STEPS = 12;
const MAX_CREDITS = 200;
let spent = 0;

for (let step = 0; step < MAX_STEPS; step += 1) {
  const turn = await api.models.turn({ model, messages, tools });
  spent += turn.usage.credits;

  messages.push(turn.message);

  if (turn.stopReason === "end_turn") return turn.message.content;
  if (turn.stopReason !== "tool_use") throw new Error(`unfinished: ${turn.stopReason}`);
  if (spent > MAX_CREDITS) throw new Error(`budget spent after ${step + 1} steps`);

  for (const call of turn.message.toolCalls) {
    messages.push({ role: "tool", toolCallId: call.id, name: call.name,
                    content: String(await run(call.name, call.args)) });
  }
}

throw new Error(`no answer after ${MAX_STEPS} steps`);
MAX_STEPS = 12
MAX_CREDITS = 200

def solve(messages):
    spent = 0
    for step in range(MAX_STEPS):
        turn = api.models.turn(model=model, messages=messages, tools=tools)
        spent += turn["usage"]["credits"]

        messages.append(turn["message"])

        if turn["stopReason"] == "end_turn":
            return turn["message"]["content"]
        if turn["stopReason"] != "tool_use":
            raise RuntimeError(f"unfinished: {turn['stopReason']}")
        if spent > MAX_CREDITS:
            raise RuntimeError(f"budget spent after {step + 1} steps")

        for call in turn["message"]["toolCalls"]:
            messages.append({"role": "tool", "toolCallId": call["id"], "name": call["name"],
                             "content": str(run(call["name"], call["args"]))})

    raise RuntimeError(f"no answer after {MAX_STEPS} steps")
Beide Grenzen verdienen ihren Platz

Der Schritt zählt fängt eine Schleife, die im Kreis. Der Kredit zählt fängt eine Schleife, die Fortschritte teuer macht. Sie scheitern anders, und ein Lauf kann entweder treffen.

Wenn das die Schleife ist, die Sie schreiben wollten, ist es die Agent-Engine – mit Berechtigungen, Budget, Retries und einem Fallback-Modell bereits vorhanden. Siehe Agent-Engine .