diff --git a/packages/runtime/src/ginno_runtime/api/messages_ui.py b/packages/runtime/src/ginno_runtime/api/messages_ui.py index 29273d76..a8e0fa5a 100644 --- a/packages/runtime/src/ginno_runtime/api/messages_ui.py +++ b/packages/runtime/src/ginno_runtime/api/messages_ui.py @@ -21,6 +21,7 @@ from ..api import server_tools from ..goals.templates import context_row_text as goal_context_row from ..knowledge.citations import parse_citation_block, strip_citation_block +from ..models import responses_reasoning_summary from ..tools.artifact_tools import ARTIFACT_TOOL_NAMES from ..tools.render_tools import RENDER_TOOL_NAMES, split_attach_tags, widget_event from ..tools.workflow_tools import RUN_CACHE, WORKFLOW_TOOL_NAMES @@ -1171,9 +1172,11 @@ def flush_assistant() -> None: for blk in step: if blk.get("kind") == "sources" and blk.get("items"): blk["items"] = _resolve_source_items(blk["items"], ref_map) - rk = (getattr(m, "additional_kwargs", None) or {}).get("reasoning_content") - if rk: - step.insert(0, {"kind": "thinking", "text": rk}) + reasoning = responses_reasoning_summary(m) or ( + getattr(m, "additional_kwargs", None) or {} + ).get("reasoning_content") + if reasoning: + step.insert(0, {"kind": "thinking", "text": reasoning}) for tc in getattr(m, "tool_calls", None) or []: nm = tc.get("name") args = tc.get("args") or {} diff --git a/packages/runtime/src/ginno_runtime/api/stream/engine.py b/packages/runtime/src/ginno_runtime/api/stream/engine.py index 78443a46..b09252f0 100644 --- a/packages/runtime/src/ginno_runtime/api/stream/engine.py +++ b/packages/runtime/src/ginno_runtime/api/stream/engine.py @@ -36,6 +36,7 @@ from ...graph import BLOCK_PREFIX from ...knowledge import citations as cit from ...lang import t +from ...models import responses_reasoning_summary from ...server_shared import ( _PENDING_KIND, _PENDING_RESUME, diff --git a/packages/runtime/src/ginno_runtime/api/stream/stages/streamio.py b/packages/runtime/src/ginno_runtime/api/stream/stages/streamio.py index 3d19f80f..cfe814c4 100644 --- a/packages/runtime/src/ginno_runtime/api/stream/stages/streamio.py +++ b/packages/runtime/src/ginno_runtime/api/stream/stages/streamio.py @@ -185,6 +185,9 @@ async def handle_messages_text(ctx: StreamTurnCtx, chunk) -> None: 调用方(run.py)已做 chunk.type gate(``("ai","AIMessageChunk")``)。 """ + summary = eng.responses_reasoning_summary(chunk) + if summary: + await ctx._coal.feed("thinking.delta", summary) content = getattr(chunk, "content", "") if isinstance(content, list): for b in content: @@ -277,9 +280,10 @@ async def handle_messages_text(ctx: StreamTurnCtx, chunk) -> None: ctx.turn_text.append(content) ctx.seg_text.append(content) await ctx._coal.feed("token.delta", content) - rk = (getattr(chunk, "additional_kwargs", None) or {}).get("reasoning_content") - if rk: - await ctx._coal.feed("thinking.delta", rk) + if not summary: + rk = (getattr(chunk, "additional_kwargs", None) or {}).get("reasoning_content") + if rk: + await ctx._coal.feed("thinking.delta", rk) async def handle_custom(ctx: StreamTurnCtx, payload) -> None: diff --git a/packages/runtime/src/ginno_runtime/models.py b/packages/runtime/src/ginno_runtime/models.py index aa04c357..ea3846c7 100644 --- a/packages/runtime/src/ginno_runtime/models.py +++ b/packages/runtime/src/ginno_runtime/models.py @@ -275,36 +275,36 @@ def _replay_reasoning_content(messages: list[Any], payload: dict) -> None: _RESPONSES_CLS: type | None = None +def responses_reasoning_summary(message: Any) -> str: + """Read the public summary from current or legacy Responses messages.""" + def block_summary(block: Any) -> str: + if not isinstance(block, dict) or block.get("type") != "reasoning": + return "" + summary = block.get("summary") + if not isinstance(summary, list): + return "" + return "".join( + part["text"] for part in summary + if isinstance(part, dict) + and part.get("type") == "summary_text" + and isinstance(part.get("text"), str) + ) + + content = getattr(message, "content", None) + if isinstance(content, list): + text = "".join(block_summary(block) for block in content) + if text: + return text + return block_summary((getattr(message, "additional_kwargs", None) or {}).get("reasoning")) + + def bridge_responses_reasoning(gen_chunk): - """Re-attach Responses-API reasoning summaries as ``reasoning_content``. - - The Responses API streams thinking output as official *reasoning summary* - events, which langchain-openai turns into content blocks shaped - ``{"type": "reasoning", "summary": [{"type": "summary_text", "text": ...}]}`` - — NOT the third-party ``delta.reasoning_content`` field that - ReasoningChatOpenAI harvests on the chat-completions path. Ginno's - thinking pipeline (api/stream.py ``thinking.delta``; api/messages_ui.py - replay) reads ``additional_kwargs["reasoning_content"]``, so copy each - delta's summary text there. Chunk accumulation merges additional_kwargs, - so the persisted message ends up with the full reasoning text. - """ - try: - content = gen_chunk.message.content - if isinstance(content, list): - texts = [ - s.get("text", "") - for block in content - if isinstance(block, dict) and block.get("type") == "reasoning" - for s in (block.get("summary") or []) - if isinstance(s, dict) - ] - text = "".join(t for t in texts if t) - if text: - ak = getattr(gen_chunk.message, "additional_kwargs", None) - if ak is not None: - ak["reasoning_content"] = text - except (AttributeError, TypeError): - pass + """Keep the reasoning_content field used by saved messages and gateway replay.""" + message = getattr(gen_chunk, "message", None) + text = responses_reasoning_summary(message) + kwargs = getattr(message, "additional_kwargs", None) + if text and kwargs is not None: + kwargs["reasoning_content"] = text return gen_chunk diff --git a/packages/runtime/src/ginno_runtime/testing/fake_model.py b/packages/runtime/src/ginno_runtime/testing/fake_model.py index 027cbc56..7ff8781a 100644 --- a/packages/runtime/src/ginno_runtime/testing/fake_model.py +++ b/packages/runtime/src/ginno_runtime/testing/fake_model.py @@ -50,7 +50,7 @@ def script_tool_call(name: str, args: dict[str, Any] | None = None, call_id: str def script( - text: str = "", + text: str | list[str | dict] = "", tool_calls: list[dict] | None = None, msg_id: str | None = None, usage: dict | None = None, @@ -222,10 +222,9 @@ def _iter_chunks(msg: AIMessage): ) ) else: - content = msg.content if isinstance(msg.content, str) else "" yield ChatGenerationChunk( message=AIMessageChunk( - content=content, + content=msg.content, id=cid, **({"usage_metadata": usage} if usage else {}), ) diff --git a/packages/runtime/tests/e2e/test_packaged_ui_reasoning_summary.py b/packages/runtime/tests/e2e/test_packaged_ui_reasoning_summary.py new file mode 100644 index 00000000..31d08180 --- /dev/null +++ b/packages/runtime/tests/e2e/test_packaged_ui_reasoning_summary.py @@ -0,0 +1,55 @@ +"""Responses reasoning summaries are visible during chat and after reload.""" + +from __future__ import annotations + +import json +import re + +import pytest +import test_packaged_ui_tasks_overview as smoke + +pytestmark = pytest.mark.e2e + +SUMMARY = "Compare the two choices before answering." +ANSWER = "Choose the second option." + + +def test_reasoning_summary_in_chat_and_history(tmp_path, monkeypatch): + smoke._require_runtime() + from playwright.sync_api import expect, sync_playwright + + scripts = tmp_path / "responses.json" + scripts.write_text(json.dumps([{"content": [ + {"type": "reasoning", "summary": [{"type": "summary_text", "text": SUMMARY}]}, + {"type": "text", "text": ANSWER}, + ]}])) + monkeypatch.setenv("GINNO_FAKE_LLM_SCRIPTS", str(scripts)) + port = smoke._free_port() + proc, log = smoke._spawn(tmp_path, port) + try: + smoke._wait_health(port) + with sync_playwright() as pw: + browser, page = smoke._new_page(pw) + try: + page.goto(f"http://127.0.0.1:{port}/", wait_until="load") + title = "Reasoning summary test" + ta = page.locator("textarea").first + ta.fill(title) + ta.press("Enter") + expect(page.get_by_text(ANSWER, exact=True)).to_be_visible(timeout=15_000) + + def check_summary(): + panel = page.get_by_role("button", name=re.compile(r"^Deeply thought")) + expect(panel).to_have_count(1) + if panel.get_attribute("title") == "Expand reasoning": + panel.click() + expect(page.get_by_text(SUMMARY, exact=True)).to_be_visible() + + check_summary() + page.reload(wait_until="load") + expect(page.get_by_text(ANSWER, exact=True)).to_be_visible(timeout=15_000) + check_summary() + finally: + browser.close() + finally: + smoke._stop(proc, log) diff --git a/packages/runtime/tests/e2e/test_stream_event_order_e2e.py b/packages/runtime/tests/e2e/test_stream_event_order_e2e.py index d9bc0669..2522b56b 100644 --- a/packages/runtime/tests/e2e/test_stream_event_order_e2e.py +++ b/packages/runtime/tests/e2e/test_stream_event_order_e2e.py @@ -10,14 +10,17 @@ from __future__ import annotations +import httpx import pytest -from conftest import event_names +from conftest import event_names, events_of from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, AIMessageChunk, ToolMessage from langchain_core.outputs import ChatGenerationChunk, ChatResult, ChatGeneration +from openai import AsyncOpenAI from pydantic import PrivateAttr from ginno_runtime import jsonx as json +from ginno_runtime import models from ginno_runtime.api.stream import delta_coalesce pytestmark = pytest.mark.e2e @@ -148,4 +151,52 @@ def test_thinking_does_not_overtake_buffered_text(create_session, ws_conv): ) assert before == "正文尾片", ( f"thinking 插队到缓冲文本前: thinking.delta 前只收到 {before!r}" - ) \ No newline at end of file + ) + + +@pytest.mark.parametrize("protocol", ["openai-compatible", "openai-responses"]) +def test_codex_reasoning_summary_reaches_websocket_once( + protocol, client, create_session, ws_conv, monkeypatch, +): + name = "codex/gpt-6.2-sol" + cfg = { + "enabled": True, + "protocol": protocol, + "api_key": "fixture-key", + "base_url": "https://responses.example.test/v1", + "default_model": name, + } + monkeypatch.setattr(models.prov_mod, "load_providers", lambda: {"fixture": cfg}) + model = models.build_model("fixture") + wire_events = [ + {"type": "response.reasoning_summary_text.delta", "delta": text, + "output_index": 0, "summary_index": 0, "item_id": "rs_test", "sequence_number": i} + for i, text in enumerate(("Compare ", "choices.")) + ] + wire_events.append({ + "type": "response.output_text.delta", "delta": "Choose B.", + "output_index": 1, "content_index": 0, "item_id": "msg_test", "sequence_number": 2, + }) + requests = [] + + def provider(request): + requests.append(request.url.path) + body = "".join(f"data: {json.dumps(event)}\n\n" for event in wire_events) + return httpx.Response(200, content=body, headers={"Content-Type": "text/event-stream"}) + + transport = httpx.AsyncClient(transport=httpx.MockTransport(provider)) + model.root_async_client = AsyncOpenAI( + base_url=cfg["base_url"], api_key=cfg["api_key"], http_client=transport, + ) + try: + sid = create_session(model, title="Summary transport test") + with ws_conv(sid) as conv: + conv.invoke("Select an option.") + events = conv.recv_until("message.end", "error") + finally: + client.portal.call(transport.aclose) + + assert requests == ["/v1/responses"] + assert not events_of(events, "error") + assert "".join(e["content"] for e in events_of(events, "thinking.delta")) == "Compare choices." + assert "".join(e["content"] for e in events_of(events, "token.delta")) == "Choose B." \ No newline at end of file diff --git a/packages/runtime/tests/unit/test_content_blocks.py b/packages/runtime/tests/unit/test_content_blocks.py index 1d9e9728..9dc61f77 100644 --- a/packages/runtime/tests/unit/test_content_blocks.py +++ b/packages/runtime/tests/unit/test_content_blocks.py @@ -10,6 +10,7 @@ import base64 +import pytest from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from ginno_runtime.graph import _latest_human_text, text_of_content @@ -148,6 +149,36 @@ def test_ai_content_blocks_includes_thinking_text_and_image(): assert blocks[2]["url"] == f"data:image/png;base64,{B64}" +@pytest.mark.parametrize("shape", ["native", "legacy", "bridged", "encrypted-only"]) +def test_responses_reasoning_summary_replays_once(shape): + block = { + "type": "reasoning", + "summary": [{"type": "summary_text", "text": "Compare choices."}], + "encrypted_content": "ciphertext", + } + answer = {"type": "text", "text": "Choose B."} + kwargs = {} + if shape == "legacy": + kwargs["reasoning"] = block + content = [answer] + else: + content = [block, answer] + if shape == "bridged": + kwargs["reasoning_content"] = "Compare choices." + elif shape == "encrypted-only": + block["summary"] = [] + + messages = _messages_to_ui([ + HumanMessage(content="Choose an option."), + AIMessage(content=content, additional_kwargs=kwargs), + ], agent_id="dev") + blocks = [block for m in messages if m["role"] == "assistant" for block in m["blocks"]] + assert blocks[-1] == {"kind": "text", "text": "Choose B."} + assert blocks[:-1] == ( + [] if shape == "encrypted-only" else [{"kind": "thinking", "text": "Compare choices."}] + ) + + # --------------------------------------------------------------------------- # # _tool_content_str / _truncate_for_ws # --------------------------------------------------------------------------- #