蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测 v2 messages/updates/values/custom 组合流式、chunk.text 多模态块提取、astream 拼接与 SSE JSON 帧封装

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-streaming.py
explore-streaming.py394 行
"""Offline deterministic runtime lab for LangChain Chapter 18 (streaming)."""
import asyncio
import json
import platform
from typing import Any, Iterator

from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langgraph.config import get_stream_writer
from pydantic import Field


class ScriptedStreamingModel(BaseChatModel):
    responses: list[AIMessage] = Field(default_factory=list)
    call_index: int = 0
    explicit_chunks: list[Any] | None = None
    chunk_size: int = 4

    @property
    def _llm_type(self) -> str:
        return "scripted-offline-streaming"

    def bind_tools(self, tools, **kwargs):
        return self

    def _generate(
        self,
        messages: list[BaseMessage],
        stop: list[str] | None = None,
        run_manager: Any = None,
        **kwargs: Any,
    ) -> ChatResult:
        idx = min(self.call_index, len(self.responses) - 1)
        self.call_index += 1
        return ChatResult(generations=[ChatGeneration(message=self.responses[idx])])

    def _stream(
        self,
        messages: list[BaseMessage],
        stop: list[str] | None = None,
        run_manager: Any = None,
        **kwargs: Any,
    ) -> Iterator[ChatGenerationChunk]:
        idx = min(self.call_index, len(self.responses) - 1)
        self.call_index += 1
        msg = self.responses[idx]
        if msg.tool_calls:
            yield ChatGenerationChunk(
                message=AIMessageChunk(content=msg.content, tool_calls=msg.tool_calls, id=msg.id)
            )
            return
        if self.explicit_chunks is not None:
            for item in self.explicit_chunks:
                if run_manager and isinstance(item, str):
                    run_manager.on_llm_new_token(item)
                yield ChatGenerationChunk(message=AIMessageChunk(content=item))
            return
        text = str(msg.content)
        for i in range(0, len(text), self.chunk_size):
            piece = text[i : i + self.chunk_size]
            if run_manager:
                run_manager.on_llm_new_token(piece)
            yield ChatGenerationChunk(message=AIMessageChunk(content=piece))


def case_messages_v2_chunk_metadata_and_block_text() -> dict:
    m = ScriptedStreamingModel(
        responses=[AIMessage(content="unused")],
        explicit_chunks=[
            "你好",
            "!欢迎",
            [{"type": "text", "text": "学习 Python。"}],
        ],
    )
    agent = create_agent(model=m, tools=[])
    first_info = None
    pieces: list[str] = []
    envelope_keys: list[str] = []

    for ev in agent.stream(
        {"messages": [{"role": "user", "content": "打个招呼"}]},
        stream_mode="messages",
        version="v2",
    ):
        if not envelope_keys:
            envelope_keys = sorted(ev.keys())
        if ev["type"] != "messages":
            continue
        chunk, meta = ev["data"]
        if meta.get("langgraph_node") == "model" and chunk.text:
            if first_info is None:
                first_info = {
                    "text": chunk.text,
                    "node": meta.get("langgraph_node"),
                    "type": type(chunk).__name__,
                }
            pieces.append(chunk.text)

    joined = "".join(pieces)
    actual = {
        "envelope_keys": envelope_keys,
        "first_info": first_info,
        "chunk_count": len(pieces),
        "char_count": len(joined),
        "chunk_ne_chars": len(pieces) != len(joined),
        "joined_text": joined,
    }
    expected = {
        "envelope_keys": ["data", "ns", "type"],
        "first_info": {"text": "你好", "node": "model", "type": "AIMessageChunk"},
        "chunk_count": 3,
        "char_count": 15,
        "chunk_ne_chars": True,
        "joined_text": "你好!欢迎学习 Python。",
    }
    return {
        "name": "messages_v2_chunk_metadata_and_block_text",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_updates_and_values_v2() -> dict:
    @tool
    def search_course(keyword: str) -> str:
        """按关键词查询模拟编程课程。"""
        return {"python": "Python3 基础教程", "html": "HTML 基础教程"}.get(
            keyword.lower(), "未找到相关模拟课程"
        )

    m_upd = ScriptedStreamingModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_course", "args": {"keyword": "python"}, "id": "u1", "type": "tool_call"}
                ],
            ),
            AIMessage(content="可以先学习 Python3 基础教程。"),
        ]
    )
    ag_upd = create_agent(model=m_upd, tools=[search_course])
    upd_nodes: list[str] = []
    tool_outputs: list[str] = []
    for ev in ag_upd.stream(
        {"messages": [{"role": "user", "content": "搜索 python 课程"}]},
        stream_mode="updates",
        version="v2",
    ):
        if ev["type"] != "updates":
            continue
        for node, upd in ev["data"].items():
            upd_nodes.append(node)
            if isinstance(upd, dict):
                for msg in upd.get("messages", []):
                    if msg.type == "tool":
                        tool_outputs.append(f"{msg.name}:{msg.content}")

    m_val = ScriptedStreamingModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_course", "args": {"keyword": "python"}, "id": "u2", "type": "tool_call"}
                ],
            ),
            AIMessage(content="可以先学习 Python3 基础教程。"),
        ]
    )
    ag_val = create_agent(model=m_val, tools=[search_course])
    value_shapes = []
    for ev in ag_val.stream(
        {"messages": [{"role": "user", "content": "搜索 python 课程"}]},
        stream_mode="values",
        version="v2",
    ):
        if ev["type"] == "values":
            value_shapes.append([m.type for m in ev["data"].get("messages", [])])

    actual = {
        "updates_nodes": upd_nodes,
        "tool_outputs": tool_outputs,
        "values_shapes": value_shapes,
    }
    expected = {
        "updates_nodes": ["model", "tools", "model"],
        "tool_outputs": ["search_course:Python3 基础教程"],
        "values_shapes": [
            ["human"],
            ["human", "ai"],
            ["human", "ai", "tool"],
            ["human", "ai", "tool", "ai"],
        ],
    }
    return {
        "name": "updates_and_values_v2",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_custom_and_combined_modes() -> dict:
    @tool
    def process_files(task: str) -> str:
        """模拟处理三个文件,并报告处理进度。"""
        writer = get_stream_writer()
        for i in range(1, 4):
            writer({"task": task, "current": i, "total": 3, "message": f"已处理 {i}/3"})
        return "三个模拟文件处理完成"

    m = ScriptedStreamingModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "process_files", "args": {"task": "测试文件"}, "id": "f1", "type": "tool_call"}
                ],
            ),
            AIMessage(content="三个模拟文件处理完成"),
        ],
        chunk_size=5,
    )
    agent = create_agent(model=m, tools=[process_files])
    custom_msgs: list[str] = []
    update_nodes: list[str] = []
    text_parts: list[str] = []

    for ev in agent.stream(
        {"messages": [{"role": "user", "content": "模拟处理测试文件"}]},
        stream_mode=["messages", "updates", "custom"],
        version="v2",
    ):
        mode = ev["type"]
        if mode == "custom":
            custom_msgs.append(ev["data"]["message"])
        elif mode == "updates":
            update_nodes.extend(ev["data"].keys())
        elif mode == "messages":
            chunk, meta = ev["data"]
            if meta.get("langgraph_node") == "model" and chunk.text:
                text_parts.append(chunk.text)

    actual = {
        "custom_msgs": custom_msgs,
        "update_nodes": update_nodes,
        "joined_text": "".join(text_parts),
    }
    expected = {
        "custom_msgs": ["已处理 1/3", "已处理 2/3", "已处理 3/3"],
        "update_nodes": ["model", "tools", "model"],
        "joined_text": "三个模拟文件处理完成",
    }
    return {
        "name": "custom_and_combined_modes",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_astream_async_collection() -> dict:
    m = ScriptedStreamingModel(
        responses=[AIMessage(content="语法简洁、生态丰富、易于学习")],
        chunk_size=4,
    )
    agent = create_agent(model=m, tools=[])

    async def run_async() -> tuple[list[str], str, int]:
        full_text: list[str] = []
        async for ev in agent.astream(
            {"messages": [{"role": "user", "content": "Python 三个优点"}]},
            stream_mode="messages",
            version="v2",
        ):
            if ev["type"] != "messages":
                continue
            chunk, meta = ev["data"]
            if meta.get("langgraph_node") == "model" and chunk.text:
                full_text.append(chunk.text)
        joined = "".join(full_text)
        return full_text, joined, len(joined)

    chunks, joined, char_len = asyncio.run(run_async())
    actual = {
        "chunks": chunks,
        "joined": joined,
        "char_len": char_len,
    }
    expected = {
        "chunks": ["语法简洁", "、生态丰", "富、易于", "学习"],
        "joined": "语法简洁、生态丰富、易于学习",
        "char_len": 14,
    }
    return {
        "name": "astream_async_collection",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_sse_json_framing_and_special_chars() -> dict:
    def sse(event: str, data: dict) -> str:
        return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"

    m = ScriptedStreamingModel(
        responses=[AIMessage(content="unused")],
        explicit_chunks=["第一行\n第二行", " <tag>安全文本</tag>"],
    )
    agent = create_agent(model=m, tools=[])

    async def collect_sse() -> list[str]:
        frames: list[str] = []
        async for item in agent.astream(
            {"messages": [{"role": "user", "content": "测试换行与标签"}]},
            stream_mode="messages",
            version="v2",
        ):
            if item["type"] != "messages":
                continue
            chunk, meta = item["data"]
            if meta.get("langgraph_node") == "model" and chunk.text:
                frames.append(sse("token", {"text": chunk.text}))
        frames.append(sse("done", {"finished": True}))
        return frames

    frames = asyncio.run(collect_sse())
    parsed_events: list[tuple[str, dict]] = []
    single_line_data_ok = True
    for frame in frames:
        assert frame.endswith("\n\n")
        lines = frame.rstrip("\n").split("\n")
        if len(lines) != 2 or not lines[0].startswith("event: ") or not lines[1].startswith("data: "):
            single_line_data_ok = False
        ev_name = lines[0][len("event: ") :]
        payload = json.loads(lines[1][len("data: ") :])
        parsed_events.append((ev_name, payload))

    reconstructed = "".join(p["text"] for name, p in parsed_events if name == "token")
    err_frame = sse("error", {"message": "模型请求失败,请稍后重试"})

    actual = {
        "frame_count": len(frames),
        "single_line_data_ok": single_line_data_ok,
        "event_names": [name for name, _ in parsed_events],
        "reconstructed_text": reconstructed,
        "done_flag": parsed_events[-1][1]["finished"],
        "error_frame_valid": err_frame.startswith("event: error\ndata: ") and err_frame.endswith("\n\n"),
    }
    expected = {
        "frame_count": 3,
        "single_line_data_ok": True,
        "event_names": ["token", "token", "done"],
        "reconstructed_text": "第一行\n第二行 <tag>安全文本</tag>",
        "done_flag": True,
        "error_frame_valid": True,
    }
    return {
        "name": "sse_json_framing_and_special_chars",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def main() -> None:
    cases = [
        case_messages_v2_chunk_metadata_and_block_text(),
        case_updates_and_values_v2(),
        case_custom_and_combined_modes(),
        case_astream_async_collection(),
        case_sse_json_framing_and_special_chars(),
    ]
    print(
        json.dumps(
            {
                "version": platform.python_version(),
                "system": platform.system(),
                "cases": cases,
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。

入口文件:projects/langchain-streaming-lab/explore-streaming.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-streaming.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LangChain

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip

下载课程关联工程包:LangChain

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a535.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习