# turn · motivos de parada

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

`turn.stopReason`

Por che il modele s'impuse. È il campo su su loop ramies on, e que dice una risposta finita da un tronco.

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

## I due vedrete {#two}

| Reson | Significado | Fa |
| --- | --- | --- |
| tool_use | Decise di chiamare tools. toolCalls is poblated. | Rule, anexe i risultati, ripetere. |
| end_turn | Finit. La risposta è il contenit. | Assegna il content a chi lo chiese. |

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

> **Branch on stopReason, mai se toolCalls è vazio**
>
> Un virare può trasportare il testo e le chiamate d'outils da una volta — il modele dice ce è pec fa, poi lo fa. Testando il testo prima fa il loop stop un pas e perde il lavoro.

## Quando si fermava al soffitto {#ceiling}

Un virat puè anche finire perché non era più spazio che perché era finit. Non è un erro — si obten una risposta valida che contende una risposta incompleta, che è il caso pericoloso precisamente perché nulla lance.

```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 usual è `maxOutputTokens`, e su un modele di ragionamento il ragionamento è spendet da quel msim tetvel — ved [pensando](/pt/sdk/ref/models/turn/thinking).

## Un loop che termina {#loop}

`tool_use` può ripetere. Amarre il numero di step, e lega la spesa — un loop con né può correre fino che qualcosa lo ferma.

```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 limites guantam su lugar**
>
> Il conto step capture un buco che va in círculos. Il conto de credit capture un buco che fa progresso costosamente.

Se è il loop che si stava per scrivere, il motor agente è il — con permissions, budget, retries e un modello de replie ya in place. Ved [Motor Agent](/pt/sdk/agent).

- [turn · mensagens](/pt/sdk/ref/models/turn/messages): Crescendo la historia corretamente entre steps.
- [Orçamento](/pt/sdk/agent/budget): Agrundando un run da quel che può spender.

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