Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
650 changes: 383 additions & 267 deletions .upstreamer/eval-report.md

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,14 @@ analysis = tool(
)
```

Manual tools are advertised to the model but not auto-executed.
Manual tools are advertised to the model but not auto-executed. A manual tool may pass `wire_input_schema=` to send its own JSON Schema to the model instead of one generated from `input_schema`.

```python
confirm = tool(name="confirm_action", input_schema=ConfirmInput, execute=False)
```

Any client tool accepts `strict=True` / `strict=False` to request provider-enforced schema adherence on tool-call arguments; it is sent on the wire tool definition (omitted means `null`, the provider default). Pass `active_tools=[...names]` to `call_model` to send and execute only a subset of `tools` (server tools are always kept).

HITL tools use `on_tool_called`; returning a value auto-resolves, returning `None` pauses with pending tool calls in state.

```python
Expand All @@ -144,6 +146,8 @@ web = server_tool({"type": "web_search_2025_08_26", "max_results": 5})

Use `require_approval` on a tool or `require_approval` on the request to pause sensitive calls before execution. Approval resume requires a state accessor with async `load()` and `save()` methods.

Resume with `approve_tool_calls` / `reject_tool_calls`. Duplicate IDs are ignored (each approved call runs once), and an ID in both lists raises before anything runs. A paused conversation stays paused until every pending call has a decision: resuming without decisions (or with decisions for only some calls) sends no model request, and `get_response()`, `get_text()`, `get_tool_calls()` and the stream getters raise an error naming the pause and the pending call IDs, while `requires_approval()`, `get_pending_tool_calls()` and `get_state()` keep working. An `awaiting_hitl` conversation also resumes when `input` carries a `function_call_output` for a pending call.

Manual tools (`execute=False`, no `on_tool_called`) pause the loop with status `"awaiting_client_tools"` when the model calls them, instead of silently dropping the call. Read the unresolved calls via `get_pending_tool_calls()` / `get_state()`, execute them yourself, and continue by calling `call_model` again with `function_call_output` items in `input`.

For durable cross-process storage, serialize state with `serialize_conversation_state` / `deserialize_conversation_state` rather than storing raw dataclass fields. The wire format is versioned (`CONVERSATION_STATE_VERSION`); a version mismatch raises `UnsupportedStateVersionError` and malformed JSON raises `InvalidStateError`, so a store can never silently misinterpret a future shape.
Expand All @@ -163,6 +167,10 @@ result = call_model(
)
```

## Usage

`get_response()` returns the *final* round's response, so its `usage` covers one generation. `await result.get_usage()` returns totals across every model call the run made (`model_calls`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_tokens`, `reasoning_tokens`, and `cost` when reported). It waits for the run and never raises: a failed or paused run returns what was accrued so far.

## Lifecycle Hooks

Pass a `HooksManager` (or an inline `{hook_name: [HookEntry(...)]}` dict of built-in hooks) via `hooks=` to observe or intervene in a run: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit`, `Stop`, `PermissionRequest`, `SessionStart`, `SessionEnd`, and `PostModelCall`. Handlers receive a validated payload dict and a `LifecycleHookContext` (`session_id`, `hook_name`, `cancel_event`).
Expand All @@ -189,6 +197,8 @@ The built-ins mirror the TypeScript package and OR together when provided as a l
- `max_cost(dollars)`
- `finish_reason_is(reason)`

A forced `tool_choice` (`"required"`, a specific tool, or `allowed_tools` with `mode: "required"`) is relaxed to `"auto"` once it has produced a tool call in a run (including across approval and client-tool resumes), so the model can answer in text instead of calling tools until the step budget runs out. A tool's `next_turn_params` may set `tool_choice` for the next turn (for example, to widen an `allowed_tools` set without touching `tools`); `next_turn_params` only runs for calls whose tool body ran and returned without error. A response truncated at `max_output_tokens` executes none of its tool calls; the run ends with that `incomplete` response.

When a stop condition fires while the model is still emitting tool calls, `call_model` makes one more turn with `tool_choice="none"` by default (tools stay in the request so the prompt-cache prefix survives) so the run ends with a natural-language answer. `allow_final_response` tunes this: `True` or omitted appends `DEFAULT_FINAL_RESPONSE_DIRECTIVE` as a user message, a non-empty string replaces the wording, `""` appends nothing, and `False` disables the extra turn entirely.

## Format Compatibility
Expand Down
33 changes: 33 additions & 0 deletions src/openrouter_agent/call_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,46 @@
from .hooks_resolve import resolve_hooks
from .model_result import ModelResult
from .tool_executor import convert_tools_to_api_format
from .tool_types import get_tool_function, is_server_tool


#: Upstream `callModel` options whose features this port does not implement
#: yet. Refused instead of being forwarded to the Responses API, where they
#: would be sent as unknown request fields or silently ignored.
UNSUPPORTED_CALL_MODEL_OPTIONS = (
"doom_loop",
"signal",
"tool_timeout_ms",
"tool_concurrency",
"async_tools",
"stream_replay",
)


def call_model(client: Any, request: Mapping[str, Any], options: Optional[Mapping[str, Any]] = None) -> ModelResult:
unsupported = [key for key in UNSUPPORTED_CALL_MODEL_OPTIONS if request.get(key) is not None]
if unsupported:
raise NotImplementedError(
f"call_model option(s) not supported by this Python port yet: {', '.join(unsupported)}"
)
tools = request.get("tools")
# Narrow tools to the active subset (if provided) before API conversion and
# before they are registered for execution, so the model cannot call
# filtered tools and the executor does not carry orphaned definitions.
# Server tools are always kept.
active_tools = request.get("active_tools")
if active_tools is not None and tools is not None:
active_set = set(active_tools)
tools = [t for t in tools if is_server_tool(t) or get_tool_function(t).get("name") in active_set]
# A filtered-to-empty (or explicitly empty) tools list omits the outbound
# `tools` key entirely instead of sending `tools: []`, which several
# providers reject; the engine treats it as its no-tools state.
if tools is not None and len(tools) == 0:
tools = None
final_request = dict(request)
for key in (
"tools",
"active_tools",
"stop_when",
"state",
"require_approval",
Expand Down
24 changes: 24 additions & 0 deletions src/openrouter_agent/chat_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,30 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str,
"output": _content_to_string(msg.get("content")),
}
)
elif role == "assistant":
content = _content_to_string(msg.get("content"))
tool_calls = msg.get("tool_calls") or msg.get("toolCalls") or []
# Skip the message item only when there is no content AND there are
# tool calls to emit in its place. A content-less assistant message
# with no tool calls still round-trips as an empty message.
if content or not tool_calls:
output.append({"type": "message", "role": role, "content": content})
# One function_call item per tool call. The chat format's
# `function.arguments` is already a JSON string, so it is
# forwarded as-is.
for call in tool_calls:
function = get_field(call, "function", {}) or {}
call_id = get_field(call, "id")
output.append(
{
"type": "function_call",
"callId": call_id,
"id": call_id,
"name": get_field(function, "name"),
"arguments": get_field(function, "arguments"),
"status": "completed",
}
)
else:
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
return output
Expand Down
1 change: 1 addition & 0 deletions src/openrouter_agent/conversation_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState:
partial_response=partial_response,
interrupted_by=parsed.get("interrupted_by"),
version=CONVERSATION_STATE_VERSION,
consumed_forced_tool_choice_key=parsed.get("consumed_forced_tool_choice_key"),
)


Expand Down
7 changes: 7 additions & 0 deletions src/openrouter_agent/hooks_emit.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,14 @@ async def execute_handler_chain(
behavior = HOOK_BEHAVIOR.get(hook_name)

for index, entry in enumerate(entries):
# Checked before each handler so synchronous chains stop promptly.
if context.cancel_event.is_set():
# A hook that can block (PreToolUse, UserPromptSubmit) fails
# closed: the handlers left unrun may include the guard that
# would have blocked, so an aborted chain must not read as an
# approval.
if behavior and behavior.block_field:
blocked = True
break

gate = _evaluate_entry_gate(entry, current_payload, index, options)
Expand Down
4 changes: 3 additions & 1 deletion src/openrouter_agent/hooks_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ class EmitResult:
pending: List["asyncio.Task[None]"] = field(default_factory=list)
#: The payload after all mutation piping has been applied.
final_payload: Dict[str, Any] = field(default_factory=dict)
#: True if any handler triggered a block/reject short-circuit.
#: True if any handler triggered a block/reject short-circuit, or if the
#: chain of a blocking hook (PreToolUse, UserPromptSubmit) was aborted
#: before every handler ran.
blocked: bool = False
#: True if any handler's result actually piped a mutation into the payload.
mutated: bool = False
Expand Down
Loading
Loading