# turn · mensagens

Canonical URL: https://developers.iagenify.com/pt/sdk/ref/models/turn/messages/
Language: pt

`api.models.turn({ messages })`

Tres roli, e la sola regola che decide se un loop di chiamare a utensili funzionât.

Status: obrigatório · never empty · you own the history

Un virat non tiene nulla. Il model sa è exacto lo che è in questo array — quindi il array è la conversa, e crescendo il bonit è il loop.

## I tre ruoli {#roles}

| rol | Conteúdo | Script da |
| --- | --- | --- |
| Usuario | e optionalmente immagini | Tu |
| assistente | content, e toolCalls quando decide agir | Copied retro del virare anterior |
| Instrumento | toollCallId, nome, contenit — o resultado que ha prodotto | Tu, dopo la ruleta del utense |

```javascript
[
  { role: "user", content: "What is the weather in Tunis?" },

  { role: "assistant", content: "",
    toolCalls: [{ id: "call_0", name: "weather",
                  args: { city: "Tunis" }, signature: "…" }] },

  { role: "tool", toolCallId: "call_0", name: "weather",
    content: "22°C, clear" },
]
```

## Il loop, in pleno {#loop}

```javascript
const messages = [{ role: "user", content: question }];

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

  // 1. The assistant's move goes back in, UNCHANGED.
  messages.push(turn.message);

  if (turn.stopReason !== "tool_use") return turn.message.content;

  // 2. Run what it asked for, and answer every call it made.
  for (const call of turn.message.toolCalls) {
    const result = await run(call.name, call.args);
    messages.push({ role: "tool", toolCallId: call.id, name: call.name,
                    content: String(result) });
  }
}
throw new Error("too many steps");
```

> **Impulsare il messaggio di assistente invariat**
>
> Reconstruire, largare un campo che non riconormi, o mantenendo solo il testo romperà il turn.Alguns models portano una firma in un appello di utensili che deve revenir come ha lasciato.

## Risponde a ogni chiamata, anche i fallis {#answer-all}

Un virat puè chiedere per variu utensilîs a la volta. Ocunune necessita di suo proprio messaggio `tool`, concomparit da `toolCallId` — lascia un non risposto e il viratül ne è inconsistente.

```javascript
for (const call of turn.message.toolCalls) {
  let content;
  try {
    content = String(await run(call.name, call.args));
  } catch (err) {
    // A failure is a result. Say what went wrong — it is what lets the model recover.
    content = `Error: ${err.message}`;
  }
  messages.push({ role: "tool", toolCallId: call.id, name: call.name, content });
}
```

Dicindo al modele che un utensiliu failed, e porquo, vale generalmente più di disfarçe: può tentare in un altro modo. Silenzio basta fa-lo repete la stessa chiamata.

## Immagini e ataxes {#images}

Un messaggio d'usuari puè portare immagini, e un resultado d'utensiliu puè portar ataxs — una pagina, un document, un record — per cui il modele ved lo che l'uteniu produciu invecché una decripçâne dell.

```javascript
{ role: "user", content: "What is wrong with this screenshot?",
  images: [{ mime: "image/png", data: base64 }] }

{ role: "tool", toolCallId: "call_0", name: "read", content: "report.pdf, 12 pages",
  attachments: [{ mime: "application/pdf", data: base64 }] }
```

| Acceptat | Tipos |
| --- | --- |
| Imagens | Png · jpeg · webp · gif · heic · heif |
| Documenti | pdf |
| Audio | wav · mp3 · mp4 · aac · ogg · flac · opus |
| Video | mp4 · mpeg · mov · avi · webm · flv · 3gpp |

> **Un giro porta al majù 18 MB di attachs**
>
> Passò che il turn è negat prima che nulla è facturato. Un tipo non riconoscit è negat tamès, nominato nel messaggio — convertitelo, o decrivilo in testo.

## L'historia è per il che pagate {#growth}

Todo lo che è in array e s'invia a ogni turn, e un loop che run 20 gradini invia il primo messaggio 20 volte.

- **Drop o che has beved.** Un grande risultato de ferramentas, que ha già fost ragionat, può essere sostituito con una nota breve di che è accaduto.
- **Sommare la mezza vecchia** e portar in funzione la matriz a partir del sumario — que è ciò que il motor agente fa per voi.

## Erros {#errors}

| Código | Status | Quando |
| --- | --- | --- |
| messages_required | 400 | L'array era o vazio o mancava. |
| context_too_large | 400 | Piu que la finestra del modele. Refused ante ogni débito. |
| turn_failed | 502 | Il provider ha rifiutat. Il messaggio è del provider, redatto. |

- [turn · ferramentas](/pt/sdk/ref/models/turn/tools): Declare lo que può chiamare, e quanto costà.
- [turn · motivos de parada](/pt/sdk/ref/models/turn/stop-reasons): Sapere quando il loop è finit.
- [Mecanismo de agentes](/pt/sdk/agent): Questo loop, ya scrit, con permissions e budget.

```python
[
    {"role": "user", "content": "What is the weather in Tunis?"},

    {"role": "assistant", "content": "",
     "toolCalls": [{"id": "call_0", "name": "weather",
                    "args": {"city": "Tunis"}, "signature": "…"}]},

    {"role": "tool", "toolCallId": "call_0", "name": "weather",
     "content": "22°C, clear"},
]
```

```python
def answer(question):
    messages = [{"role": "user", "content": question}]

    for _ in range(10):
        turn = api.models.turn(model=model, messages=messages, tools=tools)

        # 1. The assistant's move goes back in, UNCHANGED.
        messages.append(turn["message"])

        if turn["stopReason"] != "tool_use":
            return turn["message"]["content"]

        # 2. Run what it asked for, and answer every call it made.
        for call in turn["message"]["toolCalls"]:
            result = run(call["name"], call["args"])
            messages.append({"role": "tool", "toolCallId": call["id"], "name": call["name"],
                             "content": str(result)})
    raise RuntimeError("too many steps")
```

```python
for call in turn["message"]["toolCalls"]:
    try:
        content = str(run(call["name"], call["args"]))
    except Exception as error:
        # A failure is a result. Say what went wrong — it is what lets the model recover.
        content = f"Error: {error}"
    messages.append({"role": "tool", "toolCallId": call["id"], "name": call["name"], "content": content})
```

```python
{"role": "user", "content": "What is wrong with this screenshot?",
 "images": [{"mime": "image/png", "data": base64_png}]}

{"role": "tool", "toolCallId": "call_0", "name": "read", "content": "report.pdf, 12 pages",
 "attachments": [{"mime": "application/pdf", "data": base64_pdf}]}
```
