[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792C9XGWY83F7DSDM3EQKC6":3,"skill-same:01M792C9XGWY83F7DSDM3EQKC6":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M792C9XGWY83F7DSDM3EQKC6","langchain-langgraph-streaming",null,"Pick the correct LangGraph 1.0 stream_mode (\"messages\" vs \"updates\" vs \"values\"),\nwire it into SSE or WebSocket without proxy-buffering gotchas, and filter\nastream_events(v2) server-side before forwarding to the browser. Use when\nbuilding a live-token chat UI, a per-node progress bar, a debug\u002Ftime-travel\nview, or diagnosing a LangGraph stream that hangs over a production proxy.\nTrigger with \"langgraph streaming\", \"stream_mode messages\", \"stream_mode updates\",\n\"stream_mode values\", \"langgraph SSE\", \"langgraph astream_events\", \"SSE hangs\nbehind nginx\", \"cloud run streaming\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-streaming\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-langgraph-streaming\ndescription: |\n  Pick the correct LangGraph 1.0 stream_mode (\"messages\" vs \"updates\" vs \"values\"),\n  wire it into SSE or WebSocket without proxy-buffering gotchas, and filter\n  astream_events(v2) server-side before forwarding to the browser. Use when\n  building a live-token chat UI, a per-node progress bar, a debug\u002Ftime-travel\n  view, or diagnosing a LangGraph stream that hangs over a production proxy.\n  Trigger with \"langgraph streaming\", \"stream_mode messages\", \"stream_mode updates\",\n  \"stream_mode values\", \"langgraph SSE\", \"langgraph astream_events\", \"SSE hangs\n  behind nginx\", \"cloud run streaming\".\nallowed-tools: Read, Write, Edit, Bash(python:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, streaming, sse, websocket]\ncompatible-with: claude-code, codex\n---\n\n# LangGraph Streaming (Python)\n\n## Overview\n\nAn engineer ships `stream_mode=\"values\"` to a token-level chat UI because it\n\"seemed the most complete.\" Every single token causes the full graph state —\nmessage history, scratchpad, plan — to be re-sent and re-rendered. At ~60\ntokens\u002Fsec the browser overdraws, the React reconciler can't keep up, the tab\nfreezes, and users blame the model. The correct answer was `stream_mode=\"messages\"`,\nwhich emits an `AIMessageChunk` delta per token (typically 5-50 bytes) — one\ntoken's worth of DOM work. This is pain-catalog entry **P19** and it is the #1\nLangGraph integration mistake in the 1.0 generation.\n\nThen the same UI ships to Cloud Run and hangs forever. No error. No logs. The\nserver is emitting tokens; they just never reach the browser. Default proxy\nbuffering (Nginx, Cloud Run's HTTP\u002F1.1 path, Cloudflare Free) holds the last\nchunk waiting for more bytes. This is **P46** — SSE streams from LangGraph\ndrop the final `end` event over proxies that buffer — and the fix is three\nheaders: `X-Accel-Buffering: no`, `Cache-Control: no-cache`, `Connection: keep-alive`.\n\nAnd then the debug view starts crashing browser tabs on long runs. The engineer\nforwarded `astream_events(version=\"v2\")` raw to the client because \"it has more\ndetail\" — but v2 emits thousands of events per invocation (per-token, per-node,\nper-runnable lifecycle), and a 60-second agent run easily hits 3,000 events.\nBrowsers freeze on the JSON deserialize queue. This is **P47** — filter\nserver-side, forward only `on_chat_model_stream` tokens (and optionally\n`on_tool_start` \u002F `on_tool_end`).\n\nThis skill ships the decision matrix, a production-grade FastAPI SSE endpoint\nwith the anti-buffering headers and a 15-second heartbeat, a server-side v2\nevent filter that drops ~90% of noise, and a WebSocket variant with\nreconnect-by-`thread_id` that resumes from the LangGraph checkpointer. Pin:\n`langgraph 1.0.x`, `langchain-core 1.0.x`. Pain-catalog anchors: **P19, P46,\nP47, P48, P67**, plus P16 for the `thread_id` rule and P22 for checkpointer\npersistence.\n\n## Prerequisites\n\n- Python 3.10+\n- `langgraph >= 1.0, \u003C 2.0`, `langchain-core >= 1.0, \u003C 2.0`\n- `fastapi >= 0.110`, `uvicorn[standard]` (for SSE\u002FWebSocket hosting)\n- A checkpointer: `langgraph.checkpoint.memory.MemorySaver` for dev, or\n  `langgraph.checkpoint.postgres.PostgresSaver` for prod\n- Access to deploy behind your actual proxy (Nginx \u002F Cloud Run \u002F Cloudflare) —\n  localhost does not reproduce the buffering class of bugs\n\n## Instructions\n\n### Step 1 — Pick the right `stream_mode` for your UI\n\nThe three modes emit fundamentally different payloads. Match the mode to the\nUI shape **before** writing any server code.\n\n| UI type | `stream_mode` | Payload each tick | Emit rate | Overdraw risk | Typical bandwidth per 5s run |\n|---|---|---|---|---|---|\n| Live-token chat | `\"messages\"` | `(AIMessageChunk, metadata)` delta | ~30-80 tokens\u002Fsec | Low | ~5-15 KB |\n| Per-node progress bar \u002F status line | `\"updates\"` | `{node_name: state_diff}` | 1 per node (~2-20 per run) | Low | ~1-5 KB |\n| Debug \u002F time-travel \u002F state replay | `\"values\"` | Entire graph state dict | 1 per node (~2-20 per run) | **High** (state size × steps) | ~20 KB to MBs |\n| Hybrid (progress + tokens) | `[\"updates\", \"messages\"]` | `(mode, payload)` interleaved | Sum of above | Depends on inner modes | Sum |\n| Non-browser observability | `astream_events(v2)` + filter | Filtered dicts | Depends on filter | Low (server-controlled) | Controlled |\n\nDecision tree:\n\n```\nDo you need LLM tokens rendered live in the UI?\n├── Yes → stream_mode=\"messages\"\n│         (add \"updates\" to the list if you also want per-node progress)\n└── No, I need per-step progress\n    ├── Full state for debug\u002Freplay? → stream_mode=\"values\"\n    └── Just what changed (most UIs)  → stream_mode=\"updates\"\n```\n\nFull payload samples and combined-mode examples are in\n[Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### Step 2 — Wire a minimal SSE endpoint\n\n```python\nimport asyncio, json\nfrom fastapi import FastAPI\nfrom fastapi.responses import StreamingResponse\nfrom langchain_core.messages import HumanMessage\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom app.graph import build_graph\n\napp = FastAPI()\ngraph = build_graph(checkpointer=MemorySaver())\n\n\ndef sse(event: str, data: dict) -> str:\n    return f\"event: {event}\\ndata: {json.dumps(data, default=str)}\\n\\n\"\n\n\nasync def stream_tokens(thread_id: str, user_input: str):\n    config = {\"configurable\": {\"thread_id\": thread_id}}\n    async for chunk, metadata in graph.astream(\n        {\"messages\": [HumanMessage(user_input)]},\n        config=config,\n        stream_mode=\"messages\",\n    ):\n        # chunk.content may be list[dict] on Claude tool-use turns (P02)\n        text = chunk.text if hasattr(chunk, \"text\") else (\n            chunk.content if isinstance(chunk.content, str) else None\n        )\n        if text:\n            yield sse(\"token\", {\"text\": text, \"node\": metadata.get(\"langgraph_node\")})\n    yield sse(\"done\", {\"thread_id\": thread_id})\n```\n\nAlways use `graph.astream(...)` (async). Never call `graph.stream(...)` (sync)\nfrom inside an async handler — it blocks the event loop and one slow request\nblocks every other connection (P48).\n\n### Step 3 — Set the anti-buffering headers\n\n```python\n@app.get(\"\u002Fstream\")\nasync def stream(thread_id: str, q: str):\n    return StreamingResponse(\n        stream_tokens(thread_id, q),\n        media_type=\"text\u002Fevent-stream\",\n        headers={\n            \"X-Accel-Buffering\": \"no\",    # Nginx \u002F Cloud Run \u002F Cloudflare\n            \"Cache-Control\": \"no-cache\",  # Block intermediate caches\n            \"Connection\": \"keep-alive\",   # Hold the TCP connection\n        },\n    )\n```\n\nThese three headers are non-negotiable in production. Without them, your\nstream works on localhost and hangs on Cloud Run. See [SSE Endpoint Template](references\u002Fsse-endpoint-template.md)\nfor the full template with a 15-second heartbeat (required to survive Cloud\nRun's 60s idle timeout and corporate-proxy timeouts) plus reverse-proxy\nsnippets for Nginx, Traefik, and Cloud Run.\n\n### Step 4 — Filter `astream_events(version=\"v2\")` server-side\n\nIf your UI needs richer events than `\"messages\"` provides — tool start\u002Fend,\nprogress markers, retrieval events — do **not** forward `astream_events`\nraw. A single 60-second agent run can emit 3,000+ events. Filter on the\nserver and forward only what the browser uses.\n\n```python\nFORWARD = {\"on_chat_model_stream\", \"on_tool_start\", \"on_tool_end\"}\n\nasync def filtered(graph, inputs, config):\n    async for event in graph.astream_events(inputs, config=config, version=\"v2\"):\n        kind = event[\"event\"]\n        if kind == \"on_chat_model_stream\":\n            chunk = event[\"data\"][\"chunk\"]\n            text = chunk.text if hasattr(chunk, \"text\") else None\n            if text:\n                yield {\"type\": \"token\", \"text\": text,\n                       \"node\": event[\"metadata\"].get(\"langgraph_node\")}\n        elif kind == \"on_tool_start\":\n            yield {\"type\": \"tool_start\", \"tool\": event[\"name\"]}\n        elif kind == \"on_tool_end\":\n            yield {\"type\": \"tool_end\", \"tool\": event[\"name\"]}\n        # Drop: on_chain_*, on_parser_*, on_prompt_*, on_retriever_* (P47)\n```\n\nNever use `astream_log()` in new code — soft-deprecated in 1.0 (P67), scheduled\nfor removal in 2.0. Use `astream_events(version=\"v2\")` instead. Full event\ntaxonomy and compression\u002Fbackpressure patterns in\n[Astream Events Filtering](references\u002Fastream-events-filtering.md).\n\n### Step 5 — WebSocket variant with reconnect\n\nUse WebSocket instead of SSE when the user may cancel, interrupt, or send\nfollow-up messages mid-stream. WebSocket also sidesteps Cloudflare Free's\ndefault response buffering.\n\n```python\nfrom fastapi import WebSocket, WebSocketDisconnect\n\n@app.websocket(\"\u002Fws\u002F{thread_id}\")\nasync def ws(websocket: WebSocket, thread_id: str):\n    await websocket.accept()\n    config = {\"configurable\": {\"thread_id\": thread_id}}  # P16 — always\n    try:\n        while True:\n            msg = json.loads(await websocket.receive_text())\n            if msg[\"type\"] == \"user_message\":\n                async for chunk, metadata in graph.astream(\n                    {\"messages\": [HumanMessage(msg[\"text\"])]},\n                    config=config,\n                    stream_mode=\"messages\",\n                ):\n                    text = chunk.text if hasattr(chunk, \"text\") else None\n                    if text:\n                        await websocket.send_json({\"type\": \"token\", \"text\": text})\n                await websocket.send_json({\"type\": \"done\"})\n    except WebSocketDisconnect:\n        pass  # Checkpointer persists state; reconnect with same thread_id resumes\n```\n\nBecause LangGraph checkpointers persist state per `thread_id`, a client that\nreconnects to `\u002Fws\u002F{same-thread-id}` automatically sees the prior conversation\nhistory on the next turn — no special \"resume\" handshake required for\nbetween-turn reconnects. For mid-stream reconnects and cancellation handling,\nsee [WebSocket & Reconnect](references\u002Fwebsocket-and-reconnect.md).\n\n### Step 6 — Run the proxy-readiness checklist before shipping\n\nA stream that works on `uvicorn --reload main:app` on your laptop will hang\nbehind Cloud Run. Before you ship, walk this checklist:\n\n- [ ] Deployed endpoint returns `Content-Type: text\u002Fevent-stream` (or `101 Switching Protocols` for WebSocket)\n- [ ] Deployed endpoint returns `X-Accel-Buffering: no` and `Cache-Control: no-cache`\n- [ ] `curl -N https:\u002F\u002Fyour.app\u002Fstream?...` shows tokens arriving incrementally — NOT all at once at the end\n- [ ] Cloud Run deployed with `--use-http2` (HTTP\u002F2 end-to-end flushes chunks reliably)\n- [ ] If behind Cloudflare: Free plan may buffer — test on Pro or use a paid page rule to disable response buffering (or switch to WebSocket)\n- [ ] 15-second heartbeat configured (`: heartbeat\\n\\n` SSE comment every 15s) so idle streams don't get killed by the 60s timeout\n- [ ] Long-idle load test: run a tool-using agent that waits 45s on an API call; stream should stay alive\n\nTest behind your actual proxy, not just localhost.\n\n## Output\n\n- `stream_mode` chosen deliberately from the decision matrix (`\"messages\"` for tokens, `\"updates\"` for progress, `\"values\"` for debug)\n- Minimal FastAPI SSE endpoint using `graph.astream(..., stream_mode=\"messages\")` in an async handler\n- Required anti-buffering headers (`X-Accel-Buffering`, `Cache-Control`, `Connection`) on the `StreamingResponse`\n- Server-side `astream_events(version=\"v2\")` filter that forwards only `on_chat_model_stream` + `on_tool_start` + `on_tool_end`\n- Optional WebSocket variant with `thread_id` required at the route and checkpointer-backed resume\n- Proxy-readiness checklist walked end-to-end before shipping past localhost\n\n## Error Handling\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Browser tab freezes on token stream | Shipped `stream_mode=\"values\"` to a token UI; full state on every tick (P19) | Switch to `stream_mode=\"messages\"` — emits per-token deltas only |\n| Per-node progress bar never advances | Shipped `stream_mode=\"messages\"` to a per-node UI; no node-boundary events (P19) | Switch to `stream_mode=\"updates\"` |\n| Stream works on localhost, hangs on Cloud Run | Proxy buffering holds last chunk (P46) | Add `X-Accel-Buffering: no`, `Cache-Control: no-cache` headers; deploy Cloud Run with `--use-http2` |\n| Stream closes after ~60s with no data | Idle-connection timeout on proxy | Send `: heartbeat\\n\\n` SSE comment every 15s |\n| Browser tab freezes on long `astream_events` run | Forwarded unfiltered v2 events; 3,000+ events per run (P47) | Filter server-side: forward only `on_chat_model_stream` + optional tool events |\n| `DeprecationWarning: astream_log is deprecated` | Using soft-deprecated API (P67) | Migrate to `astream_events(version=\"v2\")` |\n| Agent has amnesia on every WebSocket message | Missing `thread_id` in config (P16) | Require `thread_id` at route; assert in middleware |\n| `AttributeError: 'list' object has no attribute 'lower'` on chunk.content | Claude streams content blocks, not plain strings on tool-use turns (P02) | Use `chunk.text` (1.0+) or check `isinstance(chunk.content, str)` before calling string methods |\n| One slow request blocks all other WebSocket clients | Sync `graph.stream()` or `graph.invoke()` inside async handler (P48) | Always use `graph.astream()` \u002F `graph.ainvoke()` in async contexts |\n| Cloudflare Free plan buffers SSE | Free-tier response buffering | Upgrade plan with page rule to disable buffering, or switch endpoint to WebSocket |\n\n## Examples\n\n### Live-token chat UI (the default case)\n\n`stream_mode=\"messages\"` plus SSE plus the three anti-buffering headers. One\ntoken per SSE frame (~5-50 bytes each), 30-80 frames\u002Fsec during active model\ngeneration, heartbeat every 15s during tool waits. See\n[SSE Endpoint Template](references\u002Fsse-endpoint-template.md) for the complete\nFastAPI example including heartbeat, reverse-proxy config, and the client\n`EventSource` code.\n\n### Per-node progress bar for a multi-step agent\n\n`stream_mode=\"updates\"` yields one event per node (typically 2-20 per\ninvocation). Render as discrete status ticks: \"Planning...\" → \"Searching...\" →\n\"Summarizing...\" → \"Done.\" Payload is tiny (~100 bytes per tick). Combine with\n`\"messages\"` (`stream_mode=[\"updates\", \"messages\"]`) to show both progress\nticks and streaming tokens in the active node's pane. Full payload samples in\n[Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### Debug \u002F time-travel view with `\"values\"`\n\n`stream_mode=\"values\"` yields the entire graph state after each node. Useful\nfor state replay, test recording, observability pipelines — **not** for\nbrowser UIs where state size × steps × re-render quickly freezes the tab.\nPipe to a server-side log (or LangSmith), not to the browser. Example and\ncaveats in [Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### WebSocket with reconnect-by-`thread_id`\n\nWhen users can cancel mid-stream or send follow-up messages before the\nprevious turn finishes. The `thread_id` is required at the route; the\ncheckpointer persists history; reconnecting with the same `thread_id`\nautomatically sees prior turns. Cancellation is implemented via\n`asyncio.Task.cancel()` on the active `astream` iteration. Worked example\nwith half-open connection detection in\n[WebSocket & Reconnect](references\u002Fwebsocket-and-reconnect.md).\n\n## Resources\n\n- [LangGraph streaming how-to](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Fstreaming\u002F)\n- [LangGraph streaming concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fstreaming\u002F)\n- [LangChain `astream_events` v2](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fstreaming\u002F#using-stream-events)\n- [FastAPI `StreamingResponse`](https:\u002F\u002Ffastapi.tiangolo.com\u002Fadvanced\u002Fcustom-response\u002F#streamingresponse)\n- [FastAPI WebSockets](https:\u002F\u002Ffastapi.tiangolo.com\u002Fadvanced\u002Fwebsockets\u002F)\n- [Cloud Run HTTP\u002F2 end-to-end](https:\u002F\u002Fcloud.google.com\u002Frun\u002Fdocs\u002Fconfiguring\u002Fhttp2)\n- [Nginx `proxy_buffering` directive](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_proxy_module.html#proxy_buffering)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P16, P19, P22, P46, P47, P48, P67)\n","# LangGraph Streaming (Python)\n\n## Overview\n\nAn engineer ships `stream_mode=\"values\"` to a token-level chat UI because it\n\"seemed the most complete.\" Every single token causes the full graph state —\nmessage history, scratchpad, plan — to be re-sent and re-rendered. At ~60\ntokens\u002Fsec the browser overdraws, the React reconciler can't keep up, the tab\nfreezes, and users blame the model. The correct answer was `stream_mode=\"messages\"`,\nwhich emits an `AIMessageChunk` delta per token (typically 5-50 bytes) — one\ntoken's worth of DOM work. This is pain-catalog entry **P19** and it is the #1\nLangGraph integration mistake in the 1.0 generation.\n\nThen the same UI ships to Cloud Run and hangs forever. No error. No logs. The\nserver is emitting tokens; they just never reach the browser. Default proxy\nbuffering (Nginx, Cloud Run's HTTP\u002F1.1 path, Cloudflare Free) holds the last\nchunk waiting for more bytes. This is **P46** — SSE streams from LangGraph\ndrop the final `end` event over proxies that buffer — and the fix is three\nheaders: `X-Accel-Buffering: no`, `Cache-Control: no-cache`, `Connection: keep-alive`.\n\nAnd then the debug view starts crashing browser tabs on long runs. The engineer\nforwarded `astream_events(version=\"v2\")` raw to the client because \"it has more\ndetail\" — but v2 emits thousands of events per invocation (per-token, per-node,\nper-runnable lifecycle), and a 60-second agent run easily hits 3,000 events.\nBrowsers freeze on the JSON deserialize queue. This is **P47** — filter\nserver-side, forward only `on_chat_model_stream` tokens (and optionally\n`on_tool_start` \u002F `on_tool_end`).\n\nThis skill ships the decision matrix, a production-grade FastAPI SSE endpoint\nwith the anti-buffering headers and a 15-second heartbeat, a server-side v2\nevent filter that drops ~90% of noise, and a WebSocket variant with\nreconnect-by-`thread_id` that resumes from the LangGraph checkpointer. Pin:\n`langgraph 1.0.x`, `langchain-core 1.0.x`. Pain-catalog anchors: **P19, P46,\nP47, P48, P67**, plus P16 for the `thread_id` rule and P22 for checkpointer\npersistence.\n\n## Prerequisites\n\n- Python 3.10+\n- `langgraph >= 1.0, \u003C 2.0`, `langchain-core >= 1.0, \u003C 2.0`\n- `fastapi >= 0.110`, `uvicorn[standard]` (for SSE\u002FWebSocket hosting)\n- A checkpointer: `langgraph.checkpoint.memory.MemorySaver` for dev, or\n  `langgraph.checkpoint.postgres.PostgresSaver` for prod\n- Access to deploy behind your actual proxy (Nginx \u002F Cloud Run \u002F Cloudflare) —\n  localhost does not reproduce the buffering class of bugs\n\n## Instructions\n\n### Step 1 — Pick the right `stream_mode` for your UI\n\nThe three modes emit fundamentally different payloads. Match the mode to the\nUI shape **before** writing any server code.\n\n| UI type | `stream_mode` | Payload each tick | Emit rate | Overdraw risk | Typical bandwidth per 5s run |\n|---|---|---|---|---|---|\n| Live-token chat | `\"messages\"` | `(AIMessageChunk, metadata)` delta | ~30-80 tokens\u002Fsec | Low | ~5-15 KB |\n| Per-node progress bar \u002F status line | `\"updates\"` | `{node_name: state_diff}` | 1 per node (~2-20 per run) | Low | ~1-5 KB |\n| Debug \u002F time-travel \u002F state replay | `\"values\"` | Entire graph state dict | 1 per node (~2-20 per run) | **High** (state size × steps) | ~20 KB to MBs |\n| Hybrid (progress + tokens) | `[\"updates\", \"messages\"]` | `(mode, payload)` interleaved | Sum of above | Depends on inner modes | Sum |\n| Non-browser observability | `astream_events(v2)` + filter | Filtered dicts | Depends on filter | Low (server-controlled) | Controlled |\n\nDecision tree:\n\n```\nDo you need LLM tokens rendered live in the UI?\n├── Yes → stream_mode=\"messages\"\n│         (add \"updates\" to the list if you also want per-node progress)\n└── No, I need per-step progress\n    ├── Full state for debug\u002Freplay? → stream_mode=\"values\"\n    └── Just what changed (most UIs)  → stream_mode=\"updates\"\n```\n\nFull payload samples and combined-mode examples are in\n[Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### Step 2 — Wire a minimal SSE endpoint\n\n```python\nimport asyncio, json\nfrom fastapi import FastAPI\nfrom fastapi.responses import StreamingResponse\nfrom langchain_core.messages import HumanMessage\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom app.graph import build_graph\n\napp = FastAPI()\ngraph = build_graph(checkpointer=MemorySaver())\n\n\ndef sse(event: str, data: dict) -> str:\n    return f\"event: {event}\\ndata: {json.dumps(data, default=str)}\\n\\n\"\n\n\nasync def stream_tokens(thread_id: str, user_input: str):\n    config = {\"configurable\": {\"thread_id\": thread_id}}\n    async for chunk, metadata in graph.astream(\n        {\"messages\": [HumanMessage(user_input)]},\n        config=config,\n        stream_mode=\"messages\",\n    ):\n        # chunk.content may be list[dict] on Claude tool-use turns (P02)\n        text = chunk.text if hasattr(chunk, \"text\") else (\n            chunk.content if isinstance(chunk.content, str) else None\n        )\n        if text:\n            yield sse(\"token\", {\"text\": text, \"node\": metadata.get(\"langgraph_node\")})\n    yield sse(\"done\", {\"thread_id\": thread_id})\n```\n\nAlways use `graph.astream(...)` (async). Never call `graph.stream(...)` (sync)\nfrom inside an async handler — it blocks the event loop and one slow request\nblocks every other connection (P48).\n\n### Step 3 — Set the anti-buffering headers\n\n```python\n@app.get(\"\u002Fstream\")\nasync def stream(thread_id: str, q: str):\n    return StreamingResponse(\n        stream_tokens(thread_id, q),\n        media_type=\"text\u002Fevent-stream\",\n        headers={\n            \"X-Accel-Buffering\": \"no\",    # Nginx \u002F Cloud Run \u002F Cloudflare\n            \"Cache-Control\": \"no-cache\",  # Block intermediate caches\n            \"Connection\": \"keep-alive\",   # Hold the TCP connection\n        },\n    )\n```\n\nThese three headers are non-negotiable in production. Without them, your\nstream works on localhost and hangs on Cloud Run. See [SSE Endpoint Template](references\u002Fsse-endpoint-template.md)\nfor the full template with a 15-second heartbeat (required to survive Cloud\nRun's 60s idle timeout and corporate-proxy timeouts) plus reverse-proxy\nsnippets for Nginx, Traefik, and Cloud Run.\n\n### Step 4 — Filter `astream_events(version=\"v2\")` server-side\n\nIf your UI needs richer events than `\"messages\"` provides — tool start\u002Fend,\nprogress markers, retrieval events — do **not** forward `astream_events`\nraw. A single 60-second agent run can emit 3,000+ events. Filter on the\nserver and forward only what the browser uses.\n\n```python\nFORWARD = {\"on_chat_model_stream\", \"on_tool_start\", \"on_tool_end\"}\n\nasync def filtered(graph, inputs, config):\n    async for event in graph.astream_events(inputs, config=config, version=\"v2\"):\n        kind = event[\"event\"]\n        if kind == \"on_chat_model_stream\":\n            chunk = event[\"data\"][\"chunk\"]\n            text = chunk.text if hasattr(chunk, \"text\") else None\n            if text:\n                yield {\"type\": \"token\", \"text\": text,\n                       \"node\": event[\"metadata\"].get(\"langgraph_node\")}\n        elif kind == \"on_tool_start\":\n            yield {\"type\": \"tool_start\", \"tool\": event[\"name\"]}\n        elif kind == \"on_tool_end\":\n            yield {\"type\": \"tool_end\", \"tool\": event[\"name\"]}\n        # Drop: on_chain_*, on_parser_*, on_prompt_*, on_retriever_* (P47)\n```\n\nNever use `astream_log()` in new code — soft-deprecated in 1.0 (P67), scheduled\nfor removal in 2.0. Use `astream_events(version=\"v2\")` instead. Full event\ntaxonomy and compression\u002Fbackpressure patterns in\n[Astream Events Filtering](references\u002Fastream-events-filtering.md).\n\n### Step 5 — WebSocket variant with reconnect\n\nUse WebSocket instead of SSE when the user may cancel, interrupt, or send\nfollow-up messages mid-stream. WebSocket also sidesteps Cloudflare Free's\ndefault response buffering.\n\n```python\nfrom fastapi import WebSocket, WebSocketDisconnect\n\n@app.websocket(\"\u002Fws\u002F{thread_id}\")\nasync def ws(websocket: WebSocket, thread_id: str):\n    await websocket.accept()\n    config = {\"configurable\": {\"thread_id\": thread_id}}  # P16 — always\n    try:\n        while True:\n            msg = json.loads(await websocket.receive_text())\n            if msg[\"type\"] == \"user_message\":\n                async for chunk, metadata in graph.astream(\n                    {\"messages\": [HumanMessage(msg[\"text\"])]},\n                    config=config,\n                    stream_mode=\"messages\",\n                ):\n                    text = chunk.text if hasattr(chunk, \"text\") else None\n                    if text:\n                        await websocket.send_json({\"type\": \"token\", \"text\": text})\n                await websocket.send_json({\"type\": \"done\"})\n    except WebSocketDisconnect:\n        pass  # Checkpointer persists state; reconnect with same thread_id resumes\n```\n\nBecause LangGraph checkpointers persist state per `thread_id`, a client that\nreconnects to `\u002Fws\u002F{same-thread-id}` automatically sees the prior conversation\nhistory on the next turn — no special \"resume\" handshake required for\nbetween-turn reconnects. For mid-stream reconnects and cancellation handling,\nsee [WebSocket & Reconnect](references\u002Fwebsocket-and-reconnect.md).\n\n### Step 6 — Run the proxy-readiness checklist before shipping\n\nA stream that works on `uvicorn --reload main:app` on your laptop will hang\nbehind Cloud Run. Before you ship, walk this checklist:\n\n- [ ] Deployed endpoint returns `Content-Type: text\u002Fevent-stream` (or `101 Switching Protocols` for WebSocket)\n- [ ] Deployed endpoint returns `X-Accel-Buffering: no` and `Cache-Control: no-cache`\n- [ ] `curl -N https:\u002F\u002Fyour.app\u002Fstream?...` shows tokens arriving incrementally — NOT all at once at the end\n- [ ] Cloud Run deployed with `--use-http2` (HTTP\u002F2 end-to-end flushes chunks reliably)\n- [ ] If behind Cloudflare: Free plan may buffer — test on Pro or use a paid page rule to disable response buffering (or switch to WebSocket)\n- [ ] 15-second heartbeat configured (`: heartbeat\\n\\n` SSE comment every 15s) so idle streams don't get killed by the 60s timeout\n- [ ] Long-idle load test: run a tool-using agent that waits 45s on an API call; stream should stay alive\n\nTest behind your actual proxy, not just localhost.\n\n## Output\n\n- `stream_mode` chosen deliberately from the decision matrix (`\"messages\"` for tokens, `\"updates\"` for progress, `\"values\"` for debug)\n- Minimal FastAPI SSE endpoint using `graph.astream(..., stream_mode=\"messages\")` in an async handler\n- Required anti-buffering headers (`X-Accel-Buffering`, `Cache-Control`, `Connection`) on the `StreamingResponse`\n- Server-side `astream_events(version=\"v2\")` filter that forwards only `on_chat_model_stream` + `on_tool_start` + `on_tool_end`\n- Optional WebSocket variant with `thread_id` required at the route and checkpointer-backed resume\n- Proxy-readiness checklist walked end-to-end before shipping past localhost\n\n## Error Handling\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Browser tab freezes on token stream | Shipped `stream_mode=\"values\"` to a token UI; full state on every tick (P19) | Switch to `stream_mode=\"messages\"` — emits per-token deltas only |\n| Per-node progress bar never advances | Shipped `stream_mode=\"messages\"` to a per-node UI; no node-boundary events (P19) | Switch to `stream_mode=\"updates\"` |\n| Stream works on localhost, hangs on Cloud Run | Proxy buffering holds last chunk (P46) | Add `X-Accel-Buffering: no`, `Cache-Control: no-cache` headers; deploy Cloud Run with `--use-http2` |\n| Stream closes after ~60s with no data | Idle-connection timeout on proxy | Send `: heartbeat\\n\\n` SSE comment every 15s |\n| Browser tab freezes on long `astream_events` run | Forwarded unfiltered v2 events; 3,000+ events per run (P47) | Filter server-side: forward only `on_chat_model_stream` + optional tool events |\n| `DeprecationWarning: astream_log is deprecated` | Using soft-deprecated API (P67) | Migrate to `astream_events(version=\"v2\")` |\n| Agent has amnesia on every WebSocket message | Missing `thread_id` in config (P16) | Require `thread_id` at route; assert in middleware |\n| `AttributeError: 'list' object has no attribute 'lower'` on chunk.content | Claude streams content blocks, not plain strings on tool-use turns (P02) | Use `chunk.text` (1.0+) or check `isinstance(chunk.content, str)` before calling string methods |\n| One slow request blocks all other WebSocket clients | Sync `graph.stream()` or `graph.invoke()` inside async handler (P48) | Always use `graph.astream()` \u002F `graph.ainvoke()` in async contexts |\n| Cloudflare Free plan buffers SSE | Free-tier response buffering | Upgrade plan with page rule to disable buffering, or switch endpoint to WebSocket |\n\n## Examples\n\n### Live-token chat UI (the default case)\n\n`stream_mode=\"messages\"` plus SSE plus the three anti-buffering headers. One\ntoken per SSE frame (~5-50 bytes each), 30-80 frames\u002Fsec during active model\ngeneration, heartbeat every 15s during tool waits. See\n[SSE Endpoint Template](references\u002Fsse-endpoint-template.md) for the complete\nFastAPI example including heartbeat, reverse-proxy config, and the client\n`EventSource` code.\n\n### Per-node progress bar for a multi-step agent\n\n`stream_mode=\"updates\"` yields one event per node (typically 2-20 per\ninvocation). Render as discrete status ticks: \"Planning...\" → \"Searching...\" →\n\"Summarizing...\" → \"Done.\" Payload is tiny (~100 bytes per tick). Combine with\n`\"messages\"` (`stream_mode=[\"updates\", \"messages\"]`) to show both progress\nticks and streaming tokens in the active node's pane. Full payload samples in\n[Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### Debug \u002F time-travel view with `\"values\"`\n\n`stream_mode=\"values\"` yields the entire graph state after each node. Useful\nfor state replay, test recording, observability pipelines — **not** for\nbrowser UIs where state size × steps × re-render quickly freezes the tab.\nPipe to a server-side log (or LangSmith), not to the browser. Example and\ncaveats in [Stream Mode Comparison](references\u002Fstream-mode-comparison.md).\n\n### WebSocket with reconnect-by-`thread_id`\n\nWhen users can cancel mid-stream or send follow-up messages before the\nprevious turn finishes. The `thread_id` is required at the route; the\ncheckpointer persists history; reconnecting with the same `thread_id`\nautomatically sees prior turns. Cancellation is implemented via\n`asyncio.Task.cancel()` on the active `astream` iteration. Worked example\nwith half-open connection detection in\n[WebSocket & Reconnect](references\u002Fwebsocket-and-reconnect.md).\n\n## Resources\n\n- [LangGraph streaming how-to](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Fstreaming\u002F)\n- [LangGraph streaming concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fstreaming\u002F)\n- [LangChain `astream_events` v2](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fstreaming\u002F#using-stream-events)\n- [FastAPI `StreamingResponse`](https:\u002F\u002Ffastapi.tiangolo.com\u002Fadvanced\u002Fcustom-response\u002F#streamingresponse)\n- [FastAPI WebSockets](https:\u002F\u002Ffastapi.tiangolo.com\u002Fadvanced\u002Fwebsockets\u002F)\n- [Cloud Run HTTP\u002F2 end-to-end](https:\u002F\u002Fcloud.google.com\u002Frun\u002Fdocs\u002Fconfiguring\u002Fhttp2)\n- [Nginx `proxy_buffering` directive](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_proxy_module.html#proxy_buffering)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P16, P19, P22, P46, P47, P48, P67)\n",{"name":5,"tags":24,"author":33,"license":15,"version":34,"description":35,"allowed-tools":36,"compatible-with":37},[25,26,27,28,29,30,31,32],"saas","langchain","langgraph","python","langchain-1.0","streaming","sse","websocket","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Pick the correct LangGraph 1.0 stream_mode (\"messages\" vs \"updates\" vs \"values\"),\nwire it into SSE or WebSocket without proxy-buffering gotchas, and filter\nastream_events(v2) server-side before forwarding to the browser. Use when\nbuilding a live-token chat UI, a per-node progress bar, a debug\u002Ftime-travel\nview, or diagnosing a LangGraph stream that hangs over a production proxy.\nTrigger with \"langgraph streaming\", \"stream_mode messages\", \"stream_mode updates\",\n\"stream_mode values\", \"langgraph SSE\", \"langgraph astream_events\", \"SSE hangs\nbehind nginx\", \"cloud run streaming\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-streaming",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-streaming",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-streaming",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-streaming","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-streaming\u002FSKILL.md",true,[],[62,69,76,83,90,98],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]