CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(openai): extract OSS reasoning fields + payload_quirks
xf gongdf03818bb94f
diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.pyindex 12db85f..27780d3 100644--- a/cubepi/providers/openai.py+++ b/cubepi/providers/openai.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport jsonimport time-from typing import Any+from typing import Any, Literalfrom cubepi.utils.json_parse import parse_streaming_json@@ -17,6 +17,7 @@ from cubepi.providers.base import (StreamEvent,StreamOptions,TextContent,+ ThinkingContent,ToolCall,ToolDefinition,ToolResultMessage,@@ -29,7 +30,11 @@ from cubepi.providers.base import (class OpenAIProvider:def __init__(- self, *, api_key: str | None = None, base_url: str | None = None+ self,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+ payload_quirks: list[Literal["max_completion_tokens_alias"]] | None = None,) -> None:import openai@@ -39,6 +44,7 @@ class OpenAIProvider:if base_url:kwargs["base_url"] = base_urlself._client = openai.AsyncOpenAI(**kwargs)+ self._payload_quirks: set[str] = set(payload_quirks or [])async def stream(self,@@ -70,6 +76,10 @@ class OpenAIProvider:nonlocal kwargskwargs = await invoke_on_payload(opts.on_payload, kwargs, model)+ if "max_completion_tokens_alias" in self._payload_quirks:+ if "max_completion_tokens" in kwargs:+ kwargs["max_tokens"] = kwargs.pop("max_completion_tokens")+response = await self._client.chat.completions.create(**kwargs)# Invoke on_response with HTTP metadata if available@@ -100,6 +110,8 @@ class OpenAIProvider:text_started = Falsetext_content_index = 0response_id: str | None = None+ thinking_started = False+ thinking_content_index: int | None = Noneasync for chunk in response:if response_id is None and getattr(chunk, "id", None):@@ -125,6 +137,59 @@ class OpenAIProvider:if not delta:continue+ # OSS reasoning extraction: priority order is+ # 1. delta.reasoning_content (DeepSeek/Qwen/DouBao)+ # 2. delta.reasoning (vLLM)+ # 3. delta.reasoning_details (MiniMax)+ reasoning_delta: str | None = None+ rc = getattr(delta, "reasoning_content", None)+ if rc:+ reasoning_delta = rc+ else:+ r = getattr(delta, "reasoning", None)+ if r:+ reasoning_delta = r+ else:+ rds = getattr(delta, "reasoning_details", None)+ if rds:+ parts: list[str] = []+ for d in rds:+ if hasattr(d, "text"):+ text = d.text+ elif isinstance(d, dict):+ text = d.get("text")+ else:+ text = None+ if text:+ parts.append(text)+ if parts:+ reasoning_delta = "".join(parts)++ if reasoning_delta:+ if not thinking_started:+ partial.content.append(ThinkingContent(thinking=""))+ thinking_content_index = len(partial.content) - 1+ ms.push(+ StreamEvent(+ type="thinking_start",+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ )+ )+ thinking_started = True+ existing = partial.content[thinking_content_index].thinking # type: ignore[union-attr]+ partial.content[thinking_content_index] = ThinkingContent(+ thinking=existing + reasoning_delta+ )+ ms.push(+ StreamEvent(+ type="thinking_delta",+ delta=reasoning_delta,+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ )+ )+if delta.content:if not text_started:partial.content.append(TextContent(text=""))@@ -210,6 +275,16 @@ class OpenAIProvider:chunk.choices[0].finish_reason if chunk.choices else None)if finish_reason:+ if thinking_started:+ ms.push(+ StreamEvent(+ type="thinking_end",+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ )+ )+ thinking_started = False+if text_started:ms.push(StreamEvent(diff --git a/tests/providers/test_openai_reasoning.py b/tests/providers/test_openai_reasoning.pynew file mode 100644index 0000000..902cc87--- /dev/null+++ b/tests/providers/test_openai_reasoning.py@@ -0,0 +1,456 @@+"""OpenAIProvider OSS reasoning extraction + payload_quirks tests (D4)."""+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from cubepi.providers.openai import OpenAIProvider+from cubepi.providers.base import (+ Model,+ TextContent,+ ThinkingContent,+ UserMessage,+)+++# ---------------------------------------------------------------------------+# Helpers (same style as test_openai.py)+# ---------------------------------------------------------------------------+++def _model() -> Model:+ return Model(id="deepseek-chat", provider="deepseek", api="openai")+++def _make_chunk(+ content=None,+ reasoning_content=None,+ reasoning=None,+ reasoning_details=None,+ finish_reason=None,+ id=None,+):+ """Build a mock OpenAI chat-completion chunk with optional reasoning fields."""+ delta = SimpleNamespace(+ content=content,+ tool_calls=None,+ reasoning_content=reasoning_content,+ reasoning=reasoning,+ reasoning_details=reasoning_details,+ )+ choice = SimpleNamespace(delta=delta, finish_reason=finish_reason)+ return SimpleNamespace(id=id, choices=[choice])+++async def _async_iter(chunks):+ for chunk in chunks:+ yield chunk+++def _run_stream(chunks):+ """Helper: set up mock client, return (provider, mock_client)."""+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()+ mock_client.chat.completions.create = AsyncMock(+ return_value=_async_iter(chunks)+ )+ provider = OpenAIProvider(api_key="test-key")+ provider._client = mock_client+ return provider, mock_client+++# ---------------------------------------------------------------------------+# Reasoning extraction tests+# ---------------------------------------------------------------------------+++class TestOpenAIReasoningContent:+ """delta.reasoning_content variant: DeepSeek/Qwen/DouBao."""++ @pytest.mark.asyncio+ async def test_extracts_reasoning_content_variant(self):+ """reasoning_content chunks produce thinking_start/_delta/_end events."""+ chunks = [+ _make_chunk(reasoning_content="Let me "),+ _make_chunk(reasoning_content="think"),+ _make_chunk(content="Answer"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert "thinking_start" in types+ assert "thinking_delta" in types+ assert "thinking_end" in types++ # Concatenated thinking deltas+ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert "".join(thinking_deltas) == "Let me think"++ # Final result has ThinkingContent and TextContent+ result = await ms.result()+ assert any(isinstance(c, ThinkingContent) for c in result.content)+ thinking_blocks = [c for c in result.content if isinstance(c, ThinkingContent)]+ assert thinking_blocks[0].thinking == "Let me think"++ @pytest.mark.asyncio+ async def test_thinking_end_fires_on_finish(self):+ """thinking_end is emitted when finish_reason arrives, not before."""+ chunks = [+ _make_chunk(reasoning_content="Thought"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert types.index("thinking_end") < types.index("done")++ @pytest.mark.asyncio+ async def test_thinking_start_fires_once(self):+ """thinking_start fires exactly once even with multiple reasoning_content chunks."""+ chunks = [+ _make_chunk(reasoning_content="A"),+ _make_chunk(reasoning_content="B"),+ _make_chunk(reasoning_content="C"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert types.count("thinking_start") == 1+ assert types.count("thinking_end") == 1+ assert types.count("thinking_delta") == 3+++class TestOpenAIReasoningVariantVllm:+ """delta.reasoning variant: vLLM."""++ @pytest.mark.asyncio+ async def test_extracts_reasoning_variant_vllm(self):+ """vLLM delta.reasoning field is extracted as thinking events."""+ chunks = [+ _make_chunk(reasoning="Step 1"),+ _make_chunk(reasoning=" Step 2"),+ _make_chunk(content="Result"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert "thinking_start" in types+ assert "thinking_delta" in types+ assert "thinking_end" in types++ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert "".join(thinking_deltas) == "Step 1 Step 2"++ @pytest.mark.asyncio+ async def test_reasoning_content_takes_priority_over_reasoning(self):+ """When both reasoning_content and reasoning are present, use reasoning_content."""+ chunks = [+ _make_chunk(reasoning_content="from_rc", reasoning="from_r"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert thinking_deltas == ["from_rc"]+++class TestOpenAIReasoningDetailsVariantMinimax:+ """delta.reasoning_details variant: MiniMax."""++ @pytest.mark.asyncio+ async def test_extracts_reasoning_details_list_of_objects(self):+ """MiniMax reasoning_details as list of SimpleNamespace with .text."""+ chunks = [+ _make_chunk(+ reasoning_details=[+ SimpleNamespace(text="Part A"),+ SimpleNamespace(text="Part B"),+ ]+ ),+ _make_chunk(content="Final"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert "thinking_start" in types+ assert "thinking_delta" in types++ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert "".join(thinking_deltas) == "Part APart B"++ @pytest.mark.asyncio+ async def test_extracts_reasoning_details_list_of_dicts(self):+ """MiniMax reasoning_details as list of plain dicts with 'text' key."""+ chunks = [+ _make_chunk(reasoning_details=[{"text": "Dict part"}]),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert thinking_deltas == ["Dict part"]++ @pytest.mark.asyncio+ async def test_reasoning_details_skips_empty_text(self):+ """reasoning_details entries with no text are skipped silently."""+ chunks = [+ _make_chunk(+ reasoning_details=[+ SimpleNamespace(text=""),+ SimpleNamespace(text="Only this"),+ ]+ ),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ thinking_deltas = [e.delta for e in events if e.type == "thinking_delta"]+ assert thinking_deltas == ["Only this"]+++class TestOpenAINoReasoning:+ """When no reasoning fields present, no thinking events should be emitted."""++ @pytest.mark.asyncio+ async def test_no_reasoning_no_thinking_events(self):+ """Plain content stream with no reasoning fields emits no thinking events."""+ chunks = [+ _make_chunk(content="Just text"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert "thinking_start" not in types+ assert "thinking_delta" not in types+ assert "thinking_end" not in types++ @pytest.mark.asyncio+ async def test_reasoning_content_none_does_not_trigger(self):+ """reasoning_content=None should not produce thinking events."""+ chunks = [+ _make_chunk(reasoning_content=None, content="Text"),+ _make_chunk(finish_reason="stop"),+ ]+ provider, _ = _run_stream(chunks)+ ms = await provider.stream(+ _model(), [UserMessage(content=[TextContent(text="hi")])]+ )++ events = []+ async for event in ms:+ events.append(event)++ types = [e.type for e in events]+ assert "thinking_start" not in types+++# ---------------------------------------------------------------------------+# payload_quirks tests+# ---------------------------------------------------------------------------+++class TestPayloadQuirks:+ """payload_quirks=['max_completion_tokens_alias'] renames max_completion_tokens -> max_tokens."""++ @pytest.mark.asyncio+ async def test_payload_quirk_rewrites_max_completion_tokens(self):+ """With quirk set, max_completion_tokens in kwargs is renamed to max_tokens."""+ chunks = [_make_chunk(finish_reason="stop")]+ captured_kwargs = {}++ async def on_payload(payload, model):+ payload["max_completion_tokens"] = 512+ return payload++ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()++ async def capture_create(**kwargs):+ captured_kwargs.update(kwargs)+ return _async_iter(list(chunks))++ mock_client.chat.completions.create = capture_create++ from cubepi.providers.base import StreamOptions++ provider = OpenAIProvider(+ api_key="x", payload_quirks=["max_completion_tokens_alias"]+ )+ provider._client = mock_client++ ms = await provider.stream(+ _model(),+ [UserMessage(content=[TextContent(text="hi")])],+ options=StreamOptions(on_payload=on_payload),+ )+ async for _ in ms:+ pass+ await ms.result()++ assert "max_tokens" in captured_kwargs+ assert "max_completion_tokens" not in captured_kwargs+ assert captured_kwargs["max_tokens"] == 512++ @pytest.mark.asyncio+ async def test_payload_quirk_default_no_rewrite(self):+ """Without payload_quirks, max_completion_tokens passes through unchanged."""+ chunks = [_make_chunk(finish_reason="stop")]+ captured_kwargs = {}++ async def on_payload(payload, model):+ payload["max_completion_tokens"] = 256+ return payload++ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()++ async def capture_create(**kwargs):+ captured_kwargs.update(kwargs)+ return _async_iter(list(chunks))++ mock_client.chat.completions.create = capture_create++ from cubepi.providers.base import StreamOptions++ provider = OpenAIProvider(api_key="x")+ provider._client = mock_client++ ms = await provider.stream(+ _model(),+ [UserMessage(content=[TextContent(text="hi")])],+ options=StreamOptions(on_payload=on_payload),+ )+ async for _ in ms:+ pass+ await ms.result()++ assert "max_completion_tokens" in captured_kwargs+ assert "max_tokens" not in captured_kwargs+ assert captured_kwargs["max_completion_tokens"] == 256++ @pytest.mark.asyncio+ async def test_payload_quirk_no_max_completion_tokens_noop(self):+ """With quirk set but no max_completion_tokens key, payload is unchanged."""+ chunks = [_make_chunk(finish_reason="stop")]+ captured_kwargs = {}++ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = MagicMock()+ mock_openai.return_value = mock_client+ mock_client.chat = MagicMock()+ mock_client.chat.completions = MagicMock()++ async def capture_create(**kwargs):+ captured_kwargs.update(kwargs)+ return _async_iter(list(chunks))++ mock_client.chat.completions.create = capture_create++ provider = OpenAIProvider(+ api_key="x", payload_quirks=["max_completion_tokens_alias"]+ )+ provider._client = mock_client++ ms = await provider.stream(+ _model(),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ async for _ in ms:+ pass+ await ms.result()++ assert "max_tokens" not in captured_kwargs+ assert "max_completion_tokens" not in captured_kwargs++ def test_constructor_accepts_payload_quirks(self):+ """payload_quirks parameter is accepted and stored."""+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_openai.return_value = MagicMock()+ p = OpenAIProvider(api_key="x", payload_quirks=["max_completion_tokens_alias"])+ assert "max_completion_tokens_alias" in p._payload_quirks++ def test_constructor_default_empty_quirks(self):+ """Without payload_quirks, _payload_quirks is empty."""+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_openai.return_value = MagicMock()+ p = OpenAIProvider(api_key="x")+ assert len(p._payload_quirks) == 0