refactor(providers): remove duplicate chat response parsers

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-16 15:05:56 +08:00
1 parent 0d09b3dc09
commit e4fc8788c4
9 files changed
+482 -572

No files matched your search

+108 -190
View File
@@ -1466,145 +1466,95 @@ class OpenAICompatProvider(LLMProvider):
return LLMResponse(content=response, finish_reason="stop") return LLMResponse(content=response, finish_reason="stop")
response_map = self._maybe_mapping(response) response_map = self._maybe_mapping(response)
if response_map is not None: if response_map is None:
choices = cast( raise TypeError(f"Unsupported chat response type: {type(response).__name__}")
list[object], choices = cast(
response_map.get("choices") or [], 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: reasoning_content = self._extract_text_content(
content = self._extract_text_content( response_map.get("reasoning_content")
response_map.get("content") or response_map.get("output_text") )
) if content is not None:
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),
)
return LLMResponse( return LLMResponse(
content="Error: API returned empty choices.", content=content,
finish_reason="error", reasoning_content=reasoning_content,
error_kind="empty", 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( return LLMResponse(
content="Error: API returned empty choices.", content="Error: API returned empty choices.",
finish_reason="error", finish_reason="error",
error_kind="empty", error_kind="empty",
) )
choice = response.choices[0] choice0 = self._maybe_mapping(choices[0]) or {}
msg = choice.message msg0 = self._maybe_mapping(choice0.get("message")) or {}
content = msg.content content = self._extract_text_content(msg0.get("content"))
finish_reason = choice.finish_reason finish_reason = str(choice0.get("finish_reason") or "stop")
raw_sdk_tool_calls: list[Any] = [] raw_tool_calls: list[object] = []
for ch in response.choices: # StepFun: fallback to reasoning field when content is empty
m = ch.message if not content and msg0.get("reasoning") and self._spec and self._spec.reasoning_as_content:
if hasattr(m, "tool_calls") and m.tool_calls: content = self._extract_text_content(msg0.get("reasoning"))
raw_sdk_tool_calls.extend(m.tool_calls) reasoning_content = msg0.get("reasoning_content")
if ch.finish_reason in ("tool_calls", "stop"): if reasoning_content is None and msg0.get("reasoning"):
finish_reason = ch.finish_reason reasoning_content = self._extract_text_content(msg0.get("reasoning"))
if not content and m.content: # Mistral reasoning models return thinking text inside the content
content = m.content # array; lift it into reasoning_content so the runner records it
if not content and getattr(m, "reasoning", None) and self._spec and self._spec.reasoning_as_content: # under the reasoning trace.
content = m.reasoning 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] = [] # Deduplicate tool call IDs (same pattern as streaming path)
for tc in raw_sdk_tool_calls: # Some providers reuse the same ID for parallel tool calls.
args = parse_tool_arguments(tc.function.arguments) _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) ec, prov, fn_prov = _extract_tc_extras(tc)
tool_calls.append(ToolCallRequest( raw_id = str(tc_map.get("id") or _short_tool_id())
id=str(getattr(tc, "id", None) or _short_tool_id()), if not raw_id or raw_id in _seen_tc_ids:
name=tc.function.name, 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, arguments=args,
extra_content=ec, extra_content=ec,
provider_specific_fields=prov, provider_specific_fields=prov,
function_provider_specific_fields=fn_prov, function_provider_specific_fields=fn_prov,
)) ))
if not tool_calls: if not parsed_tool_calls:
content, tool_calls = _extract_text_tool_calls(content) content, parsed_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
return LLMResponse( return LLMResponse(
content=content, content=content,
tool_calls=tool_calls, tool_calls=parsed_tool_calls,
finish_reason=finish_reason or "stop", finish_reason=finish_reason,
usage=self._extract_usage(response), usage=self._extract_usage(response_map),
reasoning_content=reasoning_content, reasoning_content=reasoning_content if isinstance(reasoning_content, str) else None,
) )
@classmethod @classmethod
@@ -1662,78 +1612,46 @@ class OpenAICompatProvider(LLMProvider):
continue continue
chunk_map = cls._maybe_mapping(chunk) chunk_map = cls._maybe_mapping(chunk)
if chunk_map is not None: if chunk_map is None:
choices = cast( raise TypeError(f"Unsupported chat chunk type: {type(chunk).__name__}")
list[object], choices = cast(
chunk_map.get("choices") or [], 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 ()
) )
for tc in delta_tool_calls: if not choices:
_accum_tc(tc, getattr(tc, "index", 0)) usage = cls._extract_usage(chunk_map) or usage
if delta: text = cls._extract_text_content(
_accum_legacy_function_call(getattr(delta, "function_call", None)) 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 # Some providers (e.g. Zhipu/GLM) reuse the same tool_call id for
# parallel tool calls in streaming mode. Deduplicate before building # parallel tool calls in streaming mode. Deduplicate before building
+69 -32
View File
@@ -5,9 +5,11 @@ field: ``{"google": {"thought_signature": "..."}}``. This MUST survive the
parse → serialize round-trip so the model can continue reasoning. parse → serialize round-trip so the model can continue reasoning.
""" """
from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
import pytest
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.base import ToolCallRequest from nanobot.providers.base import ToolCallRequest
from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.providers.registry import ProviderSpec 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"] assert "provider_specific_fields" not in payload["function"]
# ── _parse: SDK-object branch ────────────────────────────────────────── # ── _parse: SDK objects ────────────────────────────────────────────────
def _make_sdk_response_with_extra_content(): def _make_sdk_response_with_extra_content() -> ChatCompletion:
"""Simulate a Gemini response via the OpenAI SDK (SimpleNamespace).""" return ChatCompletion.model_validate({
fn = SimpleNamespace(name="get_weather", arguments='{"city":"Tokyo"}') "id": "chatcmpl-gemini",
tc = SimpleNamespace( "object": "chat.completion",
id="call_1", "created": 0,
index=0, "model": "gemini-3.1-pro-preview",
type="function", "choices": [{
function=fn, "index": 0,
extra_content=GEMINI_EXTRA, "finish_reason": "tool_calls",
) "message": {
msg = SimpleNamespace( "role": "assistant",
content=None, "content": None,
tool_calls=[tc], "tool_calls": [{
reasoning_content=None, "id": "call_1",
) "type": "function",
choice = SimpleNamespace(message=msg, finish_reason="tool_calls") "function": {
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) "name": "get_weather", "arguments": '{"city":"Tokyo"}', "inner": "value",
return SimpleNamespace(choices=[choice], usage=usage) },
"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: 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] tc = result.tool_calls[0]
assert tc.name == "get_weather" assert tc.name == "get_weather"
assert tc.extra_content == GEMINI_EXTRA 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() payload = tc.to_openai_tool_call()
assert payload["extra_content"] == GEMINI_EXTRA 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 ─────────────────────────────────────── # ── _parse: dict/mapping branch ───────────────────────────────────────
@@ -125,14 +138,21 @@ def test_parse_dict_preserves_extra_content() -> None:
assert payload["extra_content"] == GEMINI_EXTRA 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"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider() provider = OpenAICompatProvider()
response_dict = { response_dict = {
"id": "chatcmpl-parallel",
"object": "chat.completion",
"created": 0,
"model": "test-model",
"choices": [ "choices": [
{ {
"index": 0,
"message": { "message": {
"role": "assistant",
"content": None, "content": None,
"tool_calls": [{ "tool_calls": [{
"id": "call_same", "id": "call_same",
@@ -143,7 +163,9 @@ def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None:
"finish_reason": "tool_calls", "finish_reason": "tool_calls",
}, },
{ {
"index": 1,
"message": { "message": {
"role": "assistant",
"content": None, "content": None,
"tool_calls": [{ "tool_calls": [{
"id": "call_same", "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] ids = [tc.id for tc in result.tool_calls]
assert len(ids) == 2 assert len(ids) == 2
@@ -169,25 +192,39 @@ def test_parse_dict_deduplicates_duplicate_tool_call_ids() -> None:
# ── _parse_chunks: streaming round-trip ─────────────────────────────── # ── _parse_chunks: streaming round-trip ───────────────────────────────
def test_parse_chunks_sdk_preserves_extra_content() -> None: def test_parse_chunks_sdk_preserves_extra_content() -> None:
fn_delta = SimpleNamespace(name="get_weather", arguments='{"city":"Tokyo"}') chunk = ChatCompletionChunk.model_validate({
tc_delta = SimpleNamespace( "id": "chatcmpl-gemini",
id="call_1", "object": "chat.completion.chunk",
index=0, "created": 0,
function=fn_delta, "model": "gemini-3.1-pro-preview",
extra_content=GEMINI_EXTRA, "choices": [{
) "index": 0,
delta = SimpleNamespace(content=None, tool_calls=[tc_delta]) "finish_reason": "tool_calls",
choice = SimpleNamespace(finish_reason="tool_calls", delta=delta) "delta": {"tool_calls": [{
chunk = SimpleNamespace(choices=[choice], usage=None) "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]) result = OpenAICompatProvider._parse_chunks([chunk])
assert len(result.tool_calls) == 1 assert len(result.tool_calls) == 1
tc = result.tool_calls[0] tc = result.tool_calls[0]
assert tc.extra_content == GEMINI_EXTRA 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() payload = tc.to_openai_tool_call()
assert payload["extra_content"] == GEMINI_EXTRA 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: def test_parse_chunks_dict_preserves_extra_content() -> None:
+87 -63
View File
@@ -2,50 +2,40 @@
from __future__ import annotations from __future__ import annotations
import pytest
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.openai_compat_provider import OpenAICompatProvider
class FakeUsage: 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): def __init__(self, **kwargs):
for k, v in kwargs.items(): for k, v in kwargs.items():
setattr(self, k, v) setattr(self, k, v)
class FakePromptDetails: def _provider() -> OpenAICompatProvider:
"""Mimics prompt_tokens_details sub-object.""" return OpenAICompatProvider(api_key="test-key")
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
# Minimal valid choice so _parse reaches _extract_usage. # Minimal valid choice so _parse reaches _extract_usage.
_DICT_CHOICE = {"message": {"content": "Hello"}} _DICT_CHOICE = {"message": {"content": "Hello"}}
class _FakeMessage:
content = "Hello"
tool_calls = None
def _sdk_response(usage) -> ChatCompletion:
class _FakeChoice: return ChatCompletion.model_validate({
message = _FakeMessage() "id": "chatcmpl-usage",
finish_reason = "stop" "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) --- # --- dict-based response (raw JSON / mapping) ---
@@ -152,32 +142,32 @@ def test_extract_usage_missing_is_none():
# --- object-based response (OpenAI SDK Pydantic model) --- # --- object-based response (OpenAI SDK Pydantic model) ---
def test_extract_usage_openai_cached_tokens_obj(): @pytest.mark.parametrize("cache_read, cache_write", [(1200, None), (0, 0)])
"""prompt_tokens_details.cached_tokens from an SDK object response.""" def test_extract_usage_openai_cached_tokens_obj(cache_read, cache_write):
"""SDK prompt token details preserve cache counts, including explicit zero."""
p = _provider() p = _provider()
usage_obj = FakeUsage( response = _sdk_response({
prompt_tokens=2000, "prompt_tokens": 2000,
completion_tokens=300, "completion_tokens": 300,
total_tokens=2300, "total_tokens": 2300,
prompt_tokens_details=FakePromptDetails(cached_tokens=1200), "prompt_tokens_details": {
) "cached_tokens": cache_read,
response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj) "cache_write_tokens": cache_write,
},
})
result = p._parse(response) result = p._parse(response)
assert result.usage is not None 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(): def test_extract_usage_preserves_reported_total_and_cache_write_obj():
usage_obj = FakeUsage( response = _sdk_response({
prompt_tokens=15, "prompt_tokens": 15,
completion_tokens=18, "completion_tokens": 18,
total_tokens=175, "total_tokens": 175,
prompt_tokens_details=FakePromptDetails( "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 7},
cached_tokens=0, })
cache_write_tokens=7,
),
)
response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj)
result = _provider()._parse(response) 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(): def test_extract_usage_deepseek_cached_tokens_obj():
"""prompt_cache_hit_tokens from a DeepSeek SDK object response.""" """prompt_cache_hit_tokens from a DeepSeek SDK object response."""
p = _provider() p = _provider()
usage_obj = FakeUsage( response = _sdk_response({
prompt_tokens=1500, "prompt_tokens": 1500,
completion_tokens=200, "completion_tokens": 200,
total_tokens=1700, "total_tokens": 1700,
prompt_cache_hit_tokens=1200, "prompt_cache_hit_tokens": 1200,
) })
response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj)
result = p._parse(response) result = p._parse(response)
assert result.usage is not None assert result.usage is not None
assert result.usage.cache_read_tokens == 1200 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(): def test_extract_usage_stepfun_top_level_cached_tokens_obj():
"""StepFun/Moonshot: usage.cached_tokens as SDK object attribute.""" """StepFun/Moonshot: usage.cached_tokens as SDK object attribute."""
p = _provider() p = _provider()
usage_obj = FakeUsage( response = _sdk_response({
prompt_tokens=591, "prompt_tokens": 591,
completion_tokens=120, "completion_tokens": 120,
total_tokens=711, "total_tokens": 711,
cached_tokens=512, "cached_tokens": 512,
) })
response = FakeUsage(choices=[_FakeChoice()], usage=usage_obj)
result = p._parse(response) result = p._parse(response)
assert result.usage is not None assert result.usage is not None
assert result.usage.cache_read_tokens == 512 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 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(): def test_anthropic_adds_native_cache_fields_to_logical_input():
"""Anthropic excludes cache reads/writes from its native input_tokens.""" """Anthropic excludes cache reads/writes from its native input_tokens."""
from nanobot.providers.anthropic_provider import AnthropicProvider from nanobot.providers.anthropic_provider import AnthropicProvider
+18 -3
View File
@@ -1,8 +1,10 @@
"""Tests for OpenAICompatProvider handling custom/direct endpoints.""" """Tests for OpenAICompatProvider handling custom/direct endpoints."""
from types import SimpleNamespace
from unittest.mock import patch 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.openai_compat_provider import OpenAICompatProvider
from nanobot.providers.registry import find_by_name 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: def test_custom_provider_parse_handles_empty_choices() -> None:
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider() provider = OpenAICompatProvider()
response = SimpleNamespace(choices=[]) response = ChatCompletion(
id="chatcmpl-empty", choices=[], created=0, model="test-model", object="chat.completion",
)
result = provider._parse(response) 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": "."} 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 = [{ chunks = [{
"id": "chatcmpl-parallel",
"object": "chat.completion.chunk",
"created": 0,
"model": "test-model",
"choices": [{ "choices": [{
"index": 0,
"finish_reason": "tool_calls", "finish_reason": "tool_calls",
"delta": { "delta": {
"tool_calls": [ "tool_calls": [
{ {
"index": 0, "index": 0,
"id": "call_dup", "id": "call_dup",
"type": "function",
"function": {"name": "read_file", "arguments": '{"path":"a.txt"}'}, "function": {"name": "read_file", "arguments": '{"path":"a.txt"}'},
}, },
{ {
"index": 1, "index": 1,
"id": "call_dup", "id": "call_dup",
"type": "function",
"function": {"name": "read_file", "arguments": '{"path":"b.txt"}'}, "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) result = OpenAICompatProvider._parse_chunks(chunks)
ids = [tool_call.id for tool_call in result.tool_calls or []] ids = [tool_call.id for tool_call in result.tool_calls or []]
assert ids[0] == "call_dup" assert ids[0] == "call_dup"
assert len(ids) == 2 assert len(ids) == 2
assert len(set(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: def test_local_provider_502_error_includes_reachability_hint() -> None:
+20 -21
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
from unittest.mock import patch from unittest.mock import patch
import pytest 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.config.schema import ProvidersConfig
from nanobot.providers.openai_compat_provider import OpenAICompatProvider 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: 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 Mistral's vibe-cli/medium-3-5 streams content as a list. The SDK accepts
list, which was previously appended verbatim to content_parts and blew it through non-strict construction even though its schema declares str.
up later with "can only concatenate str (not list) to str".
""" """
class _Delta: def chunk(content, finish=None) -> ChatCompletionChunk:
def __init__(self, content): return ChatCompletionChunk(
self.content = content id="chatcmpl-mistral",
self.tool_calls = None object="chat.completion.chunk",
self.function_call = None created=0,
model="mistral-medium-3-5",
class _Choice: choices=[Choice(
def __init__(self, content, finish=None): index=0,
self.delta = _Delta(content) delta=ChoiceDelta.model_construct(content=content),
self.finish_reason = finish finish_reason=finish,
)],
class _Chunk: )
def __init__(self, content, finish=None):
self.choices = [_Choice(content, finish)]
chunks = [ chunks = [
_Chunk([{"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]}]), chunk([{"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]}]),
_Chunk([{"type": "text", "text": "Hello "}]), chunk([{"type": "text", "text": "Hello "}]),
_Chunk("world.", finish="stop"), chunk("world.", finish="stop"),
] ]
parsed = OpenAICompatProvider._parse_chunks(chunks) parsed = OpenAICompatProvider._parse_chunks(chunks)
assert parsed.content == "Hello world." assert parsed.content == "Hello world."
+101 -210
View File
@@ -13,55 +13,79 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
import pytest import pytest
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.base import ProviderCallContext from nanobot.providers.base import ProviderCallContext
from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.providers.registry import ModelAPICapabilities, find_by_name 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.""" """Build a minimal OpenAI chat completion response."""
message = SimpleNamespace( return ChatCompletion.model_validate({
content=content, "id": "chatcmpl-test",
tool_calls=None, "object": "chat.completion",
reasoning_content=None, "created": 0,
) "model": "test-model",
choice = SimpleNamespace(message=message, finish_reason="stop") "choices": [{
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) "index": 0,
return SimpleNamespace(choices=[choice], usage=usage) "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.""" """Build a minimal chat response that includes Gemini-style extra_content."""
function = SimpleNamespace( return ChatCompletion.model_validate({
name="exec", "id": "chatcmpl-tools",
arguments='{"cmd":"ls"}', "object": "chat.completion",
provider_specific_fields={"inner": "value"}, "created": 0,
) "model": "test-model",
tool_call = SimpleNamespace( "choices": [{
id="call_123", "index": 0,
index=0, "finish_reason": "tool_calls",
type="function", "message": {
function=function, "role": "assistant",
extra_content={"google": {"thought_signature": "signed-token"}}, "content": None,
) "tool_calls": [{
message = SimpleNamespace( "id": "call_123",
content=None, "type": "function",
tool_calls=[tool_call], "function": {
reasoning_content=None, "name": "exec",
) "arguments": '{"cmd":"ls"}',
choice = SimpleNamespace(message=message, finish_reason="tool_calls") "inner": "value",
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15) },
return SimpleNamespace(choices=[choice], usage=usage) "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.""" """Build a minimal chat response with caller-supplied tool arguments."""
function = SimpleNamespace(name="optional_tool", arguments=arguments) return ChatCompletion.model_validate({
tool_call = SimpleNamespace(id="call_123", type="function", function=function) "id": "chatcmpl-arguments",
message = SimpleNamespace(content=None, tool_calls=[tool_call], reasoning_content=None) "object": "chat.completion",
choice = SimpleNamespace(message=message, finish_reason="tool_calls") "created": 0,
return SimpleNamespace(choices=[choice], usage=SimpleNamespace()) "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: def _fake_responses_response(content: str = "ok") -> MagicMock:
@@ -94,16 +118,23 @@ def _fake_responses_stream(text: str = "ok"):
return _stream() 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"): def _fake_chat_stream(text: str = "ok"):
async def _stream(): async def _stream():
yield SimpleNamespace( yield _chat_chunk({"content": text})
choices=[SimpleNamespace(finish_reason=None, delta=SimpleNamespace(content=text, reasoning_content=None, tool_calls=None))], yield _chat_chunk({}, finish="stop", usage={
usage=None, "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
) })
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),
)
return _stream() return _stream()
@@ -112,64 +143,12 @@ def _fake_chat_stream_reasoning_chunks():
"""Mimic DeepSeek-style ``chat.completions`` stream: ``reasoning_content`` then ``content``.""" """Mimic DeepSeek-style ``chat.completions`` stream: ``reasoning_content`` then ``content``."""
async def _stream(): async def _stream():
yield SimpleNamespace( yield _chat_chunk({"reasoning_content": "step1"})
choices=[ yield _chat_chunk({"reasoning_content": "step2"})
SimpleNamespace( yield _chat_chunk({"content": "answer"})
finish_reason=None, yield _chat_chunk({}, finish="stop", usage={
delta=SimpleNamespace( "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
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,
),
)
return _stream() return _stream()
@@ -178,63 +157,19 @@ def _fake_chat_stream_tool_call_chunks():
"""Mimic OpenAI-compatible streaming tool-call argument deltas.""" """Mimic OpenAI-compatible streaming tool-call argument deltas."""
async def _stream(): async def _stream():
yield SimpleNamespace( yield _chat_chunk({"tool_calls": [{
choices=[ "index": 0,
SimpleNamespace( "id": "call_write",
finish_reason=None, "type": "function",
delta=SimpleNamespace( "function": {"name": "write_file", "arguments": '{"path":"notes.md","content":"'},
content=None, }]})
reasoning_content=None, yield _chat_chunk({"tool_calls": [{
reasoning=None, "index": 0,
tool_calls=[ "function": {"arguments": 'line\\n"}'},
SimpleNamespace( }]})
index=0, yield _chat_chunk({}, finish="tool_calls", usage={
id="call_write", "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
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),
)
return _stream() return _stream()
@@ -243,57 +178,13 @@ def _fake_chat_stream_legacy_function_call_chunks():
"""Mimic older OpenAI-compatible ``delta.function_call`` chunks.""" """Mimic older OpenAI-compatible ``delta.function_call`` chunks."""
async def _stream(): async def _stream():
yield SimpleNamespace( yield _chat_chunk({"function_call": {
choices=[ "name": "write_file", "arguments": '{"path":"notes.md","content":"',
SimpleNamespace( }})
finish_reason=None, yield _chat_chunk({"function_call": {"arguments": 'line\\n"}'}})
delta=SimpleNamespace( yield _chat_chunk({}, finish="function_call", usage={
content=None, "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
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),
)
return _stream() return _stream()
+28 -9
View File
@@ -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). providers that return a reasoning_content field (e.g. MiMo, DeepSeek-R1).
""" """
from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.utils.helpers import build_assistant_message 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"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider() provider = OpenAICompatProvider()
message = SimpleNamespace(content="answer", reasoning_content="", tool_calls=None) response = ChatCompletion.model_validate({
choice = SimpleNamespace(message=message, finish_reason="stop") "id": "chatcmpl-reasoning",
response = SimpleNamespace(choices=[choice], usage=None) "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) 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 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): def _make_reasoning_chunk(
delta = SimpleNamespace(content=content, reasoning_content=reasoning, tool_calls=None) reasoning: str | None, content: str | None, finish: str | None,
choice = SimpleNamespace(finish_reason=finish, delta=delta) ) -> ChatCompletionChunk:
return SimpleNamespace(choices=[choice], usage=None) 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: def test_parse_chunks_sdk_accumulates_reasoning_content() -> None:
+43 -31
View File
@@ -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. verifies the fallback logic for all code paths.
""" """
from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.openai_compat_provider import OpenAICompatProvider from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.providers.registry import ProviderSpec 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" assert result.reasoning_content == "formal reasoning content"
# ── _parse: SDK object branch ─────────────────────────────────────────────── # ── _parse: SDK objects ────────────────────────────────────────────────────
def _make_sdk_message(content, reasoning=None, reasoning_content=None): def _make_sdk_response(content, reasoning=None, reasoning_content=None) -> ChatCompletion:
"""Create a mock SDK message object.""" return ChatCompletion.model_validate({
msg = SimpleNamespace(content=content, tool_calls=None) "id": "chatcmpl-stepfun",
if reasoning is not None: "object": "chat.completion",
msg.reasoning = reasoning "created": 0,
if reasoning_content is not None: "model": "step-3.5-flash",
msg.reasoning_content = reasoning_content "choices": [{
return msg "index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": content,
"reasoning": reasoning,
"reasoning_content": reasoning_content,
},
}],
})
def test_parse_sdk_stepfun_reasoning_fallback() -> None: 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"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC) provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
msg = _make_sdk_message(content=None, reasoning="After analysis: result is 4.") response = _make_sdk_response(content=None, reasoning="After analysis: result is 4.")
choice = SimpleNamespace(finish_reason="stop", message=msg)
response = SimpleNamespace(choices=[choice], usage=None)
result = provider._parse(response) result = provider._parse(response)
@@ -104,13 +112,11 @@ def test_parse_sdk_stepfun_reasoning_priority() -> None:
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC) provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
msg = _make_sdk_message( response = _make_sdk_response(
content=None, content=None,
reasoning="thinking process", 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) result = provider._parse(response)
@@ -218,19 +224,27 @@ def test_parse_chunks_dict_reasoning_precedence() -> None:
assert result.reasoning_content == "formal: " 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): def _make_sdk_chunk(
"""Create a mock SDK chunk object.""" reasoning_content=None, reasoning=None, content=None, finish=None,
delta = SimpleNamespace( ) -> ChatCompletionChunk:
content=content, return ChatCompletionChunk.model_validate({
reasoning_content=reasoning_content, "id": "chatcmpl-stepfun",
reasoning=reasoning, "object": "chat.completion.chunk",
tool_calls=None, "created": 0,
) "model": "step-3.5-flash",
choice = SimpleNamespace(finish_reason=finish, delta=delta) "choices": [{
return SimpleNamespace(choices=[choice], usage=None) "index": 0,
"finish_reason": finish,
"delta": {
"content": content,
"reasoning_content": reasoning_content,
"reasoning": reasoning,
},
}],
})
def test_parse_chunks_sdk_stepfun_reasoning_fallback() -> None: 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"): with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider() provider = OpenAICompatProvider()
msg = _make_sdk_message(content=None, reasoning="internal monologue") response = _make_sdk_response(content=None, reasoning="internal monologue")
choice = SimpleNamespace(finish_reason="stop", message=msg)
response = SimpleNamespace(choices=[choice], usage=None)
result = provider._parse(response) result = provider._parse(response)
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
import httpx import httpx
import pytest import pytest
from openai.types.chat import ChatCompletionChunk
import nanobot.providers.openai_codex_provider as codex_provider import nanobot.providers.openai_codex_provider as codex_provider
from nanobot.providers.anthropic_provider import AnthropicProvider 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") monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "abc")
provider = OpenAICompatProvider(api_key="sk-test", api_base="https://example.com/v1") provider = OpenAICompatProvider(api_key="sk-test", api_base="https://example.com/v1")
chunk = SimpleNamespace( chunk = ChatCompletionChunk.model_validate({
choices=[SimpleNamespace( "id": "chatcmpl-timeout",
delta=SimpleNamespace( "object": "chat.completion.chunk",
content="ok", "created": 0,
reasoning_content=None, "model": "test-model",
reasoning=None, "choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}],
tool_calls=None, })
function_call=None,
),
finish_reason="stop",
)],
usage=None,
)
provider._client = SimpleNamespace( provider._client = SimpleNamespace(
chat=SimpleNamespace(completions=SimpleNamespace( chat=SimpleNamespace(completions=SimpleNamespace(
create=AsyncMock(return_value=_AsyncStream([chunk])), create=AsyncMock(return_value=_AsyncStream([chunk])),