Obtener una clave API
api.models

turn · motivos de detención

turn.stopReason

Por qué el modelo se detuvo. Es el campo en el que las ramas de bucle, y el que dice una respuesta terminada de una truncada.

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.

Los dos que verás

stopRasonSignificadoHacer
tool_useDecidió llamar a herramientas. toolCalls está poblada.Ejecutarlas, añadir los resultados, llamar de nuevo.
end_turnLa respuesta es el contenido.Párate, dale el contenido a quien lo haya pedido.
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"]
Rama en stopRason, nunca en si la herramientaCalls está vacía

Un turno puede llevar llamadas de texto y herramientas a la vez — el modelo dice lo que está a punto de hacer, luego lo hace. Probar el texto primero hace que el bucle se detenga un paso antes y pierda el trabajo.

Cuando se detuvo en el techo

Un giro también puede terminar porque se quedó sin espacio en lugar de porque estaba terminado. Eso no es un error, se obtiene una respuesta válida con una respuesta incompleta, que es el caso peligroso precisamente porque nada lanza.

// 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']}")

La causa habitual es maxOutputTokens, y en un modelo de pensamiento el razonamiento se gasta desde ese mismo techo — véase pensando.

Un bucle que termina

tool_use puede repetir. Atado el número de pasos, y atado el gasto — un bucle con ninguno puede correr hasta que algo más lo detenga.

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")
Ambos límites ganan su lugar

El conteo de pasos atrapa un bucle que va en círculos. El conteo de créditos atrapa un bucle que hace progreso caro. Fallan de manera diferente, y una carrera puede golpear cualquiera de los dos.

Si ese es el bucle que ibas a escribir, el motor de agente es él — con permisos, presupuesto, reintentos y un modelo de retroceso ya en su lugar. Motor agente.