> ## Documentation Index
> Fetch the complete documentation index at: https://openrouter.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Stop Conditions

> Control multi-turn execution with `stopWhen`. Use built-in helpers or custom conditions to stop by step count, tool calls, cost, or tokens.

## Basic Usage

```typescript lines theme={null}
import { OpenRouter, callModel, stepCountIs, tool } from '@openrouter/agent';
import { z } from 'zod';

const openrouter = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});

const searchTool = tool({
  name: 'search',
  description: 'Search for information on a topic',
  inputSchema: z.object({ query: z.string() }),
  execute: async ({ query }) => ({
    results: [`Result about ${query}`],
  }),
});

const analysisTool = tool({
  name: 'analyze',
  description: 'Analyze a piece of text',
  inputSchema: z.object({ text: z.string() }),
  execute: async ({ text }) => ({
    summary: `Analysis of: ${text}`,
  }),
});

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Research the history of the TypeScript language thoroughly: use the search tool, then analyze what you find.',
  tools: [searchTool, analysisTool],
  stopWhen: stepCountIs(5), // Stop after 5 steps
});

console.log(await result.getText());

```

```python title="Python" lines theme={null}
import asyncio
import os
from pydantic import BaseModel
from openrouter_agent import OpenRouter, call_model, step_count_is, tool

class SearchInput(BaseModel):
    query: str

class AnalyzeInput(BaseModel):
    text: str

search_tool = tool(
    name="search",
    description="Search for information on a topic",
    input_schema=SearchInput,
    execute=lambda params, ctx: {"results": [f"Result about {params.query}"]},
)

analysis_tool = tool(
    name="analyze",
    description="Analyze a piece of text",
    input_schema=AnalyzeInput,
    execute=lambda params, ctx: {"summary": f"Analysis of: {params.text}"},
)

async def main() -> None:
    client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])

    result = call_model(
        client,
        {
            "model": "openai/gpt-5-nano",
            "input": "Research this topic thoroughly",
            "tools": [search_tool, analysis_tool],
            "stop_when": step_count_is(5),  # Stop after 5 steps
        },
    )

    print(await result.get_text())

asyncio.run(main())

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func fn(name, desc, param string) map[string]any {
	return map[string]any{"type": "function", "function": map[string]any{
		"name": name, "description": desc,
		"parameters": map[string]any{"type": "object", "required": []string{param},
			"properties": map[string]any{param: map[string]string{"type": "string"}}},
	}}
}

func main() {
	tools := []any{
		fn("search", "Search for information on a topic", "query"),
		fn("analyze", "Analyze a piece of text", "text"),
	}
	messages := []any{map[string]string{"role": "user", "content": "Research this topic thoroughly"}}

	var text string
	for step := 0; ; step++ {
		request := map[string]any{"model": "openai/gpt-5-nano", "messages": messages}
		if step < 5 { // After 5 steps, send no tools so the model answers from the results it has
			request["tools"] = tools
		}
		body, _ := json.Marshal(request)
		req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
		req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			panic(err)
		}
		var out struct {
			Choices []struct{ Message json.RawMessage } `json:"choices"`
		}
		raw, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			panic(err)
		}
		if resp.StatusCode != http.StatusOK {
			panic(fmt.Sprintf("request failed: %s: %s", resp.Status, raw))
		}
		if err := json.Unmarshal(raw, &out); err != nil {
			panic(fmt.Sprintf("decode response: %v", err))
		}
		if len(out.Choices) == 0 {
			panic(fmt.Sprintf("no choices in response: %s", raw))
		}

		var msg struct {
			Content   string `json:"content"`
			ToolCalls []struct {
				ID       string `json:"id"`
				Function struct{ Name, Arguments string }
			} `json:"tool_calls"`
		}
		if err := json.Unmarshal(out.Choices[0].Message, &msg); err != nil {
			panic(fmt.Sprintf("decode message: %v", err))
		}
		text = msg.Content
		if len(msg.ToolCalls) == 0 {
			break
		}
		messages = append(messages, out.Choices[0].Message)

		for _, tc := range msg.ToolCalls {
			// Reject malformed arguments or a missing required argument before running the tool
			required := map[string]string{"search": "query", "analyze": "text"}[tc.Function.Name]
			var args map[string]string
			var result any
			if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil || required == "" || args[required] == "" {
				result = map[string]any{"error": "unknown tool or missing argument"}
			} else if tc.Function.Name == "search" {
				result = map[string]any{"results": []string{"Result about " + args["query"]}}
			} else {
				result = map[string]any{"summary": "Analysis of: " + args["text"]}
			}
			content, _ := json.Marshal(result)
			messages = append(messages, map[string]string{"role": "tool", "tool_call_id": tc.ID, "content": string(content)})
		}
	}

	fmt.Println(text)
}

```

```text title="Output" theme={null}
I started by searching for “TypeScript history” and then analyzed the results to synthesize a thorough history. Here’s a concise, well-rounded view of how TypeScript came to be, how it evolved, and why it matters today.

Overview
- TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing, interfaces, enums, generics, and other features to JavaScript, with the goal of enabling large-scale application development while remaining compatible with existing JavaScript code.
- It was designed and open-sourced by Microsoft, with Anders Hejlsberg (the designer of C# and Turbo Pascal) leading the effort.
- TypeScript has grown through broad ecosystem support (editor tooling, npm packages, DefinitelyTyped) and adoption in popular frameworks (notably Angular) and toolchains.

Key milestones and timeline (high-level)
- 2012–2013: Origins and early development
  - Microsoft begins work on a typed extension of JavaScript to address the needs of large-scale web apps.
  - The project remains experimental and then begins to take shape as a language that preserves JavaScript semantics while adding optional static typing.
- 2014: TypeScript 1.0 release
  - Official 1.0 release marks the transition from a research/prototype project to a stable language with a defined release process.
  - Core features include optional typing, interfaces, classes, modules, and generics, all compiles down to JavaScript.
- Mid-to-late 2010s: Growth of the 2.x era and expansion of the type system
  - TypeScript 2.x brings significant improvements to type inference, nullability handling, union types, and better tooling experiences.
  - The language gains more sophisticated type capabilities (e.g., better generics, mapped types) and tighter editor support via the Language Service API.
- Late 2010s to early 2020s: Ongoing feature evolution and ecosystem maturation
  - 3.x series introduces more advanced type system features (inference improvements, conditional types, template literal types) and broader library support.
  - The DefinitelyTyped ecosystem flourishes, providing type declaration files for a vast number of JavaScript libraries, which accelerates adoption.
  - Editor tooling becomes highly responsive, with improved intellisense, refactoring, and compile-time checks integrated into popular editors.
- 2020s: Modern language enhancements and broader adoption
  - 4.x series introduces features that improve type expressiveness and developer ergonomics, such as variadic tuple types, more precise control over type inference, and improved performance in the compiler.
  - New language capabilities like template literal types, improved module resolution, and incremental/build performance enhancements help TypeScript scale with modern codebases.
  - The ecosystem expands beyond front-end (back-end, tooling, and other domains) and TypeScript becomes a staple in many large-scale projects.
- 2023–present: Stabilization, refinement, and long-term direction
  - TypeScript continues to evolve with regular releases that emphasize developer experience, performance, and compatibility with evolving JavaScript/ECMAScript features.
  - The language remains deeply intertwined with popular frameworks (notably Angular) and is widely used in both client-side and server-side development.

Why TypeScript gained traction
- Stronger guarantees for large codebases: Optional static typing helps catch errors at compile time, improves maintainability, and enables better tooling (refactoring, navigation, auto-completion).
- Tight editor integration: The TypeScript Language Service powers rich IDE features across editors, making development smoother and faster.
- Ecosystem support: DefinitelyTyped and npm allow a vast library ecosystem to be typed progressively, lowering the barrier to adopting TypeScript in existing projects.
- Popular framework influence: Angular’s early adoption and heavy use of TypeScript helped popularize the language in enterprise-grade applications. Over time, many other projects and teams adopted TypeScript for the same benefits.
- Compatibility and migration: TypeScript is designed to be a superset of JavaScript, with gradual typing—teams can adopt it gradually and progressively tighten types as needed.

Design goals and characteristics
- Optional, gradual typing: Developers can add types incrementally, starting with plain JavaScript and gradually introducing typings.
- Structural typing: Type compatibility is based on shape rather than explicit declarations, enabling flexible, reusable interfaces.
- Rich type system: Includes unions, intersections, generics, mapped types, conditional types, template literal types, and more, enabling expressive type expressions.
```

## Go helpers

The Go tabs on the rest of this page are fragments. They call the helpers below, which need the imports `bytes`, `encoding/json`, `fmt`, `io`, `net/http`, and `os`. `callTool` is application-defined: it takes a tool name and its decoded arguments and returns the tool's output. Tool definitions such as `searchTool` are built with `fn` from the example above.

When a stop check fires on a reply that still contains tool calls, the fragments call `finish`, which runs the pending calls and then asks for one final answer with tool calling forbidden. Fragments that stop by leaving the loop after a tool round (a token, cost, or step budget in the loop condition) need the same final turn, shown in [Final response after stop](#final-response-after-stop).

```go title="Go" lines theme={null}
type ToolCall struct {
	ID       string `json:"id"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

type Usage struct {
	TotalTokens int     `json:"total_tokens"`
	Cost        float64 `json:"cost"`
}

// Message is one assistant reply, with the response's finish reason and usage attached
type Message struct {
	Content      string     `json:"content"`
	ToolCalls    []ToolCall `json:"tool_calls"`
	FinishReason string     `json:"-"`
	Usage        Usage      `json:"-"`
}

// ToolResult is one executed tool call
type ToolResult struct {
	CallID   string
	ToolName string
	Result   map[string]any
}

// Message is the tool-role message that returns the result to the model
func (r ToolResult) Message() map[string]string {
	content, _ := json.Marshal(r.Result)
	return map[string]string{"role": "tool", "tool_call_id": r.CallID, "content": string(content)}
}

// send makes one request. Pass "none" as toolChoice to keep the tools in the request but forbid calls.
func send(model string, messages []any, tools []any, toolChoice ...string) (Message, json.RawMessage) {
	request := map[string]any{"model": model, "messages": messages, "tools": tools}
	if len(toolChoice) > 0 {
		request["tool_choice"] = toolChoice[0]
	}
	body, _ := json.Marshal(request)
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	raw, err := io.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		panic(err)
	}
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("request failed: %s: %s", resp.Status, raw))
	}
	var out struct {
		Choices []struct {
			Message      json.RawMessage `json:"message"`
			FinishReason string          `json:"finish_reason"`
		} `json:"choices"`
		Usage Usage `json:"usage"`
	}
	if err := json.Unmarshal(raw, &out); err != nil {
		panic(fmt.Sprintf("decode response: %v", err))
	}
	if len(out.Choices) == 0 {
		panic(fmt.Sprintf("no choices in response: %s", raw))
	}
	var msg Message
	if err := json.Unmarshal(out.Choices[0].Message, &msg); err != nil {
		panic(fmt.Sprintf("decode message: %v", err))
	}
	msg.FinishReason = out.Choices[0].FinishReason
	msg.Usage = out.Usage
	return msg, out.Choices[0].Message
}

// execTools runs each call through callTool and keeps the call ID with its result
func execTools(calls []ToolCall) []ToolResult {
	var results []ToolResult
	for _, tc := range calls {
		var args map[string]any
		result := map[string]any{"error": "invalid arguments"}
		if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err == nil {
			result = callTool(tc.Function.Name, args)
		}
		results = append(results, ToolResult{CallID: tc.ID, ToolName: tc.Function.Name, Result: result})
	}
	return results
}

// runTools runs the calls and returns their tool-role messages
func runTools(calls []ToolCall) []any {
	var messages []any
	for _, r := range execTools(calls) {
		messages = append(messages, r.Message())
	}
	return messages
}

// finish runs any pending tool calls, then makes one final turn with tool calling forbidden
func finish(model string, messages []any, tools []any, msg Message, raw json.RawMessage) string {
	if len(msg.ToolCalls) == 0 {
		return msg.Content
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
	final, _ := send(model, messages, tools, "none")
	return final.Content
}
```

```typescript title="TypeScript" lines theme={null}
type ToolCall = { id: string; function: { name: string; arguments: string } };

type Usage = { total_tokens: number; cost: number };

// Message is one assistant reply, with the response's finish reason and usage attached
type Message = { content: string; tool_calls?: ToolCall[]; finishReason: string; usage: Usage };

// ToolResult is one executed tool call
type ToolResult = { callId: string; toolName: string; result: Record<string, unknown> };

// toolMessage is the tool-role message that returns the result to the model
const toolMessage = (r: ToolResult) => ({
  role: 'tool',
  tool_call_id: r.callId,
  content: JSON.stringify(r.result),
});

// send makes one request. Pass 'none' as toolChoice to keep the tools in the request but forbid calls.
async function send(
  model: string,
  messages: unknown[],
  tools: unknown[],
  toolChoice?: string,
): Promise<[Message, unknown]> {
  const request: Record<string, unknown> = { model, messages, tools };
  if (toolChoice) request.tool_choice = toolChoice;
  const resp = await fetch('https://openrouter.ai/api/v1/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  const raw = await resp.text();
  if (!resp.ok) throw new Error(`request failed: ${resp.status}: ${raw}`);
  const out = JSON.parse(raw);
  if (!out.choices?.length) throw new Error(`no choices in response: ${raw}`);
  const choice = out.choices[0];
  if (choice.error) throw new Error(choice.error.message ?? 'provider failed');
  const msg: Message = {
    content: choice.message.content ?? '',
    tool_calls: choice.message.tool_calls,
    finishReason: choice.finish_reason,
    usage: out.usage,
  };
  return [msg, choice.message];
}

// execTools runs each call through callTool and keeps the call ID with its result
async function execTools(calls: ToolCall[]): Promise<ToolResult[]> {
  const results: ToolResult[] = [];
  for (const tc of calls) {
    let result: Record<string, unknown> = { error: 'invalid arguments' };
    try {
      const args = JSON.parse(tc.function.arguments);
      result = await callTool(tc.function.name, args);
    } catch {}
    results.push({ callId: tc.id, toolName: tc.function.name, result });
  }
  return results;
}

// runTools runs the calls and returns their tool-role messages
async function runTools(calls: ToolCall[]) {
  return (await execTools(calls)).map(toolMessage);
}

// finish runs any pending tool calls, then makes one final turn with tool calling forbidden
async function finish(model: string, messages: unknown[], tools: unknown[], msg: Message, raw: unknown) {
  if (!msg.tool_calls?.length) return msg.content;
  messages = [...messages, raw, ...(await runTools(msg.tool_calls))];
  const [final] = await send(model, messages, tools, 'none');
  return final.content;
}
```

```python title="Python" lines theme={null}
import json
import os

import requests


def send(model, messages, tools, tool_choice=None):
    """Make one request. Pass "none" as tool_choice to keep the tools in the request but forbid calls.

    Returns the assistant message, the finish reason, and the response usage."""
    request = {"model": model, "messages": messages, "tools": tools}
    if tool_choice:
        request["tool_choice"] = tool_choice
    resp = requests.post(
        "https://openrouter.ai/api/v1/chat/completions",
        headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
        json=request,
    )
    if resp.status_code != 200:
        raise RuntimeError(f"request failed: {resp.status_code}: {resp.text}")
    data = resp.json()
    if not data.get("choices"):
        raise RuntimeError(f"no choices in response: {data}")
    choice = data["choices"][0]
    return choice["message"], choice.get("finish_reason"), data.get("usage", {})


def exec_tools(calls):
    """Run each call through call_tool and keep the call ID with its result."""
    results = []
    for tc in calls:
        try:
            args = json.loads(tc["function"]["arguments"])
            result = call_tool(tc["function"]["name"], args)
        except (json.JSONDecodeError, TypeError):
            result = {"error": "invalid arguments"}
        results.append({"call_id": tc["id"], "tool_name": tc["function"]["name"], "result": result})
    return results


def tool_message(r):
    """The tool-role message that returns a result to the model."""
    return {"role": "tool", "tool_call_id": r["call_id"], "content": json.dumps(r["result"])}


def run_tools(calls):
    """Run the calls and return their tool-role messages."""
    return [tool_message(r) for r in exec_tools(calls)]


def finish(model, messages, tools, msg):
    """Run any pending tool calls, then make one final turn with tool calling forbidden."""
    if not msg.get("tool_calls"):
        return msg.get("content") or ""
    messages = messages + [msg] + run_tools(msg["tool_calls"])
    final, _, _ = send(model, messages, tools, "none")
    return final.get("content") or ""

```

```bash title="cURL" lines theme={null}
# send MODEL MESSAGES TOOLS [TOOL_CHOICE]: makes one request and prints the response JSON.
# Pass "none" as TOOL_CHOICE to keep the tools in the request but forbid calls.
send() {
  jq -n --arg model "$1" --argjson messages "$2" --argjson tools "$3" --arg choice "${4:-}" \
    '{model: $model, messages: $messages, tools: $tools} + (if $choice != "" then {tool_choice: $choice} else {} end)' |
  curl -sS --fail-with-body https://openrouter.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $OPENROUTER_API_KEY" \
    -H "Content-Type: application/json" \
    -d @- | jq -e 'if (.choices | length) > 0 then . else error("no choices in response") end'
}

# run_tools MESSAGE: runs each tool call through call_tool and prints the tool-role messages as a JSON array
run_tools() {
  local results="[]" call args result
  while read -r call; do
    args=$(jq -r '.function.arguments' <<<"$call")
    if jq -e 'type == "object"' <<<"$args" >/dev/null 2>&1; then
      result=$(call_tool "$(jq -r '.function.name' <<<"$call")" "$args")
    else
      result='{"error":"invalid arguments"}'
    fi
    results=$(jq -c --argjson call "$call" --arg content "$result" \
      '. + [{role: "tool", tool_call_id: $call.id, content: $content}]' <<<"$results")
  done < <(jq -c '.tool_calls // [] | .[]' <<<"$1")
  echo "$results"
}

# finish MODEL MESSAGES TOOLS RESPONSE: runs any pending tool calls, then makes one final turn with tool calling forbidden
finish() {
  local msg results messages
  msg=$(jq -c '.choices[0].message' <<<"$4")
  if [ "$(jq '.tool_calls // [] | length' <<<"$msg")" -eq 0 ]; then
    jq -r '.content' <<<"$msg"
    return
  fi
  results=$(run_tools "$msg")
  messages=$(jq -c --argjson msg "$msg" --argjson results "$results" '. + [$msg] + $results' <<<"$2")
  send "$1" "$messages" "$3" none | jq -r '.choices[0].message.content'
}
```

## Built-in Stop Conditions

### stepCountIs(n)

Stop after a specific number of steps:

```typescript lines theme={null}
import { stepCountIs } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Analyze this data',
  tools: [analysisTool],
  stopWhen: stepCountIs(10), // Stop after 10 steps
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, step_count_is

result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Analyze this data",
        "tools": [analysis_tool],
        "stop_when": step_count_is(10),  # Stop after 10 steps
    },
)

```

```go title="Go" lines theme={null}
tools := []any{analysisTool}
messages := []any{map[string]string{"role": "user", "content": "Analyze this data"}}

var text string
for step := 1; ; step++ {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	if len(msg.ToolCalls) == 0 || step == 10 { // Stop after 10 steps
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### hasToolCall(name)

Stop when a specific tool is called:

```typescript lines theme={null}
import { hasToolCall } from '@openrouter/agent';

const finishTool = tool({
  name: 'finish',
  description: 'Call this when the task is complete',
  inputSchema: z.object({
    summary: z.string(),
  }),
  execute: async (params) => ({ done: true }),
});

const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'Research until you have enough information, then call finish',
  tools: [searchTool, finishTool],
  stopWhen: hasToolCall('finish'), // Stop when finish tool is called
});
```

```python title="Python" lines theme={null}
from pydantic import BaseModel
from openrouter_agent import call_model, has_tool_call, tool

class FinishInput(BaseModel):
    summary: str

finish_tool = tool(
    name="finish",
    description="Call this when the task is complete",
    input_schema=FinishInput,
    execute=lambda params, ctx: {"done": True},
)

result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Research the history of the Eiffel Tower until you have enough information, then call finish",
        "tools": [search_tool, finish_tool],
        "stop_when": has_tool_call("finish"),  # Stop when finish tool is called
    },
)

```

```go title="Go" lines theme={null}
finishTool := fn("finish", "Call this when the task is complete", "summary")

tools := []any{searchTool, finishTool}
messages := []any{map[string]string{"role": "user", "content": "Research until you have enough information, then call finish"}}

var msg Message
var raw any
for done := false; !done; {
	msg, raw = send("openai/gpt-5-nano", messages, tools)
	if len(msg.ToolCalls) == 0 {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
	for _, tc := range msg.ToolCalls {
		if tc.Function.Name == "finish" {
			done = true // Stop when finish tool is called
		}
	}
}
```

### maxTokensUsed(n)

Stop after using a certain number of tokens:

```typescript lines theme={null}
import { maxTokensUsed } from '@openrouter/agent';

const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'Generate content',
  tools: [writingTool],
  stopWhen: maxTokensUsed(5000), // Stop after 5000 total tokens
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, max_tokens_used

result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Generate content",
        "tools": [writing_tool],
        "stop_when": max_tokens_used(5000),  # Stop after 5000 total tokens
    },
)
```

```go title="Go" lines theme={null}
tools := []any{writingTool}
messages := []any{map[string]string{"role": "user", "content": "Generate content"}}

var text string
totalTokens := 0
for totalTokens < 5000 { // Stop after 5000 total tokens
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	text = msg.Content
	totalTokens += msg.Usage.TotalTokens
	if len(msg.ToolCalls) == 0 {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### maxCost(amount)

Stop after reaching a cost threshold:

```typescript lines theme={null}
import { callModel, maxCost } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5.2',
  input: 'Perform extensive analysis',
  tools: [analysisTool] as const,
  stopWhen: maxCost(1.00), // Stop after $1.00 spent
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, max_cost

result = call_model(
    client,
    {
        "model": "openai/gpt-5.2",
        "input": "Perform extensive analysis",
        "tools": [analysis_tool],
        "stop_when": max_cost(1.00),  # Stop after $1.00 spent
    },
)

```

```go title="Go" lines theme={null}
tools := []any{analysisTool}
messages := []any{map[string]string{"role": "user", "content": "Perform extensive analysis"}}

var text string
totalCost := 0.0
for totalCost < 1.00 { // Stop after $1.00 spent
	msg, raw := send("openai/gpt-5.2", messages, tools)
	text = msg.Content
	totalCost += msg.Usage.Cost
	if len(msg.ToolCalls) == 0 {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### finishReasonIs(reason)

Stop on a specific finish reason:

```typescript lines theme={null}
import { callModel, finishReasonIs } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Complete this task',
  tools: [taskTool],
  stopWhen: finishReasonIs('stop'), // Stop when model finishes naturally
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, finish_reason_is

result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Complete this task",
        "tools": [task_tool],
        "stop_when": finish_reason_is("stop"),  # Stop when model finishes naturally
    },
)

```

```go title="Go" lines theme={null}
tools := []any{taskTool}
messages := []any{map[string]string{"role": "user", "content": "Complete this task"}}

var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	text = msg.Content
	if msg.FinishReason == "stop" || len(msg.ToolCalls) == 0 { // Stop when model finishes naturally
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

## Combining Conditions

Pass an array to stop on any condition:

```typescript lines theme={null}
import { stepCountIs, hasToolCall, maxCost } from '@openrouter/agent';

const result = openrouter.callModel({
  model: 'openai/gpt-5.2',
  input: 'Research thoroughly but stay within budget',
  tools: [searchTool, finishTool],
  stopWhen: [
    stepCountIs(10),        // Maximum 10 steps
    maxCost(0.50),          // Maximum $0.50
    hasToolCall('finish'),  // Or when finish is called
  ],
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, step_count_is, has_tool_call, max_cost

result = call_model(
    client,
    {
        "model": "openai/gpt-5.2",
        "input": "Research thoroughly but stay within budget",
        "tools": [search_tool, finish_tool],
        "stop_when": [
            step_count_is(10),        # Maximum 10 steps
            max_cost(0.50),           # Maximum $0.50
            has_tool_call("finish"),  # Or when finish is called
        ],
    },
)

```

```go title="Go" lines theme={null}
tools := []any{searchTool, finishTool}
messages := []any{map[string]string{"role": "user", "content": "Research thoroughly but stay within budget"}}

var text string
totalCost := 0.0
for step, done := 0, false; step < 10 && totalCost < 0.50 && !done; step++ { // Maximum 10 steps, maximum $0.50
	msg, raw := send("openai/gpt-5.2", messages, tools)
	text = msg.Content
	totalCost += msg.Usage.Cost
	if len(msg.ToolCalls) == 0 {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
	for _, tc := range msg.ToolCalls {
		if tc.Function.Name == "finish" {
			done = true // Or when finish is called
		}
	}
}
```

Execution stops when **any** condition is met.

## Final Response After Stop

A stop condition can fire while the model is still emitting tool calls. By default, the SDK then executes those pending tool calls (so they have matching outputs) and makes one more model turn with `toolChoice: 'none'`, appending a built-in final-answer directive (exported as `DEFAULT_FINAL_RESPONSE_DIRECTIVE`) as a user message — so the run ends with a real natural-language answer instead of a half-finished tool call. Tools stay in the request; only calling is forbidden, which preserves the prompt-cache prefix.

Tune it with `allowFinalResponse`:

```typescript lines theme={null}
import { callModel, stepCountIs } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5.2',
  input: 'Research this topic',
  tools: [searchTool] as const,
  stopWhen: stepCountIs(5),
  // default (omitted or `true`): final turn + built-in directive

  // override the directive wording:
  // allowFinalResponse: 'Summarize what you found so far.',
  // make the final turn without appending any message:
  // allowFinalResponse: '',
  // disable the final turn (run ends on the halted tool-call turn):
  // allowFinalResponse: false,
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, step_count_is

result = call_model(
    client,
    {
        "model": "openai/gpt-5.2",
        "input": "Research the history of the Python programming language",
        "tools": [search_tool],
        "stop_when": step_count_is(5),
        # default (omitted or `True`): final turn + built-in directive

        # override the directive wording:
        # "allow_final_response": "Summarize what you found so far.",
        # make the final turn without appending any message:
        # "allow_final_response": "",
        # disable the final turn (run ends on the halted tool-call turn):
        # "allow_final_response": False,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{searchTool}
messages := []any{map[string]string{"role": "user", "content": "Research the history of the Python programming language"}}

// default: final turn + directive. Override the wording below,
// use "" to make the final turn without appending any message,
// or set allowFinalResponse = false to end on the halted tool-call turn.
allowFinalResponse := true
directive := "Summarize what you found so far."

var text string
pending := false
for step := 0; step < 5; step++ { // stepCountIs(5)
	msg, raw := send("openai/gpt-5.2", messages, tools)
	text = msg.Content
	pending = len(msg.ToolCalls) > 0
	if !pending {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...) // pending calls get outputs
}
if pending && allowFinalResponse {
	if directive != "" {
		messages = append(messages, map[string]string{"role": "user", "content": directive})
	}
	msg, _ := send("openai/gpt-5.2", messages, tools, "none") // tools stay, calling forbidden
	text = msg.Content
}

```

> [!NOTE]
>
> Without the directive, models that emit tool-call syntax as text can leak an unparsed tool call (e.g. `<tool_call>…`) into the final content when the loop stops mid-tool-call. The default directive exists to prevent exactly that.

The final turn only happens when a stop condition halted the loop while the last response contained executable tool calls. It never fires on natural completion, HITL/approval pauses, or interruption.

### Empty final output after tool rounds

Some mini-class models intermittently treat a successful tool call as the terminal answer, returning an empty `output` array on the final turn. By default, the SDK retries that follow-up once, and if it's still empty, resolves the run with empty text instead of throwing `Invalid final response: empty or invalid output`.

This tolerance only applies after at least one completed tool execution round. Runs that produce no tool work still throw on an empty final response.

Opt back into the strict contract with `strictFinalResponse: true`:

```typescript lines theme={null}
import { callModel } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5-mini',
  input: 'Look up the weather in Paris',
  tools: [weatherTool] as const,
  // Throw if the final turn after tool rounds returns empty output
  // (restores pre-0.8.0 behavior).
  strictFinalResponse: true,
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model

result = call_model(
    client,
    {
        "model": "openai/gpt-5-mini",
        "input": "Look up the weather in Paris",
        "tools": [weather_tool],
        # Raise if the final turn after tool rounds returns empty output
        # (restores pre-0.8.0 behavior).
        "strict_final_response": True,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{weatherTool}
messages := []any{map[string]string{"role": "user", "content": "Look up the weather in Paris"}}

// Throw if the final turn after tool rounds returns empty output
// (restores pre-0.8.0 behavior).
strictFinalResponse := true

var text string
toolRounds := 0
for step := 0; step < 10; step++ {
	msg, raw := send("openai/gpt-5-mini", messages, tools)
	text = msg.Content
	if len(msg.ToolCalls) == 0 {
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
	toolRounds++
}
if text == "" && (strictFinalResponse || toolRounds == 0) {
	log.Fatal("empty final response")
}
```

Set `strictFinalResponse: true` if your code depends on non-empty final text and you'd rather see an error than an empty completion. Leave it off (the default) to keep tool-terminal runs from being reported as failures.

## Custom Stop Conditions

Create custom conditions with a function:

```typescript lines theme={null}
import { callModel } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Process data',
  tools: [processTool] as const,
  stopWhen: ({ steps }) => {
    // Stop after 20 steps
    if (steps.length >= 20) return true;

    // Stop if last step had no tool calls
    const lastStep = steps[steps.length - 1];
    if (lastStep && !lastStep.toolCalls?.length) return true;

    // Continue otherwise
    return false;
  },
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model


def should_stop(ctx):
    steps = ctx["steps"]
    # Stop after 20 steps
    if len(steps) >= 20:
        return True

    # Stop if last step had no tool calls
    last_step = steps[-1] if steps else None
    if last_step and not last_step.tool_calls:
        return True

    # Continue otherwise
    return False


result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Process data",
        "tools": [process_tool],
        "stop_when": should_stop,
    },
)
```

```go title="Go" lines theme={null}
tools := []any{processTool}
messages := []any{map[string]string{"role": "user", "content": "Process data"}}

stopWhen := func(steps []Message) bool {
	// Stop after 20 steps
	if len(steps) >= 20 {
		return true
	}

	// Stop if last step had no tool calls
	if n := len(steps); n > 0 && len(steps[n-1].ToolCalls) == 0 {
		return true
	}

	// Continue otherwise
	return false
}

var steps []Message
var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if stopWhen(steps) {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### StopConditionContext

Custom functions receive:

| Property | Type | Description |
| - | - | - |
| `steps` | `StepResult[]` | All completed steps including results and usage |

### StepResult

Each step contains:

```typescript lines theme={null}
interface StepResult {
  response: Response;
  toolCalls?: ParsedToolCall[];
  toolResults?: ToolExecutionResult[];
  usage?: Usage | null; // token counts and `cost`, as in `step.usage?.cost`
}
```

## Advanced Patterns

### Time-Based Stopping

Stop after a time limit:

```typescript lines theme={null}
import { callModel } from '@openrouter/agent';

const startTime = Date.now();
const maxDuration = 30000; // 30 seconds

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Work on this task',
  tools: [workTool] as const,
  stopWhen: () => {
    return Date.now() - startTime > maxDuration;
  },
});
```

```python title="Python" lines theme={null}
import time
from openrouter_agent import call_model

start_time = time.time()
max_duration = 30  # 30 seconds

result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Work on this task",
        "tools": [work_tool],
        "stop_when": lambda ctx: time.time() - start_time > max_duration,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{workTool}
messages := []any{map[string]string{"role": "user", "content": "Work on this task"}}

startTime := time.Now()
maxDuration := 30 * time.Second // 30 seconds

stopWhen := func() bool {
	return time.Since(startTime) > maxDuration
}

var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	if len(msg.ToolCalls) == 0 || stopWhen() {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### Content-Based Stopping

Stop based on response content:

```typescript lines theme={null}
import { callModel } from '@openrouter/agent';

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Use the search tool to find the capital of Australia. Keep searching until you find the answer.',
  tools: [searchTool] as const,
  stopWhen: ({ steps }) => {
    const lastStep = steps[steps.length - 1];
    if (!lastStep) return false;

    // Check if the last step contains certain keywords
    const content = JSON.stringify(lastStep) ?? '';
    return content.includes('ANSWER FOUND') || content.includes('TASK COMPLETE');
  },
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model


def should_stop(ctx):
    steps = ctx["steps"]
    last_step = steps[-1] if steps else None
    if not last_step:
        return False

    # Check if the last step contains certain keywords
    content = str(last_step)
    return "ANSWER FOUND" in content or "TASK COMPLETE" in content


result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Use the search tool to find the capital of Australia. Keep searching until you find the answer.",
        "tools": [search_tool],
        "stop_when": should_stop,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{searchTool}
messages := []any{map[string]string{"role": "user", "content": "Use the search tool to find the capital of Australia. Keep searching until you find the answer."}}

stopWhen := func(steps []Message) bool {
	if len(steps) == 0 {
		return false
	}
	lastStep := steps[len(steps)-1]

	// Check if the last step contains certain keywords
	content, _ := json.Marshal(lastStep)
	return strings.Contains(string(content), "ANSWER FOUND") || strings.Contains(string(content), "TASK COMPLETE")
}

var steps []Message
var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if len(msg.ToolCalls) == 0 || stopWhen(steps) {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### Quality-Based Stopping

Stop when results meet quality threshold:

```typescript lines theme={null}
const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input:
    'Use the improver and scorer tools to improve this text until the scorer gives it a score above 0.9: "Our product is good and people like it alot."',
  tools: [improverTool, scorerTool] as const,
  stopWhen: ({ steps }) => {
    // Look for score in tool results
    for (const step of steps) {
      for (const result of step.toolResults ?? []) {
        if (result.toolName === 'scorer' && result.result?.score > 0.9) {
          return true;
        }
      }
    }
    return false;
  },
});
```

```python title="Python" lines theme={null}
import json

from openrouter_agent import call_model


def should_stop(ctx):
    # Look for score in tool results (each tool result is a dict)
    for step in ctx["steps"]:
        for tool_result in step.tool_results or []:
            name = tool_result.get("tool_name") or tool_result.get("name")
            output = tool_result.get("result") or tool_result.get("output") or {}
            if isinstance(output, str):
                try:
                    output = json.loads(output)
                except ValueError:
                    continue
            if name == "scorer" and isinstance(output, dict) and output.get("score", 0) > 0.9:
                return True
    return False


result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": 'Use the improver and scorer tools to improve this text until the scorer gives it a score above 0.9: "Our product is good and people like it alot."',
        "tools": [improver_tool, scorer_tool],
        "stop_when": should_stop,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{improverTool, scorerTool}
messages := []any{map[string]string{"role": "user", "content": `Use the improver and scorer tools to improve this text until the scorer gives it a score above 0.9: "Our product is good and people like it alot."`}}

var toolResults []ToolResult
stopWhen := func() bool {
	// Look for score in tool results
	for _, r := range toolResults {
		if score, ok := r.Result["score"].(float64); r.ToolName == "scorer" && ok && score > 0.9 {
			return true
		}
	}
	return false
}

var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	if len(msg.ToolCalls) == 0 {
		text = msg.Content
		break
	}
	messages = append(messages, raw)
	for _, r := range execTools(msg.ToolCalls) {
		toolResults = append(toolResults, r)
		messages = append(messages, r.Message()) // tool-role message with the matching call ID
	}
	// Check the score before another tool-enabled turn
	if stopWhen() {
		final, _ := send("openai/gpt-5-nano", messages, tools, "none")
		text = final.Content
		break
	}
}
```

### Combination with Early Exit

Combine conditions for complex logic:

```typescript expandable lines theme={null}
import { stepCountIs, maxCost } from '@openrouter/agent';

const result = openrouter.callModel({
  model: 'openai/gpt-5.2',
  input: 'Complex research task',
  tools: [searchTool, analysisTool, summarizeTool],
  stopWhen: [
    // Hard limits
    stepCountIs(50),
    maxCost(5.00),

    // Custom success condition
    ({ steps }) => {
      const lastStep = steps[steps.length - 1];
      const hasSummary = lastStep?.toolCalls?.some(
        tc => tc.name === 'summarize'
      );
      return hasSummary;
    },
  ],
});
```

## Migration from maxToolRounds

If you were using `maxToolRounds`, migrate to `stopWhen`:

```typescript lines theme={null}
import { callModel, stepCountIs } from '@openrouter/agent';

// Before: maxToolRounds
// const result = callModel(openrouter, {
//   model: 'openai/gpt-5-nano',
//   input: 'Hello',
//   tools: [myTool] as const,
//   maxToolRounds: 5,
// });

// After: stopWhen
const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Hello',
  tools: [myTool] as const,
  stopWhen: stepCountIs(5),
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model, step_count_is

# Before: max_tool_rounds
# result = call_model(
#     client,
#     {
#         "model": "openai/gpt-5-nano",
#         "input": "Hello",
#         "tools": [my_tool],
#         "max_tool_rounds": 5,
#     },
# )

# After: stop_when
result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Hello",
        "tools": [my_tool],
        "stop_when": step_count_is(5),
    },
)

```

```go title="Go" lines theme={null}
tools := []any{myTool}
messages := []any{map[string]string{"role": "user", "content": "Hello"}}

// Before: maxToolRounds
// for round := 0; round < 5; round++ { ... }

// After: stopWhen
stopWhen := stepCountIs(5)

var steps []Message
var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if len(msg.ToolCalls) == 0 || stopWhen(steps) {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### Default Behavior

If `stopWhen` is not specified, the loop runs until the model produces a turn with no tool calls. Always pass an explicit `stopWhen` (e.g. `stepCountIs(n)`, `maxCost(...)`) to bound iterations, cost, or tokens.

## Best Practices

### Always Set Limits

Always include a hard limit to prevent runaway execution:

```typescript lines theme={null}
stopWhen: [
  stepCountIs(100),    // Hard limit
  maxCost(10.00),      // Budget limit
  customCondition,     // Your logic
],
```

```python title="Python" lines theme={null}
"stop_when": [
    step_count_is(100),  # Hard limit
    max_cost(10.00),  # Budget limit
    custom_condition,  # Your logic
],
```

```go title="Go" lines theme={null}
stopWhen := []func([]Message) bool{
	stepCountIs(100), // Hard limit
	maxCost(10.00),   // Budget limit
	customCondition,  // Your logic
}

var steps []Message
var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if len(msg.ToolCalls) == 0 || slices.ContainsFunc(stopWhen, func(c func([]Message) bool) bool { return c(steps) }) {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

### Log Stop Reasons

Track why execution stopped:

```typescript lines theme={null}
const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Task',
  tools: [taskTool] as const,
  stopWhen: ({ steps }) => {
    if (steps.length >= 10) {
      console.log('Stopped: step limit');
      return true;
    }
    const totalCost = steps.reduce((sum, step) => sum + (step.usage?.cost ?? 0), 0);
    if (totalCost >= 1.00) {
      console.log('Stopped: cost limit');
      return true;
    }
    return false;
  },
});
```

```python title="Python" lines theme={null}
from openrouter_agent import call_model


def stop_when(ctx):
    steps = ctx["steps"]
    if len(steps) >= 10:
        print("Stopped: step limit")
        return True
    total_cost = sum(getattr(step.usage, "cost", None) or 0 for step in steps)
    if total_cost >= 1.00:
        print("Stopped: cost limit")
        return True
    return False


result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Task",
        "tools": [task_tool],
        "stop_when": stop_when,
    },
)

```

```go title="Go" lines theme={null}
tools := []any{taskTool}
messages := []any{map[string]string{"role": "user", "content": "Task"}}

var steps []Message
stopWhen := func() bool {
	if len(steps) >= 10 {
		fmt.Println("Stopped: step limit")
		return true
	}
	totalCost := 0.0
	for _, step := range steps {
		totalCost += step.Usage.Cost
	}
	if totalCost >= 1.00 {
		fmt.Println("Stopped: cost limit")
		return true
	}
	return false
}

var text string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if len(msg.ToolCalls) == 0 || stopWhen() {
		text = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}

```

### Test Conditions

Verify conditions work as expected:

```typescript lines theme={null}
// Test with low limits first
const testResult = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Test task',
  tools: [testTool],
  stopWhen: stepCountIs(2), // Low limit for testing
});
```

```python title="Python" lines theme={null}
# Test with low limits first
test_result = call_model(
    client,
    {
        "model": "openai/gpt-5-nano",
        "input": "Test task",
        "tools": [test_tool],
        "stop_when": step_count_is(2),  # Low limit for testing
    },
)

```

```go title="Go" lines theme={null}
tools := []any{testTool}
messages := []any{map[string]string{"role": "user", "content": "Test task"}}

// Test with low limits first
stopWhen := stepCountIs(2) // Low limit for testing

var steps []Message
var testResult string
for {
	msg, raw := send("openai/gpt-5-nano", messages, tools)
	steps = append(steps, msg)
	if len(msg.ToolCalls) == 0 || stopWhen(steps) {
		testResult = finish("openai/gpt-5-nano", messages, tools, msg, raw)
		break
	}
	messages = append(messages, raw)
	messages = append(messages, runTools(msg.ToolCalls)...)
}
```

## See Also

* **[Tools](https://openrouter.ai/docs/agent-sdk/call-model/tools.md)** - Multi-turn orchestration
* **[Dynamic Parameters](https://openrouter.ai/docs/agent-sdk/call-model/dynamic-parameters.md)** - Adaptive behavior
* **[nextTurnParams](https://openrouter.ai/docs/agent-sdk/call-model/next-turn-params.md)** - Tool-driven modifications
