Skip to content

Commit ee01804

Browse files
port: sync with @openrouter/agent upstream
1 parent ee94d6b commit ee01804

20 files changed

Lines changed: 1989 additions & 450 deletions

‎.upstreamer/eval-report.md‎

Lines changed: 189 additions & 262 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,12 @@ async for event in result.get_tool_stream():
8888

8989
async for call in result.get_tool_calls_stream():
9090
print(call.name, call.arguments)
91+
92+
usage = await result.get_usage() # totals across every model call in the run
9193
```
9294

95+
`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.
96+
9397
## Tool Variants
9498

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

122+
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.
123+
118124
Manual tools are advertised to the model but not auto-executed.
119125

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

192198
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.
193199

200+
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).
201+
202+
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.
203+
194204
## Format Compatibility
195205

196-
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.
206+
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.
197207

198208
## Development
199209

‎src/openrouter_agent/chat_compat.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
from typing import Any, Dict, List, Mapping, Sequence
55

6-
from ._utils import get_field
6+
from ._utils import dump, get_field
77
from .stream_transformers import extract_responses_message_from_response
88

99

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

1717

18-
def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str, Any]]:
18+
def _chat_tool_calls(msg: Mapping[str, Any]) -> List[Any]:
19+
tool_calls = msg.get("tool_calls")
20+
if tool_calls is None:
21+
tool_calls = msg.get("toolCalls")
22+
return list(tool_calls or [])
23+
24+
25+
def from_chat_messages(messages: Sequence[Any]) -> List[Dict[str, Any]]:
1926
output: List[Dict[str, Any]] = []
20-
for msg in messages:
27+
for raw in messages:
28+
msg = raw if isinstance(raw, Mapping) else dump(raw)
2129
role = msg.get("role")
2230
if role == "tool":
2331
output.append(
@@ -27,8 +35,32 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str,
2735
"output": _content_to_string(msg.get("content")),
2836
}
2937
)
30-
else:
31-
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
38+
continue
39+
if role == "assistant":
40+
content = _content_to_string(msg.get("content"))
41+
tool_calls = _chat_tool_calls(msg)
42+
# Skip the message item only when there is no content AND tool
43+
# calls take its place; a content-less assistant message with no
44+
# tool calls still round-trips as an empty message.
45+
if content or not tool_calls:
46+
output.append({"type": "message", "role": role, "content": content})
47+
# One function_call item per tool call. Chat-format `arguments` is
48+
# already a JSON string, so it is forwarded as-is.
49+
for call in tool_calls:
50+
function = get_field(call, "function") or {}
51+
call_id = get_field(call, "id")
52+
output.append(
53+
{
54+
"type": "function_call",
55+
"callId": call_id,
56+
"id": call_id,
57+
"name": get_field(function, "name"),
58+
"arguments": get_field(function, "arguments"),
59+
"status": "completed",
60+
}
61+
)
62+
continue
63+
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
3264
return output
3365

3466

‎src/openrouter_agent/conversation_state.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,8 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState:
168168
if parsed.get("unsent_tool_results") is not None:
169169
unsent_tool_results = [UnsentToolResult(**item) for item in parsed["unsent_tool_results"]]
170170

171+
consumed_key = parsed.get("consumed_forced_tool_choice_key")
172+
171173
partial_response = None
172174
if parsed.get("partial_response") is not None:
173175
partial_response = PartialResponse(**parsed["partial_response"])
@@ -184,6 +186,7 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState:
184186
partial_response=partial_response,
185187
interrupted_by=parsed.get("interrupted_by"),
186188
version=CONVERSATION_STATE_VERSION,
189+
consumed_forced_tool_choice_key=consumed_key if isinstance(consumed_key, str) else None,
187190
)
188191

189192

0 commit comments

Comments
 (0)