# turn · motivos de detención

Canonical URL: https://developers.iagenify.com/es/sdk/ref/models/turn/stop-reasons/
Language: es

`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.

Status: tool_use · end_turn · branch on it, not on the text

## Los dos que verás {#two}

| stopRason | Significado | Hacer |
| --- | --- | --- |
| tool_use | Decidió llamar a herramientas. toolCalls está poblada. | Ejecutarlas, añadir los resultados, llamar de nuevo. |
| end_turn | La respuesta es el contenido. | Párate, dale el contenido a quien lo haya pedido. |

```javascript
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;
}
```

> **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 {#ceiling}

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.

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

La causa habitual es `maxOutputTokens`, y en un modelo de pensamiento el razonamiento se gasta desde ese mismo techo — véase [pensando](/es/sdk/ref/models/turn/thinking).

## Un bucle que termina {#loop}

`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.

```javascript
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`);
```

> **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](/es/sdk/agent).

- [turn · mensajes](/es/sdk/ref/models/turn/messages): Crecer la historia correctamente entre pasos.
- [Presupuesto](/es/sdk/agent/budget): Recorriendo una carrera por lo que puede gastar.

```python
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"]
```

```python
# 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']}")
```

```python
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")
```
