Agent loop

latest messagemessage historyunused
PromptLLMAnswerToolstool_usetool_resultmessages[]user: fix failing testtool_use: bash("pytest")
  1. Single inference: one prompt, no environment feedback.
  2. stop_reason = tool_use: the runtime executes the call.
  3. tool_result is appended to messages[] as ground truth.
  4. The loop repeats until stop_reason = end_turn.
Notes & references

Use when

Step count is unpredictable and actions depend on environment feedback.

Avoid

Unbounded loops: always cap max_turns, tokens and wall-clock.

messages = [{ role: "user", content: task }]

while True:
    reply = llm.create(messages, tools)
    messages.append(reply)

    if reply.stop_reason == "end_turn":
        return reply.text              # done

    results = [run(call) for call in reply.tool_calls]
    messages.append({ role: "user", content: results })