diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.py index b3a77fa48..ca0b022d5 100644 --- a/nanobot/providers/openai_compat_provider.py +++ b/nanobot/providers/openai_compat_provider.py @@ -1466,145 +1466,95 @@ class OpenAICompatProvider(LLMProvider): return LLMResponse(content=response, finish_reason="stop") response_map = self._maybe_mapping(response) - if response_map is not None: - choices = cast( - list[object], - response_map.get("choices") or [], + if response_map is None: + raise TypeError(f"Unsupported chat response type: {type(response).__name__}") + choices = cast( + list[object], + response_map.get("choices") or [], + ) + if not choices: + content = self._extract_text_content( + response_map.get("content") or response_map.get("output_text") ) - if not choices: - content = self._extract_text_content( - response_map.get("content") or response_map.get("output_text") - ) - reasoning_content = self._extract_text_content( - response_map.get("reasoning_content") - ) - if content is not None: - return LLMResponse( - content=content, - reasoning_content=reasoning_content, - finish_reason=str(response_map.get("finish_reason") or "stop"), - usage=self._extract_usage(response_map), - ) + reasoning_content = self._extract_text_content( + response_map.get("reasoning_content") + ) + if content is not None: return LLMResponse( - content="Error: API returned empty choices.", - finish_reason="error", - error_kind="empty", + content=content, + reasoning_content=reasoning_content, + finish_reason=str(response_map.get("finish_reason") or "stop"), + usage=self._extract_usage(response_map), ) - - choice0 = self._maybe_mapping(choices[0]) or {} - msg0 = self._maybe_mapping(choice0.get("message")) or {} - content = self._extract_text_content(msg0.get("content")) - finish_reason = str(choice0.get("finish_reason") or "stop") - - raw_tool_calls: list[object] = [] - # StepFun: fallback to reasoning field when content is empty - if not content and msg0.get("reasoning") and self._spec and self._spec.reasoning_as_content: - content = self._extract_text_content(msg0.get("reasoning")) - reasoning_content = msg0.get("reasoning_content") - if reasoning_content is None and msg0.get("reasoning"): - reasoning_content = self._extract_text_content(msg0.get("reasoning")) - # Mistral reasoning models return thinking text inside the content - # array; lift it into reasoning_content so the runner records it - # under the reasoning trace. - spec = getattr(self, "_spec", None) - if reasoning_content is None and getattr(spec, "extract_thinking_blocks", False): - reasoning_content = self._extract_thinking_content(msg0.get("content")) - for ch in choices: - ch_map = self._maybe_mapping(ch) or {} - m = self._maybe_mapping(ch_map.get("message")) or {} - message_tool_calls = cast(object, m.get("tool_calls")) - if isinstance(message_tool_calls, list) and message_tool_calls: - raw_tool_calls.extend( - cast(list[object], message_tool_calls) - ) - if ch_map.get("finish_reason") in ("tool_calls", "stop"): - finish_reason = str(ch_map["finish_reason"]) - if not content: - content = self._extract_text_content(m.get("content")) - if reasoning_content is None: - reasoning_content = m.get("reasoning_content") - - # Deduplicate tool call IDs (same pattern as streaming path) - # Some providers reuse the same ID for parallel tool calls. - _seen_tc_ids: set[str] = set() - parsed_tool_calls: list[ToolCallRequest] = [] - for tc in raw_tool_calls: - tc_map = self._maybe_mapping(tc) or {} - fn = self._maybe_mapping(tc_map.get("function")) or {} - args = parse_tool_arguments(fn.get("arguments", {})) - ec, prov, fn_prov = _extract_tc_extras(tc) - raw_id = str(tc_map.get("id") or _short_tool_id()) - if not raw_id or raw_id in _seen_tc_ids: - raw_id = _short_tool_id() - _seen_tc_ids.add(raw_id) - parsed_tool_calls.append(ToolCallRequest( - id=raw_id, - name=str(fn.get("name") or ""), - arguments=args, - extra_content=ec, - provider_specific_fields=prov, - function_provider_specific_fields=fn_prov, - )) - if not parsed_tool_calls: - content, parsed_tool_calls = _extract_text_tool_calls(content) - - return LLMResponse( - content=content, - tool_calls=parsed_tool_calls, - finish_reason=finish_reason, - usage=self._extract_usage(response_map), - reasoning_content=reasoning_content if isinstance(reasoning_content, str) else None, - ) - - if not response.choices: return LLMResponse( content="Error: API returned empty choices.", finish_reason="error", error_kind="empty", ) - choice = response.choices[0] - msg = choice.message - content = msg.content - finish_reason = choice.finish_reason + choice0 = self._maybe_mapping(choices[0]) or {} + msg0 = self._maybe_mapping(choice0.get("message")) or {} + content = self._extract_text_content(msg0.get("content")) + finish_reason = str(choice0.get("finish_reason") or "stop") - raw_sdk_tool_calls: list[Any] = [] - for ch in response.choices: - m = ch.message - if hasattr(m, "tool_calls") and m.tool_calls: - raw_sdk_tool_calls.extend(m.tool_calls) - if ch.finish_reason in ("tool_calls", "stop"): - finish_reason = ch.finish_reason - if not content and m.content: - content = m.content - if not content and getattr(m, "reasoning", None) and self._spec and self._spec.reasoning_as_content: - content = m.reasoning + raw_tool_calls: list[object] = [] + # StepFun: fallback to reasoning field when content is empty + if not content and msg0.get("reasoning") and self._spec and self._spec.reasoning_as_content: + content = self._extract_text_content(msg0.get("reasoning")) + reasoning_content = msg0.get("reasoning_content") + if reasoning_content is None and msg0.get("reasoning"): + reasoning_content = self._extract_text_content(msg0.get("reasoning")) + # Mistral reasoning models return thinking text inside the content + # array; lift it into reasoning_content so the runner records it + # under the reasoning trace. + spec = getattr(self, "_spec", None) + if reasoning_content is None and getattr(spec, "extract_thinking_blocks", False): + reasoning_content = self._extract_thinking_content(msg0.get("content")) + for ch in choices: + ch_map = self._maybe_mapping(ch) or {} + m = self._maybe_mapping(ch_map.get("message")) or {} + message_tool_calls = cast(object, m.get("tool_calls")) + if isinstance(message_tool_calls, list) and message_tool_calls: + raw_tool_calls.extend( + cast(list[object], message_tool_calls) + ) + if ch_map.get("finish_reason") in ("tool_calls", "stop"): + finish_reason = str(ch_map["finish_reason"]) + if not content: + content = self._extract_text_content(m.get("content")) + if reasoning_content is None: + reasoning_content = m.get("reasoning_content") - tool_calls: list[ToolCallRequest] = [] - for tc in raw_sdk_tool_calls: - args = parse_tool_arguments(tc.function.arguments) + # Deduplicate tool call IDs (same pattern as streaming path) + # Some providers reuse the same ID for parallel tool calls. + _seen_tc_ids: set[str] = set() + parsed_tool_calls: list[ToolCallRequest] = [] + for tc in raw_tool_calls: + tc_map = self._maybe_mapping(tc) or {} + fn = self._maybe_mapping(tc_map.get("function")) or {} + args = parse_tool_arguments(fn.get("arguments", {})) ec, prov, fn_prov = _extract_tc_extras(tc) - tool_calls.append(ToolCallRequest( - id=str(getattr(tc, "id", None) or _short_tool_id()), - name=tc.function.name, + raw_id = str(tc_map.get("id") or _short_tool_id()) + if not raw_id or raw_id in _seen_tc_ids: + raw_id = _short_tool_id() + _seen_tc_ids.add(raw_id) + parsed_tool_calls.append(ToolCallRequest( + id=raw_id, + name=str(fn.get("name") or ""), arguments=args, extra_content=ec, provider_specific_fields=prov, function_provider_specific_fields=fn_prov, )) - if not tool_calls: - content, tool_calls = _extract_text_tool_calls(content) - - reasoning_content = getattr(msg, "reasoning_content", None) - if reasoning_content is None and getattr(msg, "reasoning", None): - reasoning_content = msg.reasoning + if not parsed_tool_calls: + content, parsed_tool_calls = _extract_text_tool_calls(content) return LLMResponse( content=content, - tool_calls=tool_calls, - finish_reason=finish_reason or "stop", - usage=self._extract_usage(response), - reasoning_content=reasoning_content, + tool_calls=parsed_tool_calls, + finish_reason=finish_reason, + usage=self._extract_usage(response_map), + reasoning_content=reasoning_content if isinstance(reasoning_content, str) else None, ) @classmethod @@ -1662,78 +1612,46 @@ class OpenAICompatProvider(LLMProvider): continue chunk_map = cls._maybe_mapping(chunk) - if chunk_map is not None: - choices = cast( - list[object], - chunk_map.get("choices") or [], - ) - if not choices: - usage = cls._extract_usage(chunk_map) or usage - text = cls._extract_text_content( - chunk_map.get("content") or chunk_map.get("output_text") - ) - if text: - content_parts.append(text) - continue - choice = cls._maybe_mapping(choices[0]) or {} - if choice.get("finish_reason"): - finish_reason = str(choice["finish_reason"]) - delta = cls._maybe_mapping(choice.get("delta")) or {} - raw_delta_content = delta.get("content") - text = cls._extract_text_content(raw_delta_content) - if text: - content_parts.append(text) - text = cls._extract_text_content(delta.get("reasoning_content")) - if not text: - text = cls._extract_text_content(delta.get("reasoning")) - if not text: - # Mistral streams thinking inside the content array as - # {"type":"thinking", thinking:[{"type":"text", ...}]}. - text = cls._extract_thinking_content(raw_delta_content) - if text: - reasoning_parts.append(text) - for idx, tc in enumerate( - cast( - Iterable[object], - delta.get("tool_calls") or [], - ) - ): - _accum_tc(tc, idx) - _accum_legacy_function_call(delta.get("function_call")) - usage = cls._extract_usage(chunk_map) or usage - continue - - if not chunk.choices: - usage = cls._extract_usage(chunk) or usage - continue - choice = chunk.choices[0] - if choice.finish_reason: - finish_reason = choice.finish_reason - delta = choice.delta - if delta and delta.content: - text = cls._extract_text_content(delta.content) - if text: - content_parts.append(text) - thinking_text = cls._extract_thinking_content(delta.content) - if thinking_text: - reasoning_parts.append(thinking_text) - if delta: - reasoning = getattr(delta, "reasoning_content", None) - if not reasoning: - reasoning = getattr(delta, "reasoning", None) - if reasoning: - text = cls._extract_text_content(reasoning) - if text: - reasoning_parts.append(text) - delta_tool_calls = ( - cast(Iterable[object], getattr(delta, "tool_calls", None) or []) - if delta - else () + if chunk_map is None: + raise TypeError(f"Unsupported chat chunk type: {type(chunk).__name__}") + choices = cast( + list[object], + chunk_map.get("choices") or [], ) - for tc in delta_tool_calls: - _accum_tc(tc, getattr(tc, "index", 0)) - if delta: - _accum_legacy_function_call(getattr(delta, "function_call", None)) + if not choices: + usage = cls._extract_usage(chunk_map) or usage + text = cls._extract_text_content( + chunk_map.get("content") or chunk_map.get("output_text") + ) + if text: + content_parts.append(text) + continue + choice = cls._maybe_mapping(choices[0]) or {} + if choice.get("finish_reason"): + finish_reason = str(choice["finish_reason"]) + delta = cls._maybe_mapping(choice.get("delta")) or {} + raw_delta_content = delta.get("content") + text = cls._extract_text_content(raw_delta_content) + if text: + content_parts.append(text) + text = cls._extract_text_content(delta.get("reasoning_content")) + if not text: + text = cls._extract_text_content(delta.get("reasoning")) + if not text: + # Mistral streams thinking inside the content array as + # {"type":"thinking", thinking:[{"type":"text", ...}]}. + text = cls._extract_thinking_content(raw_delta_content) + if text: + reasoning_parts.append(text) + for idx, tc in enumerate( + cast( + Iterable[object], + delta.get("tool_calls") or [], + ) + ): + _accum_tc(tc, idx) + _accum_legacy_function_call(delta.get("function_call")) + usage = cls._extract_usage(chunk_map) or usage # Some providers (e.g. Zhipu/GLM) reuse the same tool_call id for # parallel tool calls in streaming mode. Deduplicate before building diff --git a/tests/agent/test_gemini_thought_signature.py b/tests/agent/test_gemini_thought_signature.py index b4d08580d..7bf370d1b 100644 --- a/tests/agent/test_gemini_thought_signature.py +++ b/tests/agent/test_gemini_thought_signature.py @@ -5,9 +5,11 @@ field: ``{"google": {"thought_signature": "..."}}``. This MUST survive the parse → serialize round-trip so the model can continue reasoning. """ -from types import SimpleNamespace from unittest.mock import patch +import pytest +from openai.types.chat import ChatCompletion, ChatCompletionChunk + from nanobot.providers.base import ToolCallRequest from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.registry import ProviderSpec @@ -55,26 +57,33 @@ def test_tool_call_request_omits_absent_extras() -> None: assert "provider_specific_fields" not in payload["function"] -# ── _parse: SDK-object branch ────────────────────────────────────────── +# ── _parse: SDK objects ──────────────────────────────────────────────── -def _make_sdk_response_with_extra_content(): - """Simulate a Gemini response via the OpenAI SDK (SimpleNamespace).""" - fn = SimpleNamespace(name="get_weather", arguments='{"city":"Tokyo"}') - tc = SimpleNamespace( - id="call_1", - index=0, - type="function", - function=fn, - extra_content=GEMINI_EXTRA, - ) - msg = SimpleNamespace( - content=None, - tool_calls=[tc], - reasoning_content=None, - ) - choice = SimpleNamespace(message=msg, finish_reason="tool_calls") - usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) - return SimpleNamespace(choices=[choice], usage=usage) +def _make_sdk_response_with_extra_content() -> ChatCompletion: + return ChatCompletion.model_validate({ + "id": "chatcmpl-gemini", + "object": "chat.completion", + "created": 0, + "model": "gemini-3.1-pro-preview", + "choices": [{ + "index": 0, + "finish_reason": "tool_calls", + "message": { + "role": "assistant", + "content": None, + "tool_calls": [{ + "id": "call_1", + "type": "function", + "function": { + "name": "get_weather", "arguments": '{"city":"Tokyo"}', "inner": "value", + }, + "extra_content": GEMINI_EXTRA, + "provider_tag": "opaque", + }], + }, + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + }) def test_parse_sdk_object_preserves_extra_content() -> None: @@ -87,9 +96,13 @@ def test_parse_sdk_object_preserves_extra_content() -> None: tc = result.tool_calls[0] assert tc.name == "get_weather" assert tc.extra_content == GEMINI_EXTRA + assert tc.provider_specific_fields == {"provider_tag": "opaque"} + assert tc.function_provider_specific_fields == {"inner": "value"} payload = tc.to_openai_tool_call() assert payload["extra_content"] == GEMINI_EXTRA + assert payload["provider_specific_fields"] == {"provider_tag": "opaque"} + assert payload["function"]["provider_specific_fields"] == {"inner": "value"} # ── _parse: dict/mapping branch ─────────────────────────────────────── @@ -125,14 +138,21 @@ def test_parse_dict_preserves_extra_content() -> None: assert payload["extra_content"] == GEMINI_EXTRA -def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None: +@pytest.mark.parametrize("as_sdk", [False, True], ids=["dict", "sdk"]) +def test_parse_deduplicates_duplicate_tool_call_ids(as_sdk: bool) -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider() response_dict = { + "id": "chatcmpl-parallel", + "object": "chat.completion", + "created": 0, + "model": "test-model", "choices": [ { + "index": 0, "message": { + "role": "assistant", "content": None, "tool_calls": [{ "id": "call_same", @@ -143,7 +163,9 @@ def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None: "finish_reason": "tool_calls", }, { + "index": 1, "message": { + "role": "assistant", "content": None, "tool_calls": [{ "id": "call_same", @@ -156,7 +178,8 @@ def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None: ], } - result = provider._parse(response_dict) + response = ChatCompletion.model_validate(response_dict) if as_sdk else response_dict + result = provider._parse(response) ids = [tc.id for tc in result.tool_calls] assert len(ids) == 2 @@ -169,25 +192,39 @@ def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None: # ── _parse_chunks: streaming round-trip ─────────────────────────────── def test_parse_chunks_sdk_preserves_extra_content() -> None: - fn_delta = SimpleNamespace(name="get_weather", arguments='{"city":"Tokyo"}') - tc_delta = SimpleNamespace( - id="call_1", - index=0, - function=fn_delta, - extra_content=GEMINI_EXTRA, - ) - delta = SimpleNamespace(content=None, tool_calls=[tc_delta]) - choice = SimpleNamespace(finish_reason="tool_calls", delta=delta) - chunk = SimpleNamespace(choices=[choice], usage=None) + chunk = ChatCompletionChunk.model_validate({ + "id": "chatcmpl-gemini", + "object": "chat.completion.chunk", + "created": 0, + "model": "gemini-3.1-pro-preview", + "choices": [{ + "index": 0, + "finish_reason": "tool_calls", + "delta": {"tool_calls": [{ + "index": 0, + "id": "call_1", + "type": "function", + "function": { + "name": "get_weather", "arguments": '{"city":"Tokyo"}', "inner": "value", + }, + "extra_content": GEMINI_EXTRA, + "provider_tag": "opaque", + }]}, + }], + }) result = OpenAICompatProvider._parse_chunks([chunk]) assert len(result.tool_calls) == 1 tc = result.tool_calls[0] assert tc.extra_content == GEMINI_EXTRA + assert tc.provider_specific_fields == {"provider_tag": "opaque"} + assert tc.function_provider_specific_fields == {"inner": "value"} payload = tc.to_openai_tool_call() assert payload["extra_content"] == GEMINI_EXTRA + assert payload["provider_specific_fields"] == {"provider_tag": "opaque"} + assert payload["function"]["provider_specific_fields"] == {"inner": "value"} def test_parse_chunks_dict_preserves_extra_content() -> None: diff --git a/tests/providers/test_cached_tokens.py b/tests/providers/test_cached_tokens.py index acd63420a..37b88e7bd 100644 --- a/tests/providers/test_cached_tokens.py +++ b/tests/providers/test_cached_tokens.py @@ -2,50 +2,40 @@ from __future__ import annotations +import pytest +from openai.types.chat import ChatCompletion, ChatCompletionChunk + from nanobot.providers.openai_compat_provider import OpenAICompatProvider class FakeUsage: - """Mimics an OpenAI SDK usage object (has attributes, not dict keys).""" + """Attribute-based fixture for the Anthropic response tests.""" def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) -class FakePromptDetails: - """Mimics prompt_tokens_details sub-object.""" - def __init__(self, cached_tokens=0, cache_write_tokens=None): - self.cached_tokens = cached_tokens - self.cache_write_tokens = cache_write_tokens - - -class _FakeSpec: - supports_prompt_caching = False - model_id_prefix = None - strip_model_prefix = False - max_completion_tokens = False - reasoning_effort = None - - -def _provider(): - from unittest.mock import MagicMock - p = OpenAICompatProvider.__new__(OpenAICompatProvider) - p.client = MagicMock() - p.spec = _FakeSpec() - return p +def _provider() -> OpenAICompatProvider: + return OpenAICompatProvider(api_key="test-key") # Minimal valid choice so _parse reaches _extract_usage. _DICT_CHOICE = {"message": {"content": "Hello"}} -class _FakeMessage: - content = "Hello" - tool_calls = None - -class _FakeChoice: - message = _FakeMessage() - finish_reason = "stop" +def _sdk_response(usage) -> ChatCompletion: + return ChatCompletion.model_validate({ + "id": "chatcmpl-usage", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "finish_reason": "stop", + "message": {"role": "assistant", "content": "Hello"}, + }], + "usage": usage, + }) # --- dict-based response (raw JSON / mapping) --- @@ -152,32 +142,32 @@ def test_extract_usage_missing_is_none(): # --- object-based response (OpenAI SDK Pydantic model) --- -def test_extract_usage_openai_cached_tokens_obj(): - """prompt_tokens_details.cached_tokens from an SDK object response.""" +@pytest.mark.parametrize("cache_read, cache_write", [(1200, None), (0, 0)]) +def test_extract_usage_openai_cached_tokens_obj(cache_read, cache_write): + """SDK prompt token details preserve cache counts, including explicit zero.""" p = _provider() - usage_obj = FakeUsage( - prompt_tokens=2000, - completion_tokens=300, - total_tokens=2300, - prompt_tokens_details=FakePromptDetails(cached_tokens=1200), - ) - response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj) + response = _sdk_response({ + "prompt_tokens": 2000, + "completion_tokens": 300, + "total_tokens": 2300, + "prompt_tokens_details": { + "cached_tokens": cache_read, + "cache_write_tokens": cache_write, + }, + }) result = p._parse(response) assert result.usage is not None - assert result.usage.cache_read_tokens == 1200 + assert result.usage.cache_read_tokens == cache_read + assert result.usage.cache_write_tokens == cache_write def test_extract_usage_preserves_reported_total_and_cache_write_obj(): - usage_obj = FakeUsage( - prompt_tokens=15, - completion_tokens=18, - total_tokens=175, - prompt_tokens_details=FakePromptDetails( - cached_tokens=0, - cache_write_tokens=7, - ), - ) - response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj) + response = _sdk_response({ + "prompt_tokens": 15, + "completion_tokens": 18, + "total_tokens": 175, + "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 7}, + }) result = _provider()._parse(response) @@ -191,13 +181,12 @@ def test_extract_usage_preserves_reported_total_and_cache_write_obj(): def test_extract_usage_deepseek_cached_tokens_obj(): """prompt_cache_hit_tokens from a DeepSeek SDK object response.""" p = _provider() - usage_obj = FakeUsage( - prompt_tokens=1500, - completion_tokens=200, - total_tokens=1700, - prompt_cache_hit_tokens=1200, - ) - response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj) + response = _sdk_response({ + "prompt_tokens": 1500, + "completion_tokens": 200, + "total_tokens": 1700, + "prompt_cache_hit_tokens": 1200, + }) result = p._parse(response) assert result.usage is not None assert result.usage.cache_read_tokens == 1200 @@ -223,13 +212,12 @@ def test_extract_usage_stepfun_top_level_cached_tokens_dict(): def test_extract_usage_stepfun_top_level_cached_tokens_obj(): """StepFun/Moonshot: usage.cached_tokens as SDK object attribute.""" p = _provider() - usage_obj = FakeUsage( - prompt_tokens=591, - completion_tokens=120, - total_tokens=711, - cached_tokens=512, - ) - response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj) + response = _sdk_response({ + "prompt_tokens": 591, + "completion_tokens": 120, + "total_tokens": 711, + "cached_tokens": 512, + }) result = p._parse(response) assert result.usage is not None assert result.usage.cache_read_tokens == 512 @@ -253,6 +241,42 @@ def test_extract_usage_priority_nested_over_top_level_dict(): assert result.usage.cache_read_tokens == 100 +@pytest.mark.parametrize("as_sdk", [False, True], ids=["dict", "sdk"]) +def test_parse_chunks_preserves_usage_only_chunk(as_sdk: bool) -> None: + chunks = [ + {"choices": [{"index": 0, "delta": {"content": "Hello"}, "finish_reason": "stop"}]}, + { + "choices": [], + "usage": { + "prompt_tokens": 15, + "completion_tokens": 18, + "total_tokens": 175, + "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, + }, + }, + ] + if as_sdk: + chunks = [ChatCompletionChunk.model_validate({ + "id": "chatcmpl-usage", + "object": "chat.completion.chunk", + "created": 0, + "model": "test-model", + **chunk, + }) for chunk in chunks] + + result = OpenAICompatProvider._parse_chunks(chunks) + + assert result.content == "Hello" + assert result.finish_reason == "stop" + assert result.usage is not None + assert result.usage.input_tokens == 15 + assert result.usage.output_tokens == 18 + assert result.usage.total_tokens == 175 + assert result.usage.reported_tokens == 175 + assert result.usage.cache_read_tokens == 0 + assert result.usage.cache_write_tokens == 0 + + def test_anthropic_adds_native_cache_fields_to_logical_input(): """Anthropic excludes cache reads/writes from its native input_tokens.""" from nanobot.providers.anthropic_provider import AnthropicProvider diff --git a/tests/providers/test_custom_provider.py b/tests/providers/test_custom_provider.py index 551492257..3ce5b8219 100644 --- a/tests/providers/test_custom_provider.py +++ b/tests/providers/test_custom_provider.py @@ -1,8 +1,10 @@ """Tests for OpenAICompatProvider handling custom/direct endpoints.""" -from types import SimpleNamespace from unittest.mock import patch +import pytest +from openai.types.chat import ChatCompletion, ChatCompletionChunk + from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.registry import find_by_name @@ -10,7 +12,9 @@ from nanobot.providers.registry import find_by_name def test_custom_provider_parse_handles_empty_choices() -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider() - response = SimpleNamespace(choices=[]) + response = ChatCompletion( + id="chatcmpl-empty", choices=[], created=0, model="test-model", object="chat.completion", + ) result = provider._parse(response) @@ -118,20 +122,28 @@ def test_custom_provider_parse_chunks_normalizes_split_text_tool_call() -> None: assert result.tool_calls[0].arguments == {"path": "."} -def test_custom_provider_parse_chunks_deduplicates_parallel_tool_call_ids() -> None: +@pytest.mark.parametrize("as_sdk", [False, True], ids=["dict", "sdk"]) +def test_custom_provider_parse_chunks_deduplicates_parallel_tool_call_ids(as_sdk: bool) -> None: chunks = [{ + "id": "chatcmpl-parallel", + "object": "chat.completion.chunk", + "created": 0, + "model": "test-model", "choices": [{ + "index": 0, "finish_reason": "tool_calls", "delta": { "tool_calls": [ { "index": 0, "id": "call_dup", + "type": "function", "function": {"name": "read_file", "arguments": '{"path":"a.txt"}'}, }, { "index": 1, "id": "call_dup", + "type": "function", "function": {"name": "read_file", "arguments": '{"path":"b.txt"}'}, }, ], @@ -139,12 +151,15 @@ def test_custom_provider_parse_chunks_deduplicates_parallel_tool_call_ids() -> N }], }] + if as_sdk: + chunks = [ChatCompletionChunk.model_validate(chunk) for chunk in chunks] result = OpenAICompatProvider._parse_chunks(chunks) ids = [tool_call.id for tool_call in result.tool_calls or []] assert ids[0] == "call_dup" assert len(ids) == 2 assert len(set(ids)) == 2 + assert [tc.arguments for tc in result.tool_calls] == [{"path": "a.txt"}, {"path": "b.txt"}] def test_local_provider_502_error_includes_reachability_hint() -> None: diff --git a/tests/providers/test_mistral_provider.py b/tests/providers/test_mistral_provider.py index bd6a7cf01..42ae48648 100644 --- a/tests/providers/test_mistral_provider.py +++ b/tests/providers/test_mistral_provider.py @@ -5,6 +5,8 @@ from __future__ import annotations from unittest.mock import patch import pytest +from openai.types.chat import ChatCompletionChunk +from openai.types.chat.chat_completion_chunk import Choice, ChoiceDelta from nanobot.config.schema import ProvidersConfig from nanobot.providers.openai_compat_provider import OpenAICompatProvider @@ -263,32 +265,29 @@ def test_streaming_thinking_chunks_become_reasoning() -> None: def test_streaming_thinking_chunks_via_sdk_path() -> None: - """The SDK-style branch must coerce list-shaped delta.content to text. + """SDK chunks with list-shaped delta.content keep text and thinking separate. - Regression: Mistral's vibe-cli/medium-3-5 streamed delta.content as a - list, which was previously appended verbatim to content_parts and blew - up later with "can only concatenate str (not list) to str". + Mistral's vibe-cli/medium-3-5 streams content as a list. The SDK accepts + it through non-strict construction even though its schema declares str. """ - class _Delta: - def __init__(self, content): - self.content = content - self.tool_calls = None - self.function_call = None - - class _Choice: - def __init__(self, content, finish=None): - self.delta = _Delta(content) - self.finish_reason = finish - - class _Chunk: - def __init__(self, content, finish=None): - self.choices = [_Choice(content, finish)] + def chunk(content, finish=None) -> ChatCompletionChunk: + return ChatCompletionChunk( + id="chatcmpl-mistral", + object="chat.completion.chunk", + created=0, + model="mistral-medium-3-5", + choices=[Choice( + index=0, + delta=ChoiceDelta.model_construct(content=content), + finish_reason=finish, + )], + ) chunks = [ - _Chunk([{"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]}]), - _Chunk([{"type": "text", "text": "Hello "}]), - _Chunk("world.", finish="stop"), + chunk([{"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]}]), + chunk([{"type": "text", "text": "Hello "}]), + chunk("world.", finish="stop"), ] parsed = OpenAICompatProvider._parse_chunks(chunks) assert parsed.content == "Hello world." diff --git a/tests/providers/test_openai_compat_spec.py b/tests/providers/test_openai_compat_spec.py index 94f90dad0..95061f9db 100644 --- a/tests/providers/test_openai_compat_spec.py +++ b/tests/providers/test_openai_compat_spec.py @@ -13,55 +13,79 @@ from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch import pytest +from openai.types.chat import ChatCompletion, ChatCompletionChunk from nanobot.providers.base import ProviderCallContext from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.registry import ModelAPICapabilities, find_by_name -def _fake_chat_response(content: str = "ok") -> SimpleNamespace: +def _fake_chat_response(content: str = "ok") -> ChatCompletion: """Build a minimal OpenAI chat completion response.""" - message = SimpleNamespace( - content=content, - tool_calls=None, - reasoning_content=None, - ) - choice = SimpleNamespace(message=message, finish_reason="stop") - usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) - return SimpleNamespace(choices=[choice], usage=usage) + return ChatCompletion.model_validate({ + "id": "chatcmpl-test", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "finish_reason": "stop", + "message": {"role": "assistant", "content": content}, + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + }) -def _fake_tool_call_response() -> SimpleNamespace: +def _fake_tool_call_response() -> ChatCompletion: """Build a minimal chat response that includes Gemini-style extra_content.""" - function = SimpleNamespace( - name="exec", - arguments='{"cmd":"ls"}', - provider_specific_fields={"inner": "value"}, - ) - tool_call = SimpleNamespace( - id="call_123", - index=0, - type="function", - function=function, - extra_content={"google": {"thought_signature": "signed-token"}}, - ) - message = SimpleNamespace( - content=None, - tool_calls=[tool_call], - reasoning_content=None, - ) - choice = SimpleNamespace(message=message, finish_reason="tool_calls") - usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) - return SimpleNamespace(choices=[choice], usage=usage) + return ChatCompletion.model_validate({ + "id": "chatcmpl-tools", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "finish_reason": "tool_calls", + "message": { + "role": "assistant", + "content": None, + "tool_calls": [{ + "id": "call_123", + "type": "function", + "function": { + "name": "exec", + "arguments": '{"cmd":"ls"}', + "inner": "value", + }, + "extra_content": {"google": {"thought_signature": "signed-token"}}, + }], + }, + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + }) -def _fake_tool_call_response_with_arguments(arguments) -> SimpleNamespace: +def _fake_tool_call_response_with_arguments(arguments: str) -> ChatCompletion: """Build a minimal chat response with caller-supplied tool arguments.""" - function = SimpleNamespace(name="optional_tool", arguments=arguments) - tool_call = SimpleNamespace(id="call_123", type="function", function=function) - message = SimpleNamespace(content=None, tool_calls=[tool_call], reasoning_content=None) - choice = SimpleNamespace(message=message, finish_reason="tool_calls") - return SimpleNamespace(choices=[choice], usage=SimpleNamespace()) + return ChatCompletion.model_validate({ + "id": "chatcmpl-arguments", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "finish_reason": "tool_calls", + "message": { + "role": "assistant", + "content": None, + "tool_calls": [{ + "id": "call_123", + "type": "function", + "function": {"name": "optional_tool", "arguments": arguments}, + }], + }, + }], + }) def _fake_responses_response(content: str = "ok") -> MagicMock: @@ -94,16 +118,23 @@ def _fake_responses_stream(text: str = "ok"): return _stream() +def _chat_chunk(delta, finish=None, usage=None) -> ChatCompletionChunk: + return ChatCompletionChunk.model_validate({ + "id": "chatcmpl-stream", + "object": "chat.completion.chunk", + "created": 0, + "model": "test-model", + "choices": [{"index": 0, "finish_reason": finish, "delta": delta}], + "usage": usage, + }) + + def _fake_chat_stream(text: str = "ok"): async def _stream(): - yield SimpleNamespace( - choices=[SimpleNamespace(finish_reason=None, delta=SimpleNamespace(content=text, reasoning_content=None, tool_calls=None))], - usage=None, - ) - yield SimpleNamespace( - choices=[SimpleNamespace(finish_reason="stop", delta=SimpleNamespace(content=None, reasoning_content=None, tool_calls=None))], - usage=SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15), - ) + yield _chat_chunk({"content": text}) + yield _chat_chunk({}, finish="stop", usage={ + "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, + }) return _stream() @@ -112,64 +143,12 @@ def _fake_chat_stream_reasoning_chunks(): """Mimic DeepSeek-style ``chat.completions`` stream: ``reasoning_content`` then ``content``.""" async def _stream(): - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content="step1", - reasoning=None, - tool_calls=None, - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content="step2", - reasoning=None, - tool_calls=None, - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content="answer", - reasoning_content=None, - tool_calls=None, - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason="stop", - delta=SimpleNamespace( - content=None, - reasoning_content=None, - tool_calls=None, - ), - ), - ], - usage=SimpleNamespace( - prompt_tokens=10, - completion_tokens=5, - total_tokens=15, - ), - ) + yield _chat_chunk({"reasoning_content": "step1"}) + yield _chat_chunk({"reasoning_content": "step2"}) + yield _chat_chunk({"content": "answer"}) + yield _chat_chunk({}, finish="stop", usage={ + "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, + }) return _stream() @@ -178,63 +157,19 @@ def _fake_chat_stream_tool_call_chunks(): """Mimic OpenAI-compatible streaming tool-call argument deltas.""" async def _stream(): - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=[ - SimpleNamespace( - index=0, - id="call_write", - function=SimpleNamespace( - name="write_file", - arguments='{"path":"notes.md","content":"', - ), - ) - ], - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=[ - SimpleNamespace( - index=0, - id=None, - function=SimpleNamespace(name=None, arguments='line\\n"}'), - ) - ], - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason="tool_calls", - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=None, - ), - ), - ], - usage=SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15), - ) + yield _chat_chunk({"tool_calls": [{ + "index": 0, + "id": "call_write", + "type": "function", + "function": {"name": "write_file", "arguments": '{"path":"notes.md","content":"'}, + }]}) + yield _chat_chunk({"tool_calls": [{ + "index": 0, + "function": {"arguments": 'line\\n"}'}, + }]}) + yield _chat_chunk({}, finish="tool_calls", usage={ + "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, + }) return _stream() @@ -243,57 +178,13 @@ def _fake_chat_stream_legacy_function_call_chunks(): """Mimic older OpenAI-compatible ``delta.function_call`` chunks.""" async def _stream(): - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=None, - function_call=SimpleNamespace( - name="write_file", - arguments='{"path":"notes.md","content":"', - ), - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason=None, - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=None, - function_call=SimpleNamespace( - name=None, - arguments='line\\n"}', - ), - ), - ), - ], - usage=None, - ) - yield SimpleNamespace( - choices=[ - SimpleNamespace( - finish_reason="function_call", - delta=SimpleNamespace( - content=None, - reasoning_content=None, - reasoning=None, - tool_calls=None, - function_call=None, - ), - ), - ], - usage=SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15), - ) + yield _chat_chunk({"function_call": { + "name": "write_file", "arguments": '{"path":"notes.md","content":"', + }}) + yield _chat_chunk({"function_call": {"arguments": 'line\\n"}'}}) + yield _chat_chunk({}, finish="function_call", usage={ + "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, + }) return _stream() diff --git a/tests/providers/test_reasoning_content.py b/tests/providers/test_reasoning_content.py index f61d385c8..e8bf0fdf4 100644 --- a/tests/providers/test_reasoning_content.py +++ b/tests/providers/test_reasoning_content.py @@ -4,9 +4,10 @@ Covers non-streaming (_parse) and streaming (_parse_chunks) paths for providers that return a reasoning_content field (e.g. MiMo, DeepSeek-R1). """ -from types import SimpleNamespace from unittest.mock import patch +from openai.types.chat import ChatCompletion, ChatCompletionChunk + from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.utils.helpers import build_assistant_message @@ -83,9 +84,17 @@ def test_parse_sdk_reasoning_content_empty_string_preserved() -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider() - message = SimpleNamespace(content="answer", reasoning_content="", tool_calls=None) - choice = SimpleNamespace(message=message, finish_reason="stop") - response = SimpleNamespace(choices=[choice], usage=None) + response = ChatCompletion.model_validate({ + "id": "chatcmpl-reasoning", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "answer", "reasoning_content": ""}, + "finish_reason": "stop", + }], + }) result = provider._parse(response) @@ -172,13 +181,23 @@ def test_parse_chunks_dict_reasoning_content_none_when_absent() -> None: assert result.reasoning_content is None -# ── _parse_chunks: streaming SDK-object branch ──────────────────────────── +# ── _parse_chunks: streaming SDK objects ────────────────────────────────── -def _make_reasoning_chunk(reasoning: str | None, content: str | None, finish: str | None): - delta = SimpleNamespace(content=content, reasoning_content=reasoning, tool_calls=None) - choice = SimpleNamespace(finish_reason=finish, delta=delta) - return SimpleNamespace(choices=[choice], usage=None) +def _make_reasoning_chunk( + reasoning: str | None, content: str | None, finish: str | None, +) -> ChatCompletionChunk: + return ChatCompletionChunk.model_validate({ + "id": "chatcmpl-reasoning", + "object": "chat.completion.chunk", + "created": 0, + "model": "test-model", + "choices": [{ + "index": 0, + "finish_reason": finish, + "delta": {"content": content, "reasoning_content": reasoning}, + }], + }) def test_parse_chunks_sdk_accumulates_reasoning_content() -> None: diff --git a/tests/providers/test_stepfun_reasoning.py b/tests/providers/test_stepfun_reasoning.py index a16edfc21..586ec0415 100644 --- a/tests/providers/test_stepfun_reasoning.py +++ b/tests/providers/test_stepfun_reasoning.py @@ -5,9 +5,10 @@ the model is in thinking mode and 'content' is empty. This test module verifies the fallback logic for all code paths. """ -from types import SimpleNamespace from unittest.mock import patch +from openai.types.chat import ChatCompletion, ChatCompletionChunk + from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.registry import ProviderSpec @@ -71,17 +72,26 @@ def test_parse_dict_stepfun_reasoning_priority() -> None: assert result.reasoning_content == "formal reasoning content" -# ── _parse: SDK object branch ─────────────────────────────────────────────── +# ── _parse: SDK objects ──────────────────────────────────────────────────── -def _make_sdk_message(content, reasoning=None, reasoning_content=None): - """Create a mock SDK message object.""" - msg = SimpleNamespace(content=content, tool_calls=None) - if reasoning is not None: - msg.reasoning = reasoning - if reasoning_content is not None: - msg.reasoning_content = reasoning_content - return msg +def _make_sdk_response(content, reasoning=None, reasoning_content=None) -> ChatCompletion: + return ChatCompletion.model_validate({ + "id": "chatcmpl-stepfun", + "object": "chat.completion", + "created": 0, + "model": "step-3.5-flash", + "choices": [{ + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": content, + "reasoning": reasoning, + "reasoning_content": reasoning_content, + }, + }], + }) def test_parse_sdk_stepfun_reasoning_fallback() -> None: @@ -89,9 +99,7 @@ def test_parse_sdk_stepfun_reasoning_fallback() -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider(spec=_STEPFUN_SPEC) - msg = _make_sdk_message(content=None, reasoning="After analysis: result is 4.") - choice = SimpleNamespace(finish_reason="stop", message=msg) - response = SimpleNamespace(choices=[choice], usage=None) + response = _make_sdk_response(content=None, reasoning="After analysis: result is 4.") result = provider._parse(response) @@ -104,13 +112,11 @@ def test_parse_sdk_stepfun_reasoning_priority() -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider(spec=_STEPFUN_SPEC) - msg = _make_sdk_message( + response = _make_sdk_response( content=None, reasoning="thinking process", - reasoning_content="formal reasoning" + reasoning_content="formal reasoning", ) - choice = SimpleNamespace(finish_reason="stop", message=msg) - response = SimpleNamespace(choices=[choice], usage=None) result = provider._parse(response) @@ -218,19 +224,27 @@ def test_parse_chunks_dict_reasoning_precedence() -> None: assert result.reasoning_content == "formal: " -# ── _parse_chunks: streaming SDK-object branch ───────────────────────────── +# ── _parse_chunks: streaming SDK objects ─────────────────────────────────── -def _make_sdk_chunk(reasoning_content=None, reasoning=None, content=None, finish=None): - """Create a mock SDK chunk object.""" - delta = SimpleNamespace( - content=content, - reasoning_content=reasoning_content, - reasoning=reasoning, - tool_calls=None, - ) - choice = SimpleNamespace(finish_reason=finish, delta=delta) - return SimpleNamespace(choices=[choice], usage=None) +def _make_sdk_chunk( + reasoning_content=None, reasoning=None, content=None, finish=None, +) -> ChatCompletionChunk: + return ChatCompletionChunk.model_validate({ + "id": "chatcmpl-stepfun", + "object": "chat.completion.chunk", + "created": 0, + "model": "step-3.5-flash", + "choices": [{ + "index": 0, + "finish_reason": finish, + "delta": { + "content": content, + "reasoning_content": reasoning_content, + "reasoning": reasoning, + }, + }], + }) def test_parse_chunks_sdk_stepfun_reasoning_fallback() -> None: @@ -289,9 +303,7 @@ def test_parse_sdk_non_stepfun_no_reasoning_as_content() -> None: with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): provider = OpenAICompatProvider() - msg = _make_sdk_message(content=None, reasoning="internal monologue") - choice = SimpleNamespace(finish_reason="stop", message=msg) - response = SimpleNamespace(choices=[choice], usage=None) + response = _make_sdk_response(content=None, reasoning="internal monologue") result = provider._parse(response) diff --git a/tests/providers/test_stream_idle_timeout_config.py b/tests/providers/test_stream_idle_timeout_config.py index 9b38a4699..6aaca7a3f 100644 --- a/tests/providers/test_stream_idle_timeout_config.py +++ b/tests/providers/test_stream_idle_timeout_config.py @@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock import httpx import pytest +from openai.types.chat import ChatCompletionChunk import nanobot.providers.openai_codex_provider as codex_provider from nanobot.providers.anthropic_provider import AnthropicProvider @@ -74,19 +75,13 @@ async def test_openai_compat_stream_ignores_invalid_idle_timeout_env(monkeypatch monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "abc") provider = OpenAICompatProvider(api_key="sk-test", api_base="https://example.com/v1") - chunk = SimpleNamespace( - choices=[SimpleNamespace( - delta=SimpleNamespace( - content="ok", - reasoning_content=None, - reasoning=None, - tool_calls=None, - function_call=None, - ), - finish_reason="stop", - )], - usage=None, - ) + chunk = ChatCompletionChunk.model_validate({ + "id": "chatcmpl-timeout", + "object": "chat.completion.chunk", + "created": 0, + "model": "test-model", + "choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}], + }) provider._client = SimpleNamespace( chat=SimpleNamespace(completions=SimpleNamespace( create=AsyncMock(return_value=_AsyncStream([chunk])),