> ## 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.

# Tool Approval & State Persistence

> Add human-in-the-loop approval gates for sensitive tools and persist conversation state across callModel invocations.

## Why Approval Gates?

Some tools — sending emails, making payments, deleting records — should not auto-execute without human review. The SDK provides two mechanisms to control this:

* **`requireApproval`** — pause execution when the model calls sensitive tools, giving users a chance to approve or reject each call
* **`StateAccessor`** — persist conversation state between `callModel` invocations so approval decisions, message history, and tool results survive across runs

Together, these enable human-in-the-loop workflows where a user reviews tool calls before they execute, even across separate request/response cycles (e.g., in a web application).

## Tool-Level Approval

Add `requireApproval` directly on a tool definition. It accepts a boolean or a function:

### Always Require Approval

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

// Replace with your email provider integration
async function sendEmail(params: { to: string; subject: string; body: string }) {
  console.log(`Sending email to ${params.to}: ${params.subject}`);
}

const sendEmailTool = tool({
  name: 'send_email',
  description: 'Send an email to a recipient',
  inputSchema: z.object({
    to: z.string().email(),
    subject: z.string(),
    body: z.string(),
  }),
  outputSchema: z.object({ sent: z.boolean() }),
  requireApproval: true,
  execute: async (params) => {
    await sendEmail(params);
    return { sent: true };
  },
});
```

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


# Replace with your email provider integration
async def send_email(params):
    print(f"Sending email to {params.to}: {params.subject}")


class SendEmailInput(BaseModel):
    to: str
    subject: str
    body: str


class SendEmailOutput(BaseModel):
    sent: bool


async def execute_send_email(params, ctx):
    await send_email(params)
    return SendEmailOutput(sent=True)


send_email_tool = tool(
    name="send_email",
    description="Send an email to a recipient",
    input_schema=SendEmailInput,
    output_schema=SendEmailOutput,
    require_approval=True,
    execute=execute_send_email,
)

```

```go title="Go" lines theme={null}
// Replace with your email provider integration
func sendEmail(to, subject, body string) {
	fmt.Printf("Sending email to %s: %s\n", to, subject)
}

// Go has no agent SDK yet: your tool loop checks RequireApproval
// before calling Execute.
type ApprovalTool struct {
	Name            string
	Description     string
	Parameters      map[string]any
	RequireApproval bool
	Execute         func(args map[string]any) map[string]any
}

var sendEmailTool = ApprovalTool{
	Name:        "send_email",
	Description: "Send an email to a recipient",
	Parameters: map[string]any{
		"type": "object",
		"properties": map[string]any{
			"to":      map[string]any{"type": "string", "format": "email"},
			"subject": map[string]any{"type": "string"},
			"body":    map[string]any{"type": "string"},
		},
		"required": []string{"to", "subject", "body"},
	},
	RequireApproval: true,
	Execute: func(args map[string]any) map[string]any {
		sendEmail(fmt.Sprint(args["to"]), fmt.Sprint(args["subject"]), fmt.Sprint(args["body"]))
		return map[string]any{"sent": true}
	},
}
```

### Conditional Approval

Pass a function to require approval only in certain cases:

```typescript lines theme={null}
const deleteRecordTool = tool({
  name: 'delete_record',
  description: 'Delete a record from the database',
  inputSchema: z.object({ id: z.string() }),
  outputSchema: z.object({ deleted: z.boolean() }),
  requireApproval: async (params, context) => {
    // Only require approval for production deletions. Look the environment up
    // yourself: an argument the model fills in could be set to skip the review.
    return (await getRecordEnvironment(params.id)) === 'production';
  },
  execute: async (params) => {
    await deleteRecord(params.id);
    return { deleted: true };
  },
});
```

```python title="Python" lines theme={null}
class DeleteRecordInput(BaseModel):
    id: str


class DeleteRecordOutput(BaseModel):
    deleted: bool


def require_production_approval(params, ctx):
    # Only require approval for production deletions. Look the environment up
    # yourself: an argument the model fills in could be set to skip the review.
    return get_record_environment(params.id) == "production"


async def execute_delete_record(params, ctx):
    await delete_record(params.id)
    return DeleteRecordOutput(deleted=True)


delete_record_tool = tool(
    name="delete_record",
    description="Delete a record from the database",
    input_schema=DeleteRecordInput,
    output_schema=DeleteRecordOutput,
    require_approval=require_production_approval,
    execute=execute_delete_record,
)

```

```go title="Go" lines theme={null}
// RequireApproval is a function: your tool loop calls it with the
// parsed arguments before calling Execute.
type ConditionalApprovalTool struct {
	Name            string
	Description     string
	Parameters      map[string]any
	RequireApproval func(args map[string]any) bool
	Execute         func(args map[string]any) map[string]any
}

var deleteRecordTool = ConditionalApprovalTool{
	Name:        "delete_record",
	Description: "Delete a record from the database",
	Parameters: map[string]any{
		"type": "object",
		"properties": map[string]any{
			"id": map[string]any{"type": "string"},
		},
		"required": []string{"id"},
	},
	RequireApproval: func(args map[string]any) bool {
		// Only require approval for production deletions. Look the environment up
		// yourself: an argument the model fills in could be set to skip the review.
		return getRecordEnvironment(fmt.Sprint(args["id"])) == "production"
	},
	Execute: func(args map[string]any) map[string]any {
		deleteRecord(fmt.Sprint(args["id"]))
		return map[string]any{"deleted": true}
	},
}
```

The function receives the parsed tool arguments and a `TurnContext`, and can return a boolean or `Promise<boolean>`. Decide from data you control, such as the record's environment looked up by ID, not from an argument the model supplies.

## Call-Level Approval

Override tool-level settings with a `requireApproval` callback on `callModel` itself:

```typescript lines theme={null}
const result = callModel(openrouter, {
  model: 'openai/gpt-4o',
  input: 'Send an email and search for documents',
  tools: [sendEmailTool, searchTool] as const,
  state: myStateAccessor,
  requireApproval: (toolCall, context) => {
    // Only the read-only search tool skips review, so a tool added later needs approval by default
    return toolCall.name !== 'search_documents';
  },
});
```

```python title="Python" lines theme={null}
READ_ONLY_TOOLS = {"search_documents"}


def require_modifying_approval(tool_call, context):
    # Only known read-only tools skip review, so a tool added later needs approval by default
    return tool_call.name not in READ_ONLY_TOOLS


result = call_model(
    client,
    {
        "model": "openai/gpt-4o",
        "input": "Send an email and search for documents",
        "tools": [send_email_tool, search_tool],
        "state": my_state_accessor,
        "require_approval": require_modifying_approval,
    },
)

```

```go title="Go" lines theme={null}
// Go has no agent SDK yet, so your tool loop applies the precedence itself.
// A call-level callback, when set, overrides each tool's RequireApproval setting.
func needsApproval(tool ApprovalTool, args map[string]any, callLevel func(name string, args map[string]any) bool) bool {
	if callLevel != nil {
		return callLevel(tool.Name, args)
	}
	return tool.RequireApproval
}

func requireApproval(name string, args map[string]any) bool {
	// Only the read-only search tool skips review, so a tool added later needs approval by default
	return name != "search_documents"
}

// In your tool loop, for each call the model returns, with tool and args
// looked up and parsed from that call:
func runOrHold(tool ApprovalTool, args map[string]any) (result map[string]any, pending bool) {
	if needsApproval(tool, args, requireApproval) {
		return nil, true // save the call as pending and ask the user
	}
	return tool.Execute(args), false
}
```

The call-level callback takes priority over tool-level `requireApproval` settings when both are present, so write it to require approval unless a tool is known to be safe. A callback that lists the tools needing review silently skips review for every tool it does not name.

## How the Approval Flow Works

When tools with approval gates are called by the model, the SDK follows this flow:

1. **Model generates tool calls** — the model decides which tools to invoke
2. **SDK partitions tool calls** — each call is checked against `requireApproval` and split into two groups: those requiring approval and those that can auto-execute
3. **Auto-execute tools run immediately** — tools that don't need approval execute in parallel as normal
4. **State saves with pending approvals** — the conversation state updates to `status: 'awaiting_approval'` with the pending tool calls stored
5. **Control returns to the caller** — check `result.requiresApproval()` and inspect pending calls with `result.getPendingToolCalls()`
6. **Resume with decisions** — call `callModel` again with the same `state`, passing `approveToolCalls` and/or `rejectToolCalls` arrays of tool call IDs
7. **Approved tools execute** — the SDK runs approved tools and sends results to the model. Rejected tools send an error message to the model explaining the rejection
8. **Conversation continues** — the model processes tool results and generates the next response

## StateAccessor Interface

The `StateAccessor` interface enables any storage backend:

```typescript lines theme={null}
import type { StateAccessor, ConversationState } from '@openrouter/agent';

interface StateAccessor<TTools> {
  /** Load the current conversation state, or null if none exists */
  load: () => Promise<ConversationState<TTools> | null>;
  /** Save the conversation state */
  save: (state: ConversationState<TTools>) => Promise<void>;
}
```

### In-Memory Implementation

```typescript lines theme={null}
const conversations = new Map<string, ConversationState>();

function createStateAccessor(conversationId: string): StateAccessor {
  return {
    load: async () => conversations.get(conversationId) ?? null,
    save: async (state) => {
      conversations.set(conversationId, state);
    },
  };
}
```

```python title="Python" lines theme={null}
conversations = {}


class InMemoryStateAccessor:
    def __init__(self, conversation_id: str):
        self.conversation_id = conversation_id

    async def load(self):
        return conversations.get(self.conversation_id)

    async def save(self, state):
        conversations[self.conversation_id] = state


def create_state_accessor(conversation_id: str) -> InMemoryStateAccessor:
    return InMemoryStateAccessor(conversation_id)

```

```go title="Go" lines theme={null}
var conversations = map[string]*ConversationState{}

func createStateAccessor(conversationID string) StateAccessor {
	return StateAccessor{
		Load: func() (*ConversationState, error) {
			return conversations[conversationID], nil
		},
		Save: func(state *ConversationState) error {
			conversations[conversationID] = state
			return nil
		},
	}
}

```

For production use, implement `StateAccessor` with a persistent backend like Redis, a database, or file storage to survive process restarts.

## ConversationState

The state object tracks everything needed to resume a conversation:

| Field | Type | Description |
| - | - | - |
| `version` | `number?` | Serialization-contract version for this state blob. Absence means version `1`; `createInitialState` stamps `1` on new states. See [Serialization & Versioning](#serialization--versioning) |
| `id` | `string` | Unique conversation identifier |
| `messages` | `OpenResponsesInputUnion` | Full message history |
| `previousResponseId` | `string?` | Previous response ID for server-side chaining |
| `pendingToolCalls` | `ParsedToolCall[]?` | Tool calls awaiting human input (approval/rejection, HITL output, or unresolved manual `execute: false` calls) |
| `unsentToolResults` | `UnsentToolResult[]?` | Executed results not yet sent to model |
| `partialResponse` | `PartialResponse?` | Data captured during interruption |
| `interruptedBy` | `string?` | Signal from a new request that interrupted this conversation |
| `status` | `ConversationStatus` | Current state of the conversation |
| `createdAt` | `number` | Creation timestamp (Unix ms) |
| `updatedAt` | `number` | Last update timestamp (Unix ms) |

### Status Values

| Status | Meaning |
| - | - |
| `'in_progress'` | Conversation is actively processing |
| `'awaiting_approval'` | Paused, waiting for tool call approval/rejection |
| `'awaiting_hitl'` | Paused by a [HITL tool](https://openrouter.ai/docs/agent-sdk/call-model/tools.md#human-in-the-loop-hitl-tools) whose `onToolCalled` hook returned `null`; resume by supplying a `function_call_output` for each paused call |
| `'awaiting_client_tools'` | Paused because one or more [manual tools](https://openrouter.ai/docs/agent-sdk/call-model/tools.md#manual-tools) (`execute: false` / no execute fn) were called but not resolved. The unresolved calls are stored in `pendingToolCalls`. Resume by calling `callModel` again with new `input`; this clears the stale pendings and continues as a normal turn. Unlike `awaiting_approval` and `awaiting_hitl`, manual tools are not resumed via call IDs |
| `'awaiting_async_tools'` | Paused by a [deferred tool](https://openrouter.ai/docs/agent-sdk/call-model/async-tools.md) whose `run` called `ctx.defer(taskId)`. Any process can settle the task via `.resolve()` / `.fail()` / `.cancel()` (or `resumeToolResults`). To continue the conversation immediately, pass `run` when settling; omitting `run` only records the result and delivers it on the next `callModel({ state })` call. See [Async Tools](https://openrouter.ai/docs/agent-sdk/call-model/async-tools.md) |
| `'complete'` | Conversation finished normally |
| `'interrupted'` | Conversation was interrupted and can be resumed |

## Serialization & Versioning

`ConversationState` carries an optional `version` field that identifies the serialization contract of the blob. `createInitialState` stamps `version: 1`; older states without the field are treated as version `1`.

`StateAccessor.load` / `save` themselves are unchanged. Most callers still round-trip through `JSON.stringify` / `JSON.parse`. Use the opt-in helpers when you want typed errors and a migration hook for future serialization changes:

```typescript lines theme={null}
import {
  serializeConversationState,
  deserializeConversationState,
  UnsupportedStateVersionError,
  InvalidStateError,
} from '@openrouter/agent';
// Also available at the subpath:
// import { ... } from '@openrouter/agent/conversation-state';

const state: StateAccessor = {
  load: async () => {
    const blob = await redis.get(`conv:${id}`);
    if (!blob) return null;
    try {
      return deserializeConversationState(blob);
    } catch (err) {
      if (err instanceof UnsupportedStateVersionError) {
        // err.found and err.supported let you decide: reset, migrate, or fail
        console.error(`State version ${err.found} not in ${err.supported.join(', ')}`);
      }
      if (err instanceof InvalidStateError) {
        // Malformed JSON or missing required fields
      }
      throw err;
    }
  },
  save: async (s) => {
    await redis.set(`conv:${id}`, serializeConversationState(s));
  },
};
```

```python title="Python" lines theme={null}
from openrouter_agent import (
    serialize_conversation_state,
    deserialize_conversation_state,
    UnsupportedStateVersionError,
    InvalidStateError,
)


class RedisStateAccessor:
    async def load(self):
        blob = await redis.get(f"conv:{conversation_id}")
        if not blob:
            return None
        try:
            return deserialize_conversation_state(blob)
        except UnsupportedStateVersionError as err:
            # Decide whether to reset, migrate, or fail
            print(f"Unsupported state version: {err}")
            raise
        except InvalidStateError:
            # Malformed JSON or missing required fields
            raise

    async def save(self, s):
        await redis.set(f"conv:{conversation_id}", serialize_conversation_state(s))


state = RedisStateAccessor()

```

```go title="Go" lines theme={null}
state := StateAccessor{
	Load: func() (*ConversationState, error) {
		blob, ok := redis.Get("conv:" + id)
		if !ok {
			return nil, nil
		}
		s, err := deserializeConversationState(blob)
		if err != nil {
			var verr *UnsupportedStateVersionError
			if errors.As(err, &verr) {
				// verr.Found and verr.Supported let you decide: reset, migrate, or fail
				log.Printf("State version %d not in %v", verr.Found, verr.Supported)
			}
			var ierr *InvalidStateError
			if errors.As(err, &ierr) {
				// Malformed JSON or missing required fields
			}
			return nil, err
		}
		return s, nil
	},
	Save: func(s *ConversationState) error {
		blob, err := serializeConversationState(s)
		if err != nil {
			return err
		}
		redis.Set("conv:"+id, blob)
		return nil
	},
}
```

Compatibility policy:

* Treat the serialized JSON as **opaque**. Do not introspect item shapes across releases.
* Additive field changes are allowed within a major version.
* On version bumps, any migration work runs inside `deserializeConversationState`. Consumers using the helpers get forward-compat automatically.

Errors:

* `UnsupportedStateVersionError`: the blob's `version` isn't in this SDK build's supported set. Exposes `{ found, supported }` for logging or migration routing.
* `InvalidStateError`: the payload is malformed JSON or missing required fields (`id`, `messages`, `status`, `createdAt`, `updatedAt`).

## Complete Example

Here is an end-to-end example showing approval gates with state persistence:

```typescript expandable lines theme={null}
import { OpenRouter, tool } from '@openrouter/agent';
import type { ConversationState, StateAccessor } from '@openrouter/agent';
import { z } from 'zod';

// 1. Define a tool with approval required
const sendEmailTool = tool({
  name: 'send_email',
  description: 'Send an email',
  inputSchema: z.object({
    to: z.string().email(),
    subject: z.string(),
    body: z.string(),
  }),
  outputSchema: z.object({ sent: z.boolean(), messageId: z.string() }),
  requireApproval: true,
  execute: async (params) => {
    const result = await sendEmail(params);
    return { sent: true, messageId: result.id };
  },
});

// 2. Create a state accessor (in-memory for this example)
const store = new Map<string, ConversationState>();
const conversationId = 'conv-123';

const state: StateAccessor = {
  load: async () => store.get(conversationId) ?? null,
  save: async (s) => { store.set(conversationId, s); },
};

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

// 3. First callModel — model will try to call the tool
const result = openrouter.callModel({
  model: 'openai/gpt-4o',
  input: 'Send a welcome email to alice@example.com',
  tools: [sendEmailTool] as const,
  state,
});

// 4. Check if approval is needed
if (await result.requiresApproval()) {
  const pending = await result.getPendingToolCalls();

  for (const call of pending) {
    console.log(`Tool: ${call.name}`);
    console.log(`To: ${call.arguments.to}`);
    console.log(`Subject: ${call.arguments.subject}`);
    console.log(`ID: ${call.id}`);
  }

  // 5. Present to user for decision, then resume
  const approved = await askUserForApproval(pending);

  const approvedIds = approved.filter(a => a.decision === 'approve').map(a => a.id);
  const rejectedIds = approved.filter(a => a.decision === 'reject').map(a => a.id);

  // 6. Second callModel — resume with approval decisions
  const resumed = openrouter.callModel({
    model: 'openai/gpt-4o',
    input: [], // No new user input needed for resumption
    tools: [sendEmailTool] as const,
    state,
    approveToolCalls: approvedIds,
    rejectToolCalls: rejectedIds,
  });

  // 7. Get the final response
  const text = await resumed.getText();
  console.log(text);
  // "I've sent the welcome email to alice@example.com."
} else {
  // No approval needed — tool ran automatically
  const text = await result.getText();
  console.log(text);
}
```

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


# 1. Define a tool with approval required
class EmailInput(BaseModel):
    to: str
    subject: str
    body: str


class EmailOutput(BaseModel):
    sent: bool
    message_id: str


async def send_email(params: EmailInput, ctx) -> EmailOutput:
    # Replace with your real email provider
    return EmailOutput(sent=True, message_id="msg-001")


send_email_tool = tool(
    name="send_email",
    description="Send an email",
    input_schema=EmailInput,
    output_schema=EmailOutput,
    require_approval=True,
    execute=send_email,
)


# 2. Create a state accessor (in-memory for this example)
store = {}
conversation_id = "conv-123"


class InMemoryStateAccessor:
    async def load(self):
        return store.get(conversation_id)

    async def save(self, s):
        store[conversation_id] = s


state = InMemoryStateAccessor()


def ask_user_for_approval(pending):
    # Replace with a real UI prompt; this example approves everything
    return [{"id": call.id, "decision": "approve"} for call in pending]


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

    # 3. First call_model — model will try to call the tool
    result = call_model(
        client,
        {
            "model": "openai/gpt-4o",
            "input": "Send a welcome email to alice@example.com",
            "tools": [send_email_tool],
            "state": state,
        },
    )

    # 4. Check if approval is needed
    pending = await result.get_pending_tool_calls()
    if pending:
        for call in pending:
            print(f"Tool: {call.name}")
            print(f"To: {call.arguments['to']}")
            print(f"Subject: {call.arguments['subject']}")
            print(f"ID: {call.id}")

        # 5. Present to user for decision, then resume
        approved = ask_user_for_approval(pending)
        approved_ids = [a["id"] for a in approved if a["decision"] == "approve"]
        rejected_ids = [a["id"] for a in approved if a["decision"] == "reject"]

        # 6. Second call_model — resume with approval decisions
        resumed = call_model(
            client,
            {
                "model": "openai/gpt-4o",
                "input": [],  # No new user input needed for resumption
                "tools": [send_email_tool],
                "state": state,
                "approve_tool_calls": approved_ids,
                "reject_tool_calls": rejected_ids,
            },
        )

        # 7. Get the final response
        print(await resumed.get_text())
    else:
        # No approval needed — tool ran automatically
        print(await result.get_text())


asyncio.run(main())

```

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

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

type ToolCall struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

type Message struct {
	Role       string     `json:"role"`
	Content    any        `json:"content"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
}

type ConversationState struct {
	Messages []Message
	Pending  []ToolCall
	Status   string // "interrupted" when a run stopped early; see Resuming from Interruption
}

type StateAccessor struct {
	Load func() (*ConversationState, error)
	Save func(*ConversationState) error
}

// 1. Define a tool that requires approval
var tools = []map[string]any{{
	"type": "function",
	"function": map[string]any{
		"name":        "send_email",
		"description": "Send an email",
		"parameters": map[string]any{
			"type": "object",
			"properties": map[string]any{
				"to":      map[string]any{"type": "string"},
				"subject": map[string]any{"type": "string"},
				"body":    map[string]any{"type": "string"},
			},
			"required": []string{"to", "subject", "body"},
		},
	},
}}

func sendEmail(args map[string]any) string { return "msg-001" } // stub

func askUserForApproval(calls []ToolCall) map[string]bool {
	decisions := map[string]bool{}
	for _, c := range calls {
		decisions[c.ID] = true // approve everything in this example
	}
	return decisions
}

func chat(messages []Message) Message {
	body, _ := json.Marshal(map[string]any{"model": "openai/gpt-4o", "messages": messages, "tools": tools})
	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 {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	var out struct {
		Choices []struct{ Message Message } `json:"choices"`
	}
	if resp.StatusCode != 200 || json.Unmarshal(raw, &out) != nil || len(out.Choices) == 0 {
		log.Fatalf("request failed: %s", raw)
	}
	return out.Choices[0].Message
}

func main() {
	// 2. Create a state accessor (in-memory for this example)
	store := map[string]*ConversationState{}
	conversationID := "conv-123"
	state := StateAccessor{
		Load: func() (*ConversationState, error) { return store[conversationID], nil },
		Save: func(s *ConversationState) error { store[conversationID] = s; return nil },
	}

	// 3. First call — model will try to call the tool
	messages := []Message{{Role: "user", Content: "Send a welcome email to alice@example.com"}}
	reply := chat(messages)
	state.Save(&ConversationState{Messages: append(messages, reply), Pending: reply.ToolCalls})

	// 4. Check if approval is needed. A resumed request can return new tool
	// calls (for example a revised email after a rejection), so every round
	// goes through the same approval step
	for round := 0; len(reply.ToolCalls) > 0; round++ {
		if round == 5 {
			log.Fatal("stopped after 5 approval rounds without a final answer")
		}
		for _, call := range reply.ToolCalls {
			var args map[string]any
			json.Unmarshal([]byte(call.Function.Arguments), &args)
			// A real approval screen should show every argument, including the email body
			fmt.Printf("Tool: %s\nTo: %v\nSubject: %v\nID: %s\n", call.Function.Name, args["to"], args["subject"], call.ID)
		}

		// 5. Present to user for decision
		decisions := askUserForApproval(reply.ToolCalls)

		// 6. Resume from saved state with approval decisions
		s, _ := state.Load()
		for _, call := range s.Pending {
			result := `{"error":"rejected by user"}`
			if decisions[call.ID] {
				var args map[string]any
				// Approval covers the call the user saw; it does not make incomplete arguments valid
				if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err != nil || args["to"] == nil || args["subject"] == nil || args["body"] == nil {
					result = `{"error":"invalid arguments"}`
				} else {
					result = fmt.Sprintf(`{"sent":true,"messageId":%q}`, sendEmail(args))
				}
			}
			s.Messages = append(s.Messages, Message{Role: "tool", ToolCallID: call.ID, Content: result})
		}
		// Save the tool results before the next model request, so a failed request
		// cannot leave the calls pending and send the email again on retry
		s.Pending = nil
		state.Save(s)
		reply = chat(s.Messages)
		s.Messages = append(s.Messages, reply)
		s.Pending = reply.ToolCalls
		state.Save(s)
	}

	// 7. Print the final response once no tool calls are left
	fmt.Println(reply.Content)
}

```

```text title="Output" theme={null}
Tool: send_email
To: alice@example.com
Subject: Welcome to Our Community
ID: call_dwcvgpi9XA4dPCcuWmwI3D6y
The welcome email has been sent to alice@example.com.
```

## Resumption Patterns

### Resuming from Approval

When the state has `status: 'awaiting_approval'`, pass `approveToolCalls` and/or `rejectToolCalls` to resume:

```typescript lines theme={null}
// Load existing state
const loaded = await state.load();

if (loaded?.status === 'awaiting_approval') {
  const pending = loaded.pendingToolCalls ?? [];

  // Approve all pending calls
  const result = openrouter.callModel({
    model: 'openai/gpt-4o',
    input: [],
    tools: [sendEmailTool] as const,
    state,
    approveToolCalls: pending.map(c => c.id),
  });

  const text = await result.getText();
}
```

```python title="Python" lines theme={null}
async def resume_from_approval(client, state):
    # Load existing state
    loaded = await state.load()

    if loaded is not None and loaded.status == "awaiting_approval":
        pending = loaded.pending_tool_calls or []

        # Approve all pending calls
        result = call_model(
            client,
            {
                "model": "openai/gpt-4o",
                "input": [],
                "tools": [send_email_tool],
                "state": state,
                "approve_tool_calls": [c.id for c in pending],
            },
        )

        text = await result.get_text()
        return text

```

```go title="Go" lines theme={null}
// Load existing state
loaded, _ := state.Load()

if loaded != nil && len(loaded.Pending) > 0 { // awaiting approval
	// Approve all pending calls
	for _, call := range loaded.Pending {
		result := `{"error":"invalid arguments"}`
		var args map[string]any
		if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err == nil && args["to"] != nil && args["subject"] != nil && args["body"] != nil {
			result = fmt.Sprintf(`{"sent":true,"messageId":%q}`, sendEmail(args))
		}
		loaded.Messages = append(loaded.Messages, Message{Role: "tool", ToolCallID: call.ID, Content: result})
	}
	// Save the tool results before the next model request so a retry cannot resend
	loaded.Pending = nil
	state.Save(loaded)
	final := chat(loaded.Messages)
	loaded.Messages = append(loaded.Messages, final)
	// The model can answer with new tool calls; they wait for approval like the first ones
	loaded.Pending = final.ToolCalls
	state.Save(loaded)

	if len(final.ToolCalls) == 0 {
		text = final.Content
	}
}

```

### Resuming from Interruption

If a conversation was interrupted (`status: 'interrupted'`), calling `callModel` with the same state resumes automatically. The SDK clears the interruption flag and continues where it left off:

```typescript lines theme={null}
const loaded = await state.load();

if (loaded?.status === 'interrupted') {
  // Resume — the SDK picks up from the interruption point
  const result = openrouter.callModel({
    model: 'openai/gpt-4o',
    input: 'Continue where you left off',
    tools: myTools,
    state,
  });

  const text = await result.getText();
}
```

```python title="Python" lines theme={null}
async def resume_from_interruption(client, state):
    loaded = await state.load()

    if loaded is not None and loaded.status == "interrupted":
        # Resume — the SDK picks up from the interruption point
        result = call_model(
            client,
            {
                "model": "openai/gpt-4o",
                "input": "Continue where you left off",
                "tools": my_tools,
                "state": state,
            },
        )

        text = await result.get_text()
        return text

```

```go title="Go" lines theme={null}
// Fragment: uses the Status field of ConversationState from the complete example.
// Your loop records an interruption when a run stops early, for example on a
// cancelled request, where s is the state it was working on:
s.Status = "interrupted"
state.Save(s)

// Later, load the state and resume:
loaded, _ := state.Load()

if loaded != nil && loaded.Status == "interrupted" {
	// Resume — pick up from the interruption point
	loaded.Messages = append(loaded.Messages, Message{Role: "user", Content: "Continue where you left off"})
	final := chat(loaded.Messages)
	loaded.Messages = append(loaded.Messages, final)
	// The resumed reply can ask for tools; those calls wait for approval like any others
	loaded.Pending = final.ToolCalls
	if len(final.ToolCalls) == 0 {
		loaded.Status = "complete" // clear the interruption
		text = final.Content
	} else {
		loaded.Status = "awaiting_approval" // run the approval loop from the complete example
	}
	state.Save(loaded)
}
```

### Multi-Run Conversations

Messages accumulate automatically across `callModel` runs that share the same `StateAccessor`. Each run appends its input and response to the state's message history:

```typescript expandable lines theme={null}
const state: StateAccessor = createStateAccessor('conv-456');

// Turn 1
const r1 = openrouter.callModel({
  model: 'openai/gpt-4o',
  input: 'What is the weather in Tokyo?',
  tools: [weatherTool] as const,
  state,
});
console.log(await r1.getText());
// "The weather in Tokyo is 22°C and sunny."

// Turn 2 — state has full history from turn 1
const r2 = openrouter.callModel({
  model: 'openai/gpt-4o',
  input: 'And in Paris?',
  tools: [weatherTool] as const,
  state,
});
console.log(await r2.getText());
// "The weather in Paris is 15°C and cloudy."

// Turn 3 — state has history from both prior turns
const r3 = openrouter.callModel({
  model: 'openai/gpt-4o',
  input: 'Which city is warmer?',
  tools: [weatherTool] as const,
  state,
});
console.log(await r3.getText());
// "Tokyo is warmer at 22°C compared to Paris at 15°C."
```

```python title="Python" lines theme={null}
async def multi_run_conversation(client):
    state = create_state_accessor("conv-456")

    # Turn 1
    r1 = call_model(
        client,
        {
            "model": "openai/gpt-4o",
            "input": "What is the weather in Tokyo?",
            "tools": [weather_tool],
            "state": state,
        },
    )
    print(await r1.get_text())
    # "The weather in Tokyo is 22°C and sunny."

    # Turn 2 — state has full history from turn 1
    r2 = call_model(
        client,
        {
            "model": "openai/gpt-4o",
            "input": "And in Paris?",
            "tools": [weather_tool],
            "state": state,
        },
    )
    print(await r2.get_text())
    # "The weather in Paris is 15°C and cloudy."

    # Turn 3 — state has history from both prior turns
    r3 = call_model(
        client,
        {
            "model": "openai/gpt-4o",
            "input": "Which city is warmer?",
            "tools": [weather_tool],
            "state": state,
        },
    )
    print(await r3.get_text())
    # "Tokyo is warmer at 22°C compared to Paris at 15°C."

```

```go title="Go" lines theme={null}
// Fragment: uses chat, Message, and ConversationState from the complete example
// and createStateAccessor from the in-memory implementation. chat sends that
// example's tools; swap in your weather tool and run its calls the same way.

// runTurn loads the history, appends the input and the reply, and saves it.
func runTurn(state StateAccessor, input string) any {
	s, _ := state.Load()
	if s == nil {
		s = &ConversationState{}
	}
	s.Messages = append(s.Messages, Message{Role: "user", Content: input})
	reply := chat(s.Messages)
	s.Messages = append(s.Messages, reply)
	state.Save(s)
	return reply.Content
}

state := createStateAccessor("conv-456")

// Turn 1
fmt.Println(runTurn(state, "What is the weather in Tokyo?"))
// "The weather in Tokyo is 22°C and sunny."

// Turn 2 — state has full history from turn 1
fmt.Println(runTurn(state, "And in Paris?"))
// "The weather in Paris is 15°C and cloudy."

// Turn 3 — state has history from both prior turns
fmt.Println(runTurn(state, "Which city is warmer?"))
// "Tokyo is warmer at 22°C compared to Paris at 15°C."
```

## Next Steps

* **[Tools](https://openrouter.ai/docs/agent-sdk/call-model/tools.md)** - Tool definitions and the `tool()` helper
* **[Stop Conditions](https://openrouter.ai/docs/agent-sdk/call-model/stop-conditions.md)** - Control when tool execution loops terminate
* **[Dynamic Parameters](https://openrouter.ai/docs/agent-sdk/call-model/dynamic-parameters.md)** - Adjust parameters between turns
* **[Examples](https://openrouter.ai/docs/agent-sdk/call-model/examples/weather-tool.md)** - Complete tool implementations
* **[Gate Agent Tool Calls with Jev](https://openrouter.ai/docs/cookbook/building-agents/gate-tool-calls-with-jev.md)** - Decide `approve`, `block`, or `review` per call with a decision model instead of a static `requireApproval` flag
