Get an API key
api.models

turn · messages

api.models.turn({ messages })

The whole conversation, every time. Three roles, and the one rule that decides whether a tool-calling loop works at all.

requirednever emptyyou own the history
Using Python?

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

A turn keeps nothing. What the model knows is exactly what is in this array — so the array is the conversation, and growing it correctly is the loop.

The three roles

roleCarriesWritten by
usercontent, and optionally imagesYou
assistantcontent, and toolCalls when it decided to actCopied back from the previous turn
tooltoolCallId, name, content — the result you producedYou, after running the tool
[
  { 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" },
]
[
    {"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"},
]

The loop, in full

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");
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")
Push the assistant message back unchanged

Rebuilding it, dropping a field you did not recognise, or keeping only the text will break the next turn. Some models carry a signature on a tool call that must come back exactly as it left.

Answer every call, even the failures

A turn can ask for several tools at once. Each one needs its own tool message, matched by toolCallId — leave one unanswered and the next turn is inconsistent.

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

Telling the model that a tool failed, and why, is usually worth more than hiding it: it can try another way. Silence just makes it repeat the same call.

Images and attachments

A user message can carry images, and a tool result can carry attachments — a page, a document, a recording — so the model sees what the tool produced rather than a description of it.

{ 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 }] }
{"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}]}
AcceptedTypes
Imagespng · jpeg · webp · gif · heic · heif
Documentspdf
Audiowav · mp3 · mp4 · aac · ogg · flac · opus
Videomp4 · mpeg · mov · avi · webm · flv · 3gpp
One turn carries at most 18 MB of attachments

Past that the turn is refused before anything is billed. An unrecognised type is refused too, named in the message — convert it, or describe it in text instead.

The history is what you pay for

Everything in the array is sent on every turn, so a loop that runs twenty steps sends the first message twenty times. Two things keep that in hand.

  • Drop what has been consumed. A large tool result that has already been reasoned about can be replaced with a short note that it happened.
  • Summarise the old half and start the array from the summary — which is what the agent engine does for you.

Errors

CodeStatusWhen
messages_required400The array was missing or empty.
context_too_large400More than the model's window. Refused before any debit.
turn_failed502The provider refused. The message is the provider's, redacted.