# Tool calling

1. **Model turn** one assistant message
2. contains `ToolCall`
3. **Run tools** results join the history, the model picks again
4. text only, no `ToolCall`
5. **Finish** text is the reply

Choosing is the `ToolCall`-or-text split in the provider's message; the framework only parses and branches. Loop: `_run_loop` in `openprogram/runtime/agent/loop/loop.py`.

## Entry point

```
runtime.exec(content, tools=..., tool_choice=..., max_iterations=...)
```

| Parameter | Effect |
| --- | --- |
| `tools` | The menu: `Agent` methods, `{"spec":..., "execute":...}` dicts, or objects with `.spec` and `.execute` |
| `toolset` | Neither this nor `tools`: the full registry, so tools are on by default. `toolset="none"` or `tools=[]`: text only. A nested `exec` in a tool body inherits the outer `tools=` list (`_current_tools` contextvar). |
| `tools_source`, `tools_allow`, `tools_deny` | Trim the menu |
| `tool_choice` | `"auto"` (default), `"required"`, `"none"`, or `{"type": "function", "name": "X"}`. Mapped by the provider (OpenAI, Anthropic, Gemini, Bedrock). |
| `parallel_tool_calls=False` | One pick per round, where the provider supports it |
| `max_iterations` | Round cap, effective `max(1, max_iterations)`. `runtime.exec` defaults to 20; chat turns have none. |
| `choices` | A forced, structured ending: [next-step decision](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/choosing-the-next-step/next-step-decision.html) |

## Running the picks

| Outcome | Result |
| --- | --- |
| Tool not found | `is_error` result |
| `validate_tool_arguments` fails | `is_error` result |
| `tool.execute` raises | Exception text as `is_error` result |
| Success | `ToolResultMessage` |

Errors go back to the model so it can correct itself; they do not break the loop. Several picks in one round run in order, by `_execute_tool_calls`. A message you queue meanwhile waits until that round's calls finish, then joins the next model decision.

## Termination

| Condition | End |
| --- | --- |
| Text only | Normal; the text is the result |
| `stop_reason` is `error` or `aborted` | Error or cancel, at once |
| Rounds exceed the cap | Only when a cap is set |

**What keeps the loop going after text**

The inner `while` also runs on `pending_messages`, so queued user messages continue it after a pure-text reply. After it exits, `get_follow_up_messages` may supply messages for another round; otherwise the run ends and pushes `AgentEventAgentEnd`.

An `Agent` method in `tools` is one pickable function. If its body calls `runtime.exec`, another layer of the same loop opens.

[Function-calling design](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/calling-unification.html): registry, gating, deferred loading
