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
451 changes: 189 additions & 262 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 @@ -88,8 +88,12 @@ async for event in result.get_tool_stream():

async for call in result.get_tool_calls_stream():
print(call.name, call.arguments)

usage = await result.get_usage() # totals across every model call in the run
```

`get_response()` returns only the **final** round's response, so in a multi-round tool loop its `usage` covers one generation. `get_usage()` returns the aggregate across every model call the run made (`model_calls`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_tokens`, `reasoning_tokens`, and `cost` when reported) — the same numbers as the `SessionEnd` hook's `total_usage`, with no hooks required. It never raises for a failed run, so it is safe in a `finally` block.

## Tool Variants

Regular tools execute automatically when the model emits a matching `function_call`.
Expand All @@ -115,6 +119,8 @@ analysis = tool(
)
```

Pass `strict=True` (or `False`) to forward provider strict-schema adherence onto the wire tool definition; omit it to keep the provider default. OpenAI-style strict mode requires every declared property to be listed as required.

Manual tools are advertised to the model but not auto-executed.

```python
Expand Down Expand Up @@ -191,9 +197,13 @@ The built-ins mirror the TypeScript package and OR together when provided as a l

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.

A forced `tool_choice` (`"required"`, a specific tool, or `allowed_tools` with `mode: "required"`) applies until a response made under it calls a tool; follow-up turns then send the relaxed form (`"auto"`, or the same `allowed_tools` set with `mode: "auto"`) so the model can answer in text. A tool can set the next turn's choice via `next_turn_params={"tool_choice": fn}` (for example to widen an `allowed_tools` set without changing `tools`, which keeps the prompt-cache prefix intact).

Tool calls are only executed from responses whose status is `completed`; a response cut off at `max_output_tokens` (status `incomplete`) ends the run with none of its calls executed.

## Format Compatibility

Use `from_claude_messages` / `to_claude_message` for Anthropic-style messages and `from_chat_messages` / `to_chat_message` for OpenAI Chat-style messages. Content that cannot be represented directly is carried as `unsupported_content` instead of being silently discarded.
Use `from_claude_messages` / `to_claude_message` for Anthropic-style messages and `from_chat_messages` / `to_chat_message` for OpenAI Chat-style messages (assistant `tool_calls` become `function_call` items, so replayed tool-calling history keeps each output paired with its call). Content that cannot be represented directly is carried as `unsupported_content` instead of being silently discarded.

## Development

Expand Down
42 changes: 37 additions & 5 deletions src/openrouter_agent/chat_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
from typing import Any, Dict, List, Mapping, Sequence

from ._utils import get_field
from ._utils import dump, get_field
from .stream_transformers import extract_responses_message_from_response


Expand All @@ -15,9 +15,17 @@ def _content_to_string(content: Any) -> str:
return json.dumps(content, separators=(",", ":"))


def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str, Any]]:
def _chat_tool_calls(msg: Mapping[str, Any]) -> List[Any]:
tool_calls = msg.get("tool_calls")
if tool_calls is None:
tool_calls = msg.get("toolCalls")
return list(tool_calls or [])


def from_chat_messages(messages: Sequence[Any]) -> List[Dict[str, Any]]:
output: List[Dict[str, Any]] = []
for msg in messages:
for raw in messages:
msg = raw if isinstance(raw, Mapping) else dump(raw)
role = msg.get("role")
if role == "tool":
output.append(
Expand All @@ -27,8 +35,32 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str,
"output": _content_to_string(msg.get("content")),
}
)
else:
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
continue
if role == "assistant":
content = _content_to_string(msg.get("content"))
tool_calls = _chat_tool_calls(msg)
# Skip the message item only when there is no content AND tool
# calls take 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. Chat-format `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",
}
)
continue
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
return output


Expand Down
3 changes: 3 additions & 0 deletions src/openrouter_agent/conversation_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState:
if parsed.get("unsent_tool_results") is not None:
unsent_tool_results = [UnsentToolResult(**item) for item in parsed["unsent_tool_results"]]

consumed_key = parsed.get("consumed_forced_tool_choice_key")

partial_response = None
if parsed.get("partial_response") is not None:
partial_response = PartialResponse(**parsed["partial_response"])
Expand All @@ -184,6 +186,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=consumed_key if isinstance(consumed_key, str) else None,
)


Expand Down
Loading
Loading