iq-stream-langchain 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ .venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # The containers scripts/servers.py started
15
+ scripts/.servers.json
16
+
17
+ # Editors and agents
18
+ .idea/
19
+ .vscode/
20
+ .DS_Store
21
+ .claude
22
+ .codex
23
+ .kiro
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neuron Core
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,481 @@
1
+ Metadata-Version: 2.5
2
+ Name: iq-stream-langchain
3
+ Version: 0.1.0
4
+ Summary: Publish a LangGraph or LangChain agent run to browsers through an IQ-Stream server
5
+ Project-URL: Repository, https://github.com/neuron-core/iq-stream-python
6
+ Project-URL: Source, https://github.com/neuron-core/iq-stream-python/tree/main/packages/iq-stream-langchain
7
+ Project-URL: Issues, https://github.com/neuron-core/iq-stream-python/issues
8
+ Author: Neuron Core
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ag-ui,agents,iq-stream,langchain,langgraph,server-sent-events,sse,streaming
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Internet :: WWW/HTTP
23
+ Classifier: Topic :: Software Development :: Libraries
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: iq-stream<0.2,>=0.1.0
27
+ Requires-Dist: langgraph<2,>=1.1
28
+ Provides-Extra: ag-ui
29
+ Requires-Dist: ag-ui-langgraph[fastapi]>=0.0.47; extra == 'ag-ui'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # iq-stream-langchain
33
+
34
+ Publishes a [LangGraph](https://github.com/langchain-ai/langgraph) run, or a LangChain agent made with `create_agent`, to an [IQ-Stream server](https://github.com/neuron-core/iq-stream), so that browsers read the answer over Server-Sent Events and a reloaded page picks it up where it is. It is a thin layer over [`iq-stream`](https://pypi.org/project/iq-stream/), which holds the connection to the server.
35
+
36
+ The adapter wraps the iterator of `graph.stream()` / `graph.astream()`, which carries everything the run emits (tokens, tool calls and results, node updates, custom events, sub-graphs, interrupts) in the order LangGraph itself gives them. It is not a callback handler and not middleware: nothing is patched, and a slow or broken publisher cannot delay or fail the run. Each frame is one LangGraph stream part as JSON, the format LangGraph Server sends; AG-UI events are a second format, relayed from [`ag-ui-langgraph`](https://pypi.org/project/ag-ui-langgraph/).
37
+
38
+ ```sh
39
+ pip install iq-stream-langchain
40
+ pip install "iq-stream-langchain[ag-ui]" # the AG-UI format, through ag-ui-langgraph and FastAPI
41
+ ```
42
+
43
+ ## Publish a run
44
+
45
+ `agent` is a `create_agent` agent or any compiled graph. The publisher's `with` block closes the stream; `publish_run` relays the run to its end and returns the final state, which you save inside the block, before the close.
46
+
47
+ ```python
48
+ from langchain.agents import create_agent
49
+ from langgraph.checkpoint.memory import InMemorySaver
50
+
51
+ from iq_stream import IQClient
52
+ from iq_stream_langchain import publish_run
53
+
54
+ iq = IQClient() # IQ_STREAM_URL, IQ_STREAM_APP_KEY, IQ_STREAM_APP_SECRET
55
+ agent = create_agent(model, [get_weather], checkpointer=InMemorySaver())
56
+
57
+ ticket = iq.ticket() # hand ticket.to_dict() to the browser
58
+ config = {"configurable": {"thread_id": "thread-1"}}
59
+ question = {"messages": [{"role": "user", "content": "What is the weather in Turin?"}]}
60
+ with iq.publisher(ticket.stream_id) as publisher: # the request to the server opens now
61
+ final = publish_run(publisher, agent, question, config)
62
+ save_answer(final["messages"]) # before the close: a late browser loads it from you
63
+ # the block closes the stream with "end", or with "fail" if the run raised
64
+ ```
65
+
66
+ `model` and `get_weather` stand for your chat model and tools, `save_answer()` for your own persistence. With a checkpointer, the thread is saved when the stream of parts ends, so the close line already follows it.
67
+
68
+ Code that already iterates the stream changes one line: `relay()` yields every part `graph.stream(..., subgraphs=True, version="v2")` yields, and publishes each one on the way.
69
+
70
+ ```python
71
+ from iq_stream import IQClient
72
+ from iq_stream_langchain import relay
73
+
74
+ iq = IQClient()
75
+ ticket = iq.ticket()
76
+ with iq.publisher(ticket.stream_id) as publisher:
77
+ for part in relay(publisher, agent, question, config):
78
+ if part["type"] == "messages" and part["data"][0].type == "AIMessageChunk":
79
+ print(part["data"][0].content, end="")
80
+ ```
81
+
82
+ ### In a FastAPI app
83
+
84
+ `arelay()` and `apublish_run()` are the same over `graph.astream()`. The route answers with the ticket at once; the run is published while the page reads it. The same route answers an interrupt, as a new run on a new stream. Three more routes give a reloaded page the run in flight, cancel a run, and load a thread whose stream is over. (Check in each route that the thread is the user's, as your app does for its other data.)
85
+
86
+ ```python
87
+ import asyncio
88
+ from dataclasses import dataclass
89
+ from typing import Any
90
+
91
+ from fastapi import FastAPI, HTTPException, Response
92
+ from langgraph.types import Command
93
+ from pydantic import BaseModel
94
+
95
+ from iq_stream import AsyncPublisher, IQClient
96
+ from iq_stream_langchain import apublish_run
97
+
98
+ app = FastAPI()
99
+ iq = IQClient()
100
+
101
+
102
+ @dataclass
103
+ class Run:
104
+ stream_id: str
105
+ task: asyncio.Task[None]
106
+
107
+
108
+ running: dict[str, Run] = {} # thread id -> the run in flight
109
+
110
+
111
+ class ChatIn(BaseModel):
112
+ thread_id: str
113
+ message: str | None = None # a question, or
114
+ resume: Any = None # the answer to the interrupt the thread waits on
115
+
116
+
117
+ class StopIn(BaseModel):
118
+ token: str # the ticket's: it proves the caller holds the stream
119
+
120
+
121
+ @app.post("/chat")
122
+ async def chat(body: ChatIn) -> dict[str, str | int]:
123
+ ticket = iq.ticket()
124
+ publisher = iq.apublisher(ticket.stream_id) # the request to the IQ server opens now
125
+ run = running[body.thread_id] = Run(ticket.stream_id, asyncio.create_task(run_agent(publisher, body)))
126
+
127
+ def finished(_: asyncio.Task[None]) -> None:
128
+ if running.get(body.thread_id) is run: # not a newer run of the thread
129
+ del running[body.thread_id]
130
+
131
+ run.task.add_done_callback(finished)
132
+ return ticket.to_dict() # streamId, token, url, expiresAt
133
+
134
+
135
+ @app.get("/chat/{thread_id}/stream")
136
+ async def in_flight(thread_id: str) -> Any:
137
+ """A reloaded page's ticket for the run in flight: the server replays its stream from the first frame."""
138
+ run = running.get(thread_id)
139
+ return iq.ticket(run.stream_id).to_dict() if run else Response(status_code=204)
140
+
141
+
142
+ @app.post("/chat/{stream_id}/stop", status_code=204)
143
+ async def stop(stream_id: str, body: StopIn) -> None:
144
+ if not iq.verify("sub", body.token, stream_id):
145
+ raise HTTPException(403, "Not your stream.")
146
+ for run in list(running.values()):
147
+ if run.stream_id == stream_id:
148
+ run.task.cancel() # the page gets the Cancelled part, then iq:fail
149
+
150
+
151
+ @app.get("/chat/{thread_id}")
152
+ async def history(thread_id: str) -> list[dict[str, str]]:
153
+ """What a page loads after iq:gone: the thread as the checkpointer saved it."""
154
+ state = await agent.aget_state({"configurable": {"thread_id": thread_id}})
155
+ return [{"type": message.type, "content": message.text} for message in state.values.get("messages", [])]
156
+
157
+
158
+ async def run_agent(publisher: AsyncPublisher, body: ChatIn) -> None:
159
+ config = {"configurable": {"thread_id": body.thread_id}}
160
+ if body.resume is not None:
161
+ graph_input: Any = Command(resume=body.resume)
162
+ else:
163
+ graph_input = {"messages": [{"role": "user", "content": body.message}]}
164
+ async with publisher: # "end"; "fail" on an exception or a cancellation
165
+ await apublish_run(publisher, agent, graph_input, config)
166
+ ```
167
+
168
+ A graph whose async nodes block the event loop (a synchronous SDK called in an `async def` node) starves an `AsyncPublisher`'s keepalive. Give such a run a synchronous `Publisher`, whose keepalive has a thread of its own, and close it from a thread too: its `close()` waits for the server, which would stall every other task of the app.
169
+
170
+ ```python
171
+ import asyncio
172
+
173
+ from iq_stream import IQClient
174
+ from iq_stream_langchain import apublish_run
175
+
176
+ iq = IQClient()
177
+
178
+
179
+ async def answer(question: dict[str, list[dict[str, str]]]) -> None:
180
+ ticket = iq.ticket()
181
+ publisher = iq.publisher(ticket.stream_id)
182
+ try:
183
+ final = await apublish_run(publisher, agent, question, config)
184
+ save_answer(final["messages"])
185
+ except BaseException:
186
+ await asyncio.to_thread(publisher.close, "fail")
187
+ raise
188
+ await asyncio.to_thread(publisher.close, "end")
189
+
190
+
191
+ asyncio.run(answer(question))
192
+ ```
193
+
194
+ Async code that leaves a loop over `arelay()` early wraps it in `contextlib.aclosing()`, so that the stream is closed as a cancelled run at once. Without it Python finalizes the generator later, after the block has closed the stream with `end`.
195
+
196
+ ```python
197
+ import asyncio
198
+ import contextlib
199
+
200
+ from iq_stream import IQClient
201
+ from iq_stream_langchain import arelay
202
+
203
+ iq = IQClient()
204
+
205
+
206
+ async def first_words(question: dict[str, list[dict[str, str]]]) -> str:
207
+ ticket = iq.ticket()
208
+ text = ""
209
+ async with iq.apublisher(ticket.stream_id) as publisher:
210
+ async with contextlib.aclosing(arelay(publisher, agent, question, config)) as parts:
211
+ async for part in parts:
212
+ if part["type"] == "messages":
213
+ text += part["data"][0].text
214
+ if len(text) > 10:
215
+ break # the Cancelled part, then the close line "fail"
216
+ return text
217
+
218
+
219
+ print(asyncio.run(first_words(question)))
220
+ ```
221
+
222
+ ## What goes over the wire
223
+
224
+ One frame per stream part, without an SSE event name, its data a JSON object: `{"type": <mode>, "ns": [...], "data": ...}`, with messages and other pydantic objects as `model_dump()` gives them, as LangGraph Server sends them. `ns` is empty for the root graph and names the sub-graph otherwise. Three parts are the adapter's own:
225
+
226
+ | Part | When |
227
+ | --- | --- |
228
+ | `{"type": "metadata", "ns": [], "data": {"run_id", "thread_id"}}` | First, before the graph starts, from the config. |
229
+ | `{"type": "error", "ns": [], "data": {"error": "<exception type>", "message": "An error occurred."}}` | The run raised. The message is the exception's only with `expose_errors=True`. |
230
+ | `{"type": "error", "ns": [], "data": {"error": "Cancelled", "message": "run cancelled"}}` | The run was cancelled. |
231
+
232
+ By default the modes are `messages`, `updates`, `custom` and `tools` (`DEFAULT_STREAM_MODE`). `values` is left out because each part repeats the whole state, which grows with the thread. A `messages` part keeps the metadata keys the browser clients read (`SLIM_METADATA`), about 430 bytes a token instead of 730.
233
+
234
+ ## In the browser
235
+
236
+ The frames are LangGraph's own parts, so the page converts them with LangGraph's and the AI SDK's own code. `@neuron-core/iq-stream` has no bridge for this format yet; these functions are the whole of it, on top of its `frames()` and `chatTransport`:
237
+
238
+ ```js
239
+ import { frames } from '@neuron-core/iq-stream/client';
240
+ import { toUIMessageStream } from '@ai-sdk/langchain';
241
+
242
+ /** The frames of a stream, as the LangGraph parts iq-stream-langchain published: { type, ns, data }. */
243
+ export const langGraphParts = (url, options = {}) => frames(url, { ...options, parse: JSON.parse });
244
+
245
+ /** For `useStream({ transport })` of @langchain/langgraph-sdk/react: each part as LangGraph Server names it. */
246
+ export async function* useStreamEvents(parts) {
247
+ for await (const part of parts) {
248
+ const suffix = part.ns.length ? `|${part.ns.join('|')}` : '';
249
+ yield { event: part.type + suffix, data: part.data };
250
+ // The hook reads interrupts from `values`, which the adapter does not publish by default.
251
+ if (part.type === 'updates' && part.data?.__interrupt__) {
252
+ yield { event: `values${suffix}`, data: { __interrupt__: part.data.__interrupt__ } };
253
+ }
254
+ if (part.type === 'error') return; // the run said how it ended: the iq:fail after it adds nothing
255
+ }
256
+ }
257
+
258
+ /** For `chatTransport({ open })` of @neuron-core/iq-stream/ai-sdk: UI message chunks, converted in the page. */
259
+ export function uiMessageChunks(url, options = {}) {
260
+ let cancelled = false;
261
+ let lost; // the subscription failed without the run saying why: iq:gone, publisher_idle, a refusal
262
+ async function* tuples() {
263
+ try {
264
+ for await (const part of langGraphParts(url, options)) {
265
+ if (part.type === 'metadata') continue;
266
+ if (part.type === 'error') {
267
+ cancelled = part.data.error === 'Cancelled';
268
+ throw new Error(part.data.message);
269
+ }
270
+ yield part.ns.length ? [part.ns, part.type, part.data] : [part.type, part.data];
271
+ // @ai-sdk/langchain, too, reads a human-in-the-loop interrupt from `values` only.
272
+ if (part.type === 'updates' && part.data?.__interrupt__) {
273
+ const values = { __interrupt__: part.data.__interrupt__ };
274
+ yield part.ns.length ? [part.ns, 'values', values] : ['values', values];
275
+ }
276
+ }
277
+ } catch (error) {
278
+ if (error?.name === 'IQStreamError') lost = error;
279
+ throw error;
280
+ }
281
+ }
282
+ return toUIMessageStream(tuples()).pipeThrough(
283
+ new TransformStream({
284
+ transform(chunk, controller) {
285
+ if (chunk.type === 'error' && lost) return;
286
+ // A cancelled run is the AI SDK's `abort` chunk, which tells useChat it was stopped, not failed.
287
+ controller.enqueue(chunk.type === 'error' && cancelled ? { type: 'abort' } : chunk);
288
+ },
289
+ flush(controller) {
290
+ if (lost) controller.error(lost); // chatTransport reports it, as for any stream that failed
291
+ },
292
+ }),
293
+ );
294
+ }
295
+ ```
296
+
297
+ With the AI SDK's `useChat` (`npm install @neuron-core/iq-stream ai @ai-sdk/react @ai-sdk/langchain`), against the routes above:
298
+
299
+ ```ts
300
+ import { useChat } from '@ai-sdk/react';
301
+ import { chatTransport } from '@neuron-core/iq-stream/ai-sdk';
302
+
303
+ const transport = chatTransport({
304
+ start: async ({ chatId, messages }) => {
305
+ const message = messages.at(-1)?.parts.find((part) => part.type === 'text')?.text ?? '';
306
+ const response = await fetch('/chat', {
307
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
308
+ body: JSON.stringify({ thread_id: chatId, message }),
309
+ });
310
+ return response.json(); // the ticket
311
+ },
312
+ resume: async ({ chatId }) => { // the run in flight, after a reload
313
+ const response = await fetch(`/chat/${chatId}/stream`);
314
+ return response.status === 204 ? null : response.json();
315
+ },
316
+ stop: (ticket) => void fetch(`/chat/${ticket.streamId}/stop`, {
317
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
318
+ body: JSON.stringify({ token: ticket.token }),
319
+ }),
320
+ open: (ticket, signal) => uiMessageChunks(ticket.url, { signal }),
321
+ });
322
+
323
+ const { messages, sendMessage, stop, status } = useChat({ id: threadId, transport, resume: true });
324
+ // A tool call is a part of type 'dynamic-tool', with toolName, input, output and state; one that waits for a
325
+ // human's approval (HumanInTheLoopMiddleware) is in the state 'approval-requested'.
326
+ ```
327
+
328
+ `resume: true` is what makes a reloaded page continue the answer: the server replays the stream from its first frame, and `chatTransport` tells `useChat` it is a replay.
329
+
330
+ With LangGraph's `useStream` (`npm install @neuron-core/iq-stream @langchain/langgraph-sdk`):
331
+
332
+ ```ts
333
+ import { useStream } from '@langchain/langgraph-sdk/react';
334
+
335
+ // stream() gets the input of thread.submit(input), or the command of thread.submit(undefined, { command }).
336
+ const transport = {
337
+ async stream({ input, command, config, signal }) {
338
+ const response = await fetch('/chat', {
339
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
340
+ body: JSON.stringify({
341
+ thread_id: config.configurable.thread_id,
342
+ message: input?.messages?.at(-1)?.content,
343
+ resume: command?.resume,
344
+ }),
345
+ signal,
346
+ });
347
+ const ticket = await response.json();
348
+ return useStreamEvents(langGraphParts(ticket.url, { signal }));
349
+ },
350
+ };
351
+
352
+ const thread = useStream({ threadId, messagesKey: 'messages', transport });
353
+ // A run that waits for a human: thread.interrupt holds what it asks, and
354
+ // thread.submit(undefined, { command: { resume: answer } }) answers it.
355
+ ```
356
+
357
+ A failed run reaches `useStream` as a `StreamError` named after the exception type, and a cancelled one as one named `Cancelled`; `useChat` gets an `error` chunk or an `abort` chunk. When a subscription ends with `iq:gone` (the stream is over and frames this tab missed are gone), load the thread from your backend, as the `/chat/{thread_id}` route above offers. The functions above and the transports ran in Node against what a real subscriber received, through `StreamManager` (the engine of `useStream`, driven as the hook drives it, a resume included), `AbstractChat` (the class behind `useChat`) and `@ai-sdk/langchain` 3.0.172; the React hooks themselves were not run.
358
+
359
+ ## AG-UI
360
+
361
+ For a front end that speaks [AG-UI](https://docs.ag-ui.com) (CopilotKit, or `StreamAgent` of `@neuron-core/iq-stream/ag-ui`), relay the events of `ag_ui_langgraph.LangGraphAgent`. It owns the run: it needs a checkpointer and calls the graph itself. The run's `RUN_FINISHED` tells the page the answer is complete, so the relay publishes it only after `before_close` has saved the answer.
362
+
363
+ ```python
364
+ import asyncio
365
+
366
+ from ag_ui.core import RunAgentInput, RunFinishedEvent
367
+ from ag_ui_langgraph import LangGraphAgent
368
+ from fastapi import FastAPI
369
+
370
+ from iq_stream import AsyncPublisher, IQClient
371
+ from iq_stream_langchain.agui import arelay_agui
372
+
373
+ app = FastAPI()
374
+ iq = IQClient()
375
+ agui_agent = LangGraphAgent(name="weather", graph=agent, emit_raw_events=False)
376
+ running: set[asyncio.Task[None]] = set()
377
+
378
+
379
+ @app.post("/agent")
380
+ async def start(run_input: RunAgentInput) -> dict[str, str | int]:
381
+ ticket = iq.ticket()
382
+ task = asyncio.create_task(run(iq.apublisher(ticket.stream_id), run_input))
383
+ running.add(task)
384
+ task.add_done_callback(running.discard)
385
+ return ticket.to_dict()
386
+
387
+
388
+ async def run(publisher: AsyncPublisher, run_input: RunAgentInput) -> None:
389
+ async def save(finished: RunFinishedEvent) -> None:
390
+ state = await agent.aget_state({"configurable": {"thread_id": finished.thread_id}})
391
+ save_answer(state.values["messages"]) # before RUN_FINISHED: a late browser loads it from you
392
+
393
+ async with publisher:
394
+ async for _ in arelay_agui(publisher, agui_agent, run_input, before_close=save):
395
+ pass
396
+ ```
397
+
398
+ `arelay_agui` clones the agent for each run, as `ag_ui_langgraph`'s own endpoint does (`LangGraphAgent` keeps the state of a run on itself), so one agent serves concurrent requests. Each event is one frame, its JSON as the AG-UI encoder writes it (camelCase), published before it is yielded, except `RUN_FINISHED`: that is yielded when it comes and published once the run's events are over and `before_close(event)` has returned (awaited when it is a coroutine). If `before_close` raises, the page gets a `RUN_ERROR` instead, the stream closes with `fail` and the exception goes on; `StreamAgent` takes `RUN_FINISHED` as the end of the run, and would not report an `iq:fail` that came after it. `ag_ui_langgraph` reports a failed run as a `RUN_ERROR` event instead of raising, so the relay closes the stream with `fail` as soon as it has sent one; its message is replaced by `An error occurred.` unless `expose_errors=True`. A cancelled run ends with `RUN_FINISHED` and the `cancelled` outcome, after the events that close what the client holds open (a message, a tool call, a step, a sub-agent), which AG-UI clients require of a finished run; a loop left at `RUN_FINISHED`, before the save, is a cancelled run too. In the page, `new StreamAgent({ threadId, start: async (input) => (await fetch('/agent', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) })).json() })` reads these frames as they are.
399
+
400
+ Construct the agent with `emit_raw_events=False`: raw events multiply the size of a stream (69 events and 60 kB against 32 events and 4 kB for one run with a tool call).
401
+
402
+ ## Reference
403
+
404
+ ### `relay(publisher, graph, input, config=None, **options)` and `arelay(...)`
405
+
406
+ Run `graph.stream(input, config, subgraphs=True, version="v2")` (`astream` for `arelay`), publish each part whose mode is in `stream_mode` as one frame, and yield every part unchanged. `relay` takes a synchronous `Publisher`; `arelay` takes an `AsyncPublisher`, or a `Publisher` for graphs whose nodes block the loop and would starve the asynchronous publisher's keepalive. Both return generators: `close()` / `aclose()` cancel the run.
407
+
408
+ ### `publish_run(publisher, graph, input, config=None, **options)` and `apublish_run(...)`
409
+
410
+ Relay the run to its end and return the final state of the root graph, its last `values`, which are requested from the graph and not published. A run that waits for a human has its interrupts under `__interrupt__`, as `invoke()` returns them.
411
+
412
+ | Option | Default | |
413
+ | --- | --- | --- |
414
+ | `stream_mode` | `DEFAULT_STREAM_MODE` | The modes requested and published: `messages`, `updates`, `custom`, `tools`, and `values`, `tasks`, `checkpoints`, `debug` if you add them. |
415
+ | `also_yield` | `()` | Modes requested from the graph and yielded, not published. |
416
+ | `metadata` | `"slim"` | The metadata of a `messages` part: `"slim"` (the keys the browser clients read), `"full"`, or a list of keys. |
417
+ | `expose_errors` | `False` | Publish the message of a failed run's exception, of a `tool-error` part and of a failed tool's result (a `ToolMessage` with `status="error"`, whose content is the error's text). Otherwise the browser reads `An error occurred.`. |
418
+ | `close_on_cancel` | `"fail"` | The close line of a cancelled run, or `"end"` for an application that treats a stopped answer as final. |
419
+ | `on_oversize` | `None` | Called with an `Oversize` (`part_type`, `size`, `limit`, `truncated`) for every part over the frame limit. Without it, the first one of a run is logged as a warning on the `iq_stream_langchain` logger. A hook that raises is logged once and never fails the run. |
420
+ | `**stream_kwargs` | | Passed to `graph.stream()`: `context`, `durability`, `interrupt_before`, `control`, ... |
421
+
422
+ `encode_part(part, metadata="slim", expose_errors=False)` and `error_part(error, expose=False)` return the frame data the relay would send, for code of your own. `arelay_agui(publisher, agent, run_input, close_on_cancel="fail", expose_errors=False, on_oversize=None, before_close=None)` in `iq_stream_langchain.agui` is the AG-UI relay.
423
+
424
+ ### Which close line
425
+
426
+ | The run | Last frame | Close line |
427
+ | --- | --- | --- |
428
+ | finishes | the run's last part | `end`, from the `with` block, after your save |
429
+ | pauses on `interrupt()` | `updates` with `__interrupt__` | `end`: the answer waits for a human and resumes as a new run (`Command(resume=...)`) on a new stream |
430
+ | raises | `error` part with the exception's type | `fail`, from the `with` block; the exception goes on to your code |
431
+ | is cancelled: a cancelled task, `KeyboardInterrupt`, a drain request (`RunControl.request_drain()`) | `error` part named `Cancelled`, at once | `fail`, sent by the relay at once; with `close_on_cancel="end"`, `end`, sent by the relay once the graph has stopped |
432
+ | is left early: a `break`, `close()` / `aclose()` of the relay | `error` part named `Cancelled`, at once | `fail`, sent by the relay; with `close_on_cancel="end"`, `end` from the `with` block |
433
+
434
+ Except for a cancelled run with `close_on_cancel="end"`, the adapter never closes a stream with `end` itself: the `with` block does, so that what a late browser loads from you is saved before any browser is told the answer is complete.
435
+
436
+ "At once" means before LangGraph has stopped the run: `arelay()` reads the graph's stream in a task of its own, so a cancel lands in the relay, which publishes it, and not inside LangGraph, which lets a cancel through only once its running nodes have stopped (a tool may finish its work first).
437
+
438
+ A generator cannot tell a `break` from an exception raised by your own code inside the loop: the page reads the `Cancelled` part for both. The close line is still `fail` after an exception, from the relay or, with `close_on_cancel="end"`, from your block. Catch your own errors inside the loop, or use `publish_run()`, when the page must tell them apart. A cancel of the task that lands in your loop body (while it awaits a send or a save) is told apart on Python 3.11 and later, and closes with `close_on_cancel`; on 3.10 it is handled as a `break`.
439
+
440
+ ### Errors and limits
441
+
442
+ Publishing never breaks the run. A publisher that gives up (the server is unreachable, it closed the stream) goes inert, the relay stops encoding parts and goes on reading the run, so that the run and its persistence complete. With the core's `on_error="raise"`, the publishing error leaves the relay like any exception of the run. A part that cannot be encoded is dropped and logged once. Dates and times are ISO 8601 strings, a `timedelta` its seconds, UUIDs, decimals and paths strings, an `Enum` its value, NaN and infinities `null` (a browser's `JSON.parse` refuses the bare constants); any other value JSON cannot hold is encoded by its `repr`, never lost.
443
+
444
+ A part over the publisher's `max_frame_bytes` (64 KiB unless the app has a limit of its own): a `messages` part with text content, a large tool result usually, is sent with its content cut to fit, ending in `…[truncated]` and with `"truncated": true` in its metadata. An `updates` part that carries an interrupt is the only one that tells the page the run waits for a human, so it is never dropped: it is sent with each interrupt's `id`, its `value` with every long string cut to fit (keys, names and ids whole, so that `HumanInTheLoopMiddleware`'s `action_requests` still name the tool to approve), and `"truncated": true`; a value whose structure alone does not fit is `null`. The whole value stays in the thread's state. Any other part (`updates`, `values`, a `tool-finished` event) is not sent: the result reaches the page in the `messages` part, and the whole of it is in the state your code saves.
445
+
446
+ On the AG-UI path, a text or arguments delta is sent as several deltas of the same id, a tool result is cut, and a snapshot is not sent. The interrupt (`ag_ui_langgraph`'s `on_interrupt` event, or the interrupt outcome of `RUN_FINISHED`) is cut as above; `RUN_FINISHED` and `RUN_ERROR` are never dropped: `RUN_FINISHED` goes without its outcome if even the interrupts' ids do not fit, and an error message exposed with `expose_errors=True` that does not fit goes masked, as on the native path.
447
+
448
+ ## Limits worth knowing
449
+
450
+ - A stream is one run. A frame is at most 65,536 bytes and a stream at most 10 MiB and one hour, unless the app has limits of its own on the server. The server counts each frame at more than its size (its text as subscribers receive it, rounded up, plus 32 bytes), so a 430-byte token frame costs about 540 bytes: some 19,000 of them fit. When the server closes a stream, the relay stops publishing and the run goes on.
451
+ - On Python 3.10, an async run of an agent whose nodes call the model without passing their config, as `create_agent`'s do, streams whole messages instead of tokens: LangChain can hand the run's callbacks to such a call only from Python 3.11, whose `asyncio.create_task` takes a context. Synchronous runs stream tokens on every version; so does async code that passes `config` to the model. For the same reason an async run of `HumanInTheLoopMiddleware` (or any `interrupt()` called without the config at hand) fails on 3.10 in LangGraph itself, with "Called get_config outside of a runnable context".
452
+ - `useStream` ignores the `tools` parts (its tool events are the JavaScript runtime's), and so does `@ai-sdk/langchain`: tool calls and results still render from `messages`. Server features of `useStream` (history, branching, `joinStream`) need LangGraph Server.
453
+ - Graphs served by LangGraph Server or LangGraph Platform are not covered: those stream themselves. An application that only calls `invoke()` has nothing to publish: switch to `stream()` or `publish_run()`.
454
+ - `ag-ui-langgraph` 0.0.47 drops the arguments carried by the chunk that opens a tool call; providers that send a tool call's name and id first, with empty arguments, are not affected. Its `TOOL_CALL_RESULT` does not say that a tool failed, so a failed tool's error text goes out in it as the tool wrote it; the snapshots mask it.
455
+ - `iq_stream_langchain.experimental.iq_transformer(publisher, methods=...)` publishes the events of `stream_events(version="v3")`, which LangGraph marks as beta, while your code reads `run.output`. No browser client reads those events without LangGraph Server. A run your code stops early (a loop over a projection left, `run.abort()`, a cancelled task) looks to a transformer like one that finished, or is not reported to it at all: send the `Cancelled` part and the close line yourself.
456
+
457
+ ```python
458
+ from iq_stream import IQClient
459
+ from iq_stream_langchain import CANCELLED_PART
460
+ from iq_stream_langchain.experimental import iq_transformer
461
+
462
+ iq = IQClient()
463
+ ticket = iq.ticket()
464
+ with iq.publisher(ticket.stream_id) as publisher:
465
+ with agent.stream_events(question, config, version="v3", transformers=[iq_transformer(publisher)]) as run:
466
+ for count, message in enumerate(run.messages):
467
+ if count == 1: # your own reason to stop
468
+ publisher.send(CANCELLED_PART)
469
+ publisher.close("fail")
470
+ break
471
+ ```
472
+
473
+ ## Requirements
474
+
475
+ - Python 3.10 to 3.13, `iq-stream` 0.1, `langgraph` 1.1 or a later 1.x (the `tools` parts and drain requests need 1.2, the experimental module 1.2). For the `ag-ui` extra, `ag-ui-langgraph` 0.0.47 or later with FastAPI.
476
+ - Tested with `langgraph` 1.2.21, `langgraph-prebuilt` 1.1.1, `langchain` 1.5.0, `langchain-core` 1.8.0 and `ag-ui-langgraph` 0.0.47 (on Python 3.10: `langchain` 1.4.10 and `langchain-core` 1.7.7, the last releases that support it), and at the floor, on Python 3.10, with `langgraph` 1.1.0, `langgraph-prebuilt` 1.0.8 (the only release of the range `langgraph` 1.1.0 asks for that imports with it), `langchain` 1.2.11 (the first that takes `langgraph` 1.1) and `ag-ui-langgraph` 0.0.47.
477
+ - An IQ-Stream server 1.x.
478
+
479
+ ## License
480
+
481
+ MIT