iq-stream-llamaindex 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,283 @@
1
+ Metadata-Version: 2.5
2
+ Name: iq-stream-llamaindex
3
+ Version: 0.1.0
4
+ Summary: Publish LlamaIndex workflow and agent runs 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-llamaindex
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,llama-index,llamaindex,server-sent-events,sse,streaming,workflows
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: llama-index-workflows<3,>=2.14
28
+ Provides-Extra: ag-ui
29
+ Requires-Dist: ag-ui-protocol<2,>=1.0; extra == 'ag-ui'
30
+ Provides-Extra: agents
31
+ Requires-Dist: llama-index-core<0.15,>=0.14; extra == 'agents'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # iq-stream-llamaindex
35
+
36
+ Publish LlamaIndex runs to browsers through an [IQ-Stream server](https://github.com/neuron-core/iq-stream): a `FunctionAgent`, a `ReActAgent`, a multi-agent `AgentWorkflow`, or any `Workflow`. Your backend starts the run and hands the browser a ticket; the run's events reach the browser as Server-Sent Events while they happen, as [AG-UI](https://docs.ag-ui.com) events or as LlamaIndex's own, and the stream ends with `end` once the answer is saved, or with `fail`.
37
+
38
+ It is one coroutine, `publish(handler, publisher)`, over the handler that `run()` returns and a publisher of the core client [`iq-stream`](https://pypi.org/project/iq-stream/). It reads `handler.stream_events()`, the interface LlamaIndex documents as stable, and it is that stream's only reader: LlamaIndex allows one. `published()` does the same and hands each event on to your code.
39
+
40
+ ```sh
41
+ pip install iq-stream-llamaindex # any workflow, LlamaIndex's own events (NativeEncoder)
42
+ pip install "iq-stream-llamaindex[agents]" # adds llama-index-core: FunctionAgent, ReActAgent, AgentWorkflow
43
+ pip install "iq-stream-llamaindex[ag-ui]" # adds ag-ui-protocol: AG-UI events (AGUIEncoder)
44
+ ```
45
+
46
+ ## Publish a run
47
+
48
+ ```python
49
+ import asyncio
50
+
51
+ from iq_stream import IQClient
52
+
53
+ from iq_stream_llamaindex import AGUIEncoder, RunOutcome, publish
54
+
55
+ iq = IQClient() # IQ_STREAM_URL, IQ_STREAM_APP_KEY and IQ_STREAM_APP_SECRET
56
+
57
+
58
+ async def save_answer(outcome: RunOutcome) -> None:
59
+ print("saving", outcome.status, outcome.result) # your database: called before the close line
60
+
61
+
62
+ async def main() -> None:
63
+ ticket = iq.ticket() # hand ticket.to_dict() to the browser
64
+ handler = agent.run(user_msg="What is the weather in Paris?", run_id=ticket.stream_id)
65
+ outcome = await publish(
66
+ handler,
67
+ iq.apublisher(ticket.stream_id), # its one request to the server opens now
68
+ encoder=AGUIEncoder(thread_id="thread-1"),
69
+ before_close=save_answer,
70
+ )
71
+ print(outcome.status, outcome.frames, outcome.publish_result)
72
+
73
+
74
+ asyncio.run(main())
75
+ ```
76
+
77
+ `agent` stands for your agent or workflow. Passing the stream id as `run_id` puts it in LlamaIndex's logs and instrumentation tags (agents take it from llama-index-core 0.14.16 on; earlier releases ignore it). LlamaIndex has no synchronous API: `run()` needs a running event loop, so a queue worker wraps the run in `asyncio.run()` as above.
78
+
79
+ What `publish()` does:
80
+
81
+ - **It publishes while the run runs.** Each event becomes frames on the publisher as it is read: a text delta is a frame, a tool call is its frames, all on the one request the core client holds open. The one exception is an agent's last `AgentOutput`, which waits for llama-index-core to finalize it (below), a quarter of a second at most. Keepalives cover a tool that takes minutes, or a run waiting for a human.
82
+ - **It saves before it closes.** When the run ends, `publish()` awaits its result, calls `before_close(outcome)`, and only then sends the terminal frames (`RUN_FINISHED`, `RUN_ERROR`) and the close line. A browser that arrives after the close receives `iq:gone` and loads the answer from you, so it must be there.
83
+ - **It returns how the run ended.** A failed run is returned, not raised: `publish()` usually runs in a task of its own, where an exception would only be logged. `raise_run_errors=True` raises it after the close.
84
+ - **Publishing never breaks the run.** A publisher that gives up (the server refused, the stream grew too large) stops the encoding; the run is still read to its end, `before_close` still runs, and `outcome.published` is `False`.
85
+ - **It never hangs.** A run killed with the deprecated `handler.cancel()` publishes no terminal event; `publish()` notices that the run is done and ends the stream a second later.
86
+
87
+ ## In a FastAPI app
88
+
89
+ The route starts the run, answers with the ticket at once, and leaves the run and its stream to a task:
90
+
91
+ ```python
92
+ import asyncio
93
+
94
+ from fastapi import FastAPI
95
+ from iq_stream import IQClient
96
+ from pydantic import BaseModel
97
+
98
+ from iq_stream_llamaindex import AGUIEncoder, RunOutcome, publish
99
+
100
+ app = FastAPI()
101
+ iq = IQClient()
102
+ running: set[asyncio.Task[RunOutcome]] = set()
103
+
104
+
105
+ class ChatRequest(BaseModel):
106
+ thread_id: str
107
+ message: str
108
+
109
+
110
+ @app.post("/chat")
111
+ async def chat(request: ChatRequest) -> dict[str, str | int]:
112
+ ticket = iq.ticket()
113
+ handler = agent.run(user_msg=request.message, run_id=ticket.stream_id)
114
+ publisher = iq.apublisher(ticket.stream_id)
115
+ task = asyncio.create_task(
116
+ publish(handler, publisher, encoder=AGUIEncoder(thread_id=request.thread_id), before_close=save_answer)
117
+ )
118
+ running.add(task) # the loop keeps tasks weakly
119
+ task.add_done_callback(running.discard)
120
+ return ticket.to_dict() # streamId, token, url, expiresAt: what the browser subscribes with
121
+ ```
122
+
123
+ `save_answer(outcome)` stands for your persistence. The repository's [`examples/fastapi_agui/app.py`](https://github.com/neuron-core/iq-stream-python/tree/main/packages/iq-stream-llamaindex/examples/fastapi_agui/app.py) adds the two routes a chat needs beside this one: answering a human-input request and stopping a run, each checking the ticket's token with `iq.verify()`. Its tests serve it with uvicorn and drive it over HTTP.
124
+
125
+ ## Reading the events too
126
+
127
+ `stream_events()` has one reader. Code that still needs the events, to answer a human-input request or to log, reads them from `published()`, which yields each event after publishing it, except the terminal one, which it yields before its frames: those go out when the block is left, after `before_close`, so nothing tells the browser the run ended before your code has seen it:
128
+
129
+ ```python
130
+ import asyncio
131
+
132
+ from iq_stream import IQClient
133
+ from workflows.events import HumanResponseEvent, InputRequiredEvent
134
+
135
+ from iq_stream_llamaindex import AGUIEncoder, published
136
+
137
+ iq = IQClient()
138
+
139
+
140
+ async def run_with_approval() -> None:
141
+ ticket = iq.ticket()
142
+ handler = approval_agent.run(user_msg="Book the trip", run_id=ticket.stream_id)
143
+ encoder = AGUIEncoder(thread_id="thread-1")
144
+ async with published(handler, iq.apublisher(ticket.stream_id), encoder=encoder) as events:
145
+ async for event in events:
146
+ if isinstance(event, InputRequiredEvent): # published already, as a CUSTOM "input_required" event
147
+ answer = await answer_from_the_browser(event)
148
+ handler.ctx.send_event(HumanResponseEvent(response=answer))
149
+ print(events.outcome.status)
150
+
151
+
152
+ asyncio.run(run_with_approval())
153
+ ```
154
+
155
+ `approval_agent` stands for an agent whose tool calls `ctx.wait_for_event(HumanResponseEvent, waiter_event=InputRequiredEvent(...))`, and `answer_from_the_browser()` for your endpoint that receives the answer. The stream stays open while the run waits, on keepalives, and the same stream goes on once it is answered; keep the handler reachable by stream id for that, as the example app does. A `ToolCall` that the wait replays is announced once.
156
+
157
+ Breaking out of the loop early does not cut the browser's stream short: leaving the block reads and publishes the rest of the run. Leaving it with an exception stops the run (`handler.cancel_run()`) and closes the stream with `fail`; a cancellation does the same and closes with `close_on_cancel`. `publish(..., on_event=...)` is the same with a callback.
158
+
159
+ An agent's last `AgentOutput`, the one without tool calls, is yielded and published once the next event has arrived, or after 0.25 seconds if that comes first: llama-index-core changes it after writing it to the stream, in the step that follows (a `ReActAgent` strips its `Answer:` scaffolding, the output gains the run's tool calls), so it is published as finalized, as your result has it. The bound matters when a structured output (`structured_output_fn`, `output_cls`) is computed between that output and the end of the run: the answer does not wait for it. A memory that is slow to write can make the bound expire first, and the output is then published as written. If the task is cancelled while the output waits, it is published before the abort frames.
160
+
161
+ ## What the browser needs
162
+
163
+ **`AGUIEncoder`** publishes one AG-UI event per frame, unnamed, as AG-UI's own SSE transport sends them. In the browser, `StreamAgent` from [`@neuron-core/iq-stream/ag-ui`](https://www.npmjs.com/package/@neuron-core/iq-stream) is an `AbstractAgent` of `@ag-ui/client`, so CopilotKit and any AG-UI client can drive it: its `start(input)` posts the run's input to your `/chat` route and returns the ticket. A failed run arrives as `RUN_ERROR` and a stopped one as `RUN_FINISHED` with the `cancelled` outcome, followed by `iq:fail`; `StreamAgent` reads the first and does not report the second as another error. The tests replay what real subscribers received into `StreamAgent.runAgent()` and check the messages it rebuilds: the text, the tool call with its arguments and result, the outcome.
164
+
165
+ **`NativeEncoder`** publishes each event under its class name, with JSON data: `RunStarted`, `AgentStream`, `AgentOutput`, `ToolCall`, `ToolCallResult`, `InputRequiredEvent`, your own events, and the terminal `StopEvent`, `WorkflowFailedEvent`, `WorkflowTimedOutEvent`, `WorkflowCancelledEvent` or `RunAborted`. A page listens to those names, with `addEventListener` on an `EventSource` or with `frames(url, { events: [...] })` from `@neuron-core/iq-stream/client`, and parses each frame's data. It pairs a `ToolCallResult` with its `ToolCall` by `call_id`, not `tool_id`, which repeats when a model has no tool-call ids. It suits pages without a chat framework and workflows whose events are your own.
166
+
167
+ Either way the stream ends with `iq:end` or `iq:fail`, or `iq:gone` for a browser that came after the close and loads the answer from you.
168
+
169
+ ## Event mapping
170
+
171
+ | Stream event | `NativeEncoder`: event name and data | `AGUIEncoder` |
172
+ | --- | --- | --- |
173
+ | (before the first) | `RunStarted` `{run_id}` | `RUN_STARTED` |
174
+ | `AgentInput`, `AgentSetup` | not published: prompts and history stay on the server | a new agent: `STEP_FINISHED` of the previous one, `STEP_STARTED` |
175
+ | `AgentStream` | `AgentStream` `{delta, agent}`, with `thinking_delta` when there is one | `REASONING_*` for a thinking delta, `TEXT_MESSAGE_START` / `CONTENT` for a text delta |
176
+ | `AgentOutput` | `AgentOutput` `{agent, content, tool_calls}`; the last one's `tool_calls` are the run's, as in the result | `TEXT_MESSAGE_END`; the whole text, for an agent built with `streaming=False` |
177
+ | `ToolCall` (a replay left out) | `ToolCall` `{tool_id, call_id, tool_name, tool_kwargs}` | `TOOL_CALL_START`, `TOOL_CALL_ARGS`, `TOOL_CALL_END` |
178
+ | `ToolCallResult` | `ToolCallResult` `{tool_id, call_id, tool_name, content, is_error, return_direct}` | `TOOL_CALL_RESULT` |
179
+ | `AgentStreamStructuredOutput` | `{output}` | `CUSTOM` `structured_output` |
180
+ | `InputRequiredEvent` | its fields | `CUSTOM` `input_required` |
181
+ | An AG-UI event (from `AGUIChatWorkflow`) | its AG-UI JSON | passed through unchanged |
182
+ | Your own event | its fields, undeclared ones included | `CUSTOM` named after its class (`custom_events=False` drops it) |
183
+ | `StopEvent` | `{result}` | `STEP_FINISHED`, `RUN_FINISHED`; first the answer as a text message when a `return_direct` tool gave it |
184
+ | `WorkflowFailedEvent` | `{step_name, message}` | `RUN_ERROR` code `failed` |
185
+ | `WorkflowTimedOutEvent` | `{timeout, active_steps}` | `RUN_ERROR` code `timeout` |
186
+ | `WorkflowCancelledEvent` | `{}` | `RUN_FINISHED` with outcome `cancelled` |
187
+ | (no terminal event; the answer not saved) | `RunAborted` `{reason}` | `RUN_FINISHED` `cancelled`, or `RUN_ERROR` code `aborted` |
188
+
189
+ ## Which close line
190
+
191
+ | The run | Terminal frames | Close |
192
+ | --- | --- | --- |
193
+ | completed | `StopEvent` / `RUN_FINISHED` | `end`, after `before_close` |
194
+ | a step failed for good, or it timed out | `WorkflowFailedEvent`, `WorkflowTimedOutEvent` / `RUN_ERROR` | `fail`, after `before_close` |
195
+ | cancelled with `handler.cancel_run()` | `WorkflowCancelledEvent` / `RUN_FINISHED` `cancelled` | `fail`, or `end` with `close_on_cancel="end"`, after `before_close` |
196
+ | waiting for a human | nothing: the stream stays open | none yet |
197
+ | the task running `publish()` was cancelled | the encoder's abort frames: `RunAborted` `cancelled` / `RUN_FINISHED` `cancelled` | `fail`, or `end` with `close_on_cancel="end"`; the run is stopped and the cancellation goes on |
198
+ | `before_close` raised | the encoder's abort frames instead of the terminal ones | `fail`, and the exception goes on |
199
+ | the run ended, but no terminal event came through its stream | the encoder's abort frames | `fail` |
200
+ | the publisher gave up | none | none: the core client already closed the stream with `fail` |
201
+
202
+ A cancelled run closes with `fail` by default because its answer is incomplete, and a second tab watching the stream should not take it for a finished one; the `cancelled` outcome in the data tells the page that it was a stop.
203
+
204
+ ## Reference
205
+
206
+ ```text
207
+ publish(handler, publisher, *, encoder=None, on_event=None, before_close=None, close_on_cancel="fail",
208
+ raise_run_errors=False) -> RunOutcome
209
+ published(handler, publisher, *, encoder=None, before_close=None, close_on_cancel="fail") -> PublishedStream
210
+ ```
211
+
212
+ | Parameter | |
213
+ | --- | --- |
214
+ | `handler` | What `workflow.run(...)` or `agent.run(...)` returned, whose events nothing has read yet. |
215
+ | `publisher` | `iq.apublisher(stream_id)`, created on the running loop; any `AsyncPublisherLike`. |
216
+ | `encoder` | `NativeEncoder()` by default, `AGUIEncoder(thread_id=...)`, or your own `Encoder`. The run is encoded with a copy of it, so one encoder configured once serves concurrent runs. |
217
+ | `on_event` | Called with each event after its frames were sent, the terminal event before its frames (they follow `before_close`); may be async. Its exceptions propagate. |
218
+ | `before_close` | Called with the `RunOutcome` before the terminal frames and the close line; may be async. Its exceptions propagate, the stream closed with `fail`. |
219
+ | `close_on_cancel` | The close line of a cancelled run, stopped with `handler.cancel_run()` or by cancelling the task: `"fail"` or `"end"` (`iq_stream.Outcome`). |
220
+ | `raise_run_errors` | Raise the run's exception after the close instead of returning it. |
221
+
222
+ `RunOutcome` has `status` (`completed`, `failed`, `timed_out`, `cancelled`), `run_id`, `result` (what `await handler` returned: an agent's `AgentOutput`), `stop_event`, `error` (what `await handler` raised), `frames` (frames the publisher accepted), `published` (false once the publisher gave up) and `publish_result` (the server's answer to the close line, `None` in `before_close`).
223
+
224
+ `NativeEncoder(*, include=(), exclude=(), max_field_bytes=16_384, expose_errors=False)`: `include` and `exclude` choose events by class; the terminal event always goes out.
225
+
226
+ `AGUIEncoder(*, thread_id, run_id=None, emit_steps=True, custom_events=True, max_field_bytes=16_384, expose_errors=False)`: `run_id` defaults to the handler's; `emit_steps` publishes a step per agent; `custom_events` publishes your own events as `CUSTOM`.
227
+
228
+ Both mask the text of the exceptions they encode, a failing tool's included, as `"An error occurred."` unless `expose_errors=True`: an error message can carry what a browser should not see. Events that already are AG-UI events, which `AGUIChatWorkflow` writes itself, pass through as they are: its `MESSAGES_SNAPSHOT` carries each tool message, and for a backend tool that raised, `AGUIChatWorkflow` stores the exception's text as that message, so such a tool should catch its own exceptions and return what the browser may see.
229
+
230
+ Tool calls: a `ToolCall` that a human-input wait replays (the same id, tool and arguments, with no result yet) is announced once. Some model integrations have no tool-call ids and use the tool's name (Ollama, Gemini at times), so two calls can share an id: each call of a run gets an id of its own, LlamaIndex's id for the first, `<id>#2` for the second, `<id>#3` for the third. `AGUIEncoder` publishes it as the call's id; `NativeEncoder` keeps LlamaIndex's `tool_id` and adds it as `call_id`. A result belongs to the open call with the same id, tool and arguments, or else to the oldest open call with the same id and tool: a tool that changes its arguments in place (`numbers.sort()`) changes the result's too.
231
+
232
+ The encoder you pass is copied (`copy.copy`) for each run, and its `start()` begins the run with fresh state, so one instance configured at import serves every request, concurrent ones included. An `Encoder` of your own has four methods, each returning frames, `(event_name_or_None, data)`: `start(run_id)`, `encode(event)` for every event the terminal one included, `abort(error)` for a stream that ends without one, and `fit(frame, fits)`, what to send instead of a frame over the line limit (several frames, a shorter one, or none). Its `start()` gives the state it keeps about a run new objects, which the copy then does not share with the original.
233
+
234
+ ## Sizes
235
+
236
+ - **Large fields are cut.** Tool arguments, tool results and final answers longer than `max_field_bytes` (16 KiB) are cut, with `"truncated": true` in native frames and an ellipsis in AG-UI ones. Tool arguments stay JSON. In AG-UI the final answer is cut when it is published whole (an agent built with `streaming=False`, a `return_direct` tool's result); streamed text is never cut, only split to fit (next point).
237
+ - **Frames fit the publisher's limit.** A frame over the client's `max_frame_bytes` (65,536 by default; set it to your app's limit if the server has a lower one) is handed to the encoder's `fit()`: a long delta or tool-argument text is sent as several frames, which a page concatenates as it would the original; a tool result is cut further. What cannot be made to fit, such as an `AGUIChatWorkflow` `MESSAGES_SNAPSHOT` of a long conversation, is dropped with a warning on the `iq_stream_llamaindex` logger that names the event, never its data.
238
+ - **Text deltas are small.** The native `AgentStream` frame carries the delta, not the cumulative `response` LlamaIndex repeats in every event, so a stream grows with the answer, not with its square.
239
+ - **Every frame is JSON a browser parses.** A non-finite float (`NaN`, `Infinity`) is published as `null`, and a lone surrogate (half of a pair split across two streamed chunks, text decoded with `surrogateescape`) as U+FFFD, which is what the server would make of it, in the events `AGUIChatWorkflow` writes too.
240
+
241
+ ## Limits worth knowing
242
+
243
+ - One reader: a handler whose events something else read, or whose stream a generator of `stream_events()` that was not closed still holds, is refused with an error that says so, and the stream closes with `fail`.
244
+ - The server's stream limits (10 MiB and one hour by default) apply to a run waiting for a human too; `ctx.wait_for_event()` has its own timeout.
245
+ - Tool arguments are published whole at `ToolCall`: LlamaIndex parses them before the step starts, so there is no argument stream to relay.
246
+ - A `ReActAgent`'s text includes its `Thought:` and `Action:` scaffolding, as LlamaIndex streams it, and as its tool steps' `AgentOutput` carries it with `streaming=False`; its last answer is published without `Answer:`, as LlamaIndex saves it, unless it was streamed.
247
+ - A workflow that a tool starts on its own (an agent used as a tool) has its own handler; its events are in the stream only if the tool forwards them with `ctx.write_event_to_stream()`.
248
+ - Reasoning deltas appear when the model integration puts `thinking_delta` in its chunks, as the Anthropic one does.
249
+
250
+ ## Not covered
251
+
252
+ - A tap at the runtime for when another component already reads the handler's stream (LlamaIndex's AG-UI router, `WorkflowServer`): not in this release.
253
+ - AI SDK UI message chunks for `useChat`: no encoder yet; `AGUIEncoder` and `NativeEncoder` are the two formats.
254
+ - Durable runtimes, which replay steps and so events, and `WorkflowServer`.
255
+
256
+ ## Testing your own code
257
+
258
+ `AsyncRecordingPublisher` from `iq_stream.testing` records frames and the close line in memory:
259
+
260
+ ```python
261
+ from iq_stream.testing import AsyncRecordingPublisher
262
+
263
+ from iq_stream_llamaindex import publish
264
+
265
+
266
+ async def test_the_agent_answers_and_the_stream_ends() -> None:
267
+ publisher = AsyncRecordingPublisher()
268
+ outcome = await publish(agent.run(user_msg="Weather in Paris?"), publisher)
269
+ assert outcome.status == "completed"
270
+ assert publisher.outcome == "end"
271
+ assert publisher.frames[-1].event == "StopEvent"
272
+ ```
273
+
274
+ ## Requirements
275
+
276
+ - Python 3.10 to 3.13.
277
+ - `llama-index-workflows` 2.14 or later in 2.x; `llama-index-core` 0.14 for the agents; `ag-ui-protocol` 1.x for AG-UI. The unit tests run against the lowest of each (2.14.0, 0.14.0, 1.0.0) and against 2.26.1, 0.14.25 and 1.0.0.
278
+ - An agent tool that waits for a human (`ctx.wait_for_event()`) pauses the run from `llama-index-core` 0.14.7 on; earlier releases report the wait as the tool's error. Agents take the `run_id` given to `run()` from 0.14.16 on.
279
+ - `iq-stream` 0.1 and an IQ-Stream server 1.x.
280
+
281
+ ## License
282
+
283
+ MIT
@@ -0,0 +1,250 @@
1
+ # iq-stream-llamaindex
2
+
3
+ Publish LlamaIndex runs to browsers through an [IQ-Stream server](https://github.com/neuron-core/iq-stream): a `FunctionAgent`, a `ReActAgent`, a multi-agent `AgentWorkflow`, or any `Workflow`. Your backend starts the run and hands the browser a ticket; the run's events reach the browser as Server-Sent Events while they happen, as [AG-UI](https://docs.ag-ui.com) events or as LlamaIndex's own, and the stream ends with `end` once the answer is saved, or with `fail`.
4
+
5
+ It is one coroutine, `publish(handler, publisher)`, over the handler that `run()` returns and a publisher of the core client [`iq-stream`](https://pypi.org/project/iq-stream/). It reads `handler.stream_events()`, the interface LlamaIndex documents as stable, and it is that stream's only reader: LlamaIndex allows one. `published()` does the same and hands each event on to your code.
6
+
7
+ ```sh
8
+ pip install iq-stream-llamaindex # any workflow, LlamaIndex's own events (NativeEncoder)
9
+ pip install "iq-stream-llamaindex[agents]" # adds llama-index-core: FunctionAgent, ReActAgent, AgentWorkflow
10
+ pip install "iq-stream-llamaindex[ag-ui]" # adds ag-ui-protocol: AG-UI events (AGUIEncoder)
11
+ ```
12
+
13
+ ## Publish a run
14
+
15
+ ```python
16
+ import asyncio
17
+
18
+ from iq_stream import IQClient
19
+
20
+ from iq_stream_llamaindex import AGUIEncoder, RunOutcome, publish
21
+
22
+ iq = IQClient() # IQ_STREAM_URL, IQ_STREAM_APP_KEY and IQ_STREAM_APP_SECRET
23
+
24
+
25
+ async def save_answer(outcome: RunOutcome) -> None:
26
+ print("saving", outcome.status, outcome.result) # your database: called before the close line
27
+
28
+
29
+ async def main() -> None:
30
+ ticket = iq.ticket() # hand ticket.to_dict() to the browser
31
+ handler = agent.run(user_msg="What is the weather in Paris?", run_id=ticket.stream_id)
32
+ outcome = await publish(
33
+ handler,
34
+ iq.apublisher(ticket.stream_id), # its one request to the server opens now
35
+ encoder=AGUIEncoder(thread_id="thread-1"),
36
+ before_close=save_answer,
37
+ )
38
+ print(outcome.status, outcome.frames, outcome.publish_result)
39
+
40
+
41
+ asyncio.run(main())
42
+ ```
43
+
44
+ `agent` stands for your agent or workflow. Passing the stream id as `run_id` puts it in LlamaIndex's logs and instrumentation tags (agents take it from llama-index-core 0.14.16 on; earlier releases ignore it). LlamaIndex has no synchronous API: `run()` needs a running event loop, so a queue worker wraps the run in `asyncio.run()` as above.
45
+
46
+ What `publish()` does:
47
+
48
+ - **It publishes while the run runs.** Each event becomes frames on the publisher as it is read: a text delta is a frame, a tool call is its frames, all on the one request the core client holds open. The one exception is an agent's last `AgentOutput`, which waits for llama-index-core to finalize it (below), a quarter of a second at most. Keepalives cover a tool that takes minutes, or a run waiting for a human.
49
+ - **It saves before it closes.** When the run ends, `publish()` awaits its result, calls `before_close(outcome)`, and only then sends the terminal frames (`RUN_FINISHED`, `RUN_ERROR`) and the close line. A browser that arrives after the close receives `iq:gone` and loads the answer from you, so it must be there.
50
+ - **It returns how the run ended.** A failed run is returned, not raised: `publish()` usually runs in a task of its own, where an exception would only be logged. `raise_run_errors=True` raises it after the close.
51
+ - **Publishing never breaks the run.** A publisher that gives up (the server refused, the stream grew too large) stops the encoding; the run is still read to its end, `before_close` still runs, and `outcome.published` is `False`.
52
+ - **It never hangs.** A run killed with the deprecated `handler.cancel()` publishes no terminal event; `publish()` notices that the run is done and ends the stream a second later.
53
+
54
+ ## In a FastAPI app
55
+
56
+ The route starts the run, answers with the ticket at once, and leaves the run and its stream to a task:
57
+
58
+ ```python
59
+ import asyncio
60
+
61
+ from fastapi import FastAPI
62
+ from iq_stream import IQClient
63
+ from pydantic import BaseModel
64
+
65
+ from iq_stream_llamaindex import AGUIEncoder, RunOutcome, publish
66
+
67
+ app = FastAPI()
68
+ iq = IQClient()
69
+ running: set[asyncio.Task[RunOutcome]] = set()
70
+
71
+
72
+ class ChatRequest(BaseModel):
73
+ thread_id: str
74
+ message: str
75
+
76
+
77
+ @app.post("/chat")
78
+ async def chat(request: ChatRequest) -> dict[str, str | int]:
79
+ ticket = iq.ticket()
80
+ handler = agent.run(user_msg=request.message, run_id=ticket.stream_id)
81
+ publisher = iq.apublisher(ticket.stream_id)
82
+ task = asyncio.create_task(
83
+ publish(handler, publisher, encoder=AGUIEncoder(thread_id=request.thread_id), before_close=save_answer)
84
+ )
85
+ running.add(task) # the loop keeps tasks weakly
86
+ task.add_done_callback(running.discard)
87
+ return ticket.to_dict() # streamId, token, url, expiresAt: what the browser subscribes with
88
+ ```
89
+
90
+ `save_answer(outcome)` stands for your persistence. The repository's [`examples/fastapi_agui/app.py`](https://github.com/neuron-core/iq-stream-python/tree/main/packages/iq-stream-llamaindex/examples/fastapi_agui/app.py) adds the two routes a chat needs beside this one: answering a human-input request and stopping a run, each checking the ticket's token with `iq.verify()`. Its tests serve it with uvicorn and drive it over HTTP.
91
+
92
+ ## Reading the events too
93
+
94
+ `stream_events()` has one reader. Code that still needs the events, to answer a human-input request or to log, reads them from `published()`, which yields each event after publishing it, except the terminal one, which it yields before its frames: those go out when the block is left, after `before_close`, so nothing tells the browser the run ended before your code has seen it:
95
+
96
+ ```python
97
+ import asyncio
98
+
99
+ from iq_stream import IQClient
100
+ from workflows.events import HumanResponseEvent, InputRequiredEvent
101
+
102
+ from iq_stream_llamaindex import AGUIEncoder, published
103
+
104
+ iq = IQClient()
105
+
106
+
107
+ async def run_with_approval() -> None:
108
+ ticket = iq.ticket()
109
+ handler = approval_agent.run(user_msg="Book the trip", run_id=ticket.stream_id)
110
+ encoder = AGUIEncoder(thread_id="thread-1")
111
+ async with published(handler, iq.apublisher(ticket.stream_id), encoder=encoder) as events:
112
+ async for event in events:
113
+ if isinstance(event, InputRequiredEvent): # published already, as a CUSTOM "input_required" event
114
+ answer = await answer_from_the_browser(event)
115
+ handler.ctx.send_event(HumanResponseEvent(response=answer))
116
+ print(events.outcome.status)
117
+
118
+
119
+ asyncio.run(run_with_approval())
120
+ ```
121
+
122
+ `approval_agent` stands for an agent whose tool calls `ctx.wait_for_event(HumanResponseEvent, waiter_event=InputRequiredEvent(...))`, and `answer_from_the_browser()` for your endpoint that receives the answer. The stream stays open while the run waits, on keepalives, and the same stream goes on once it is answered; keep the handler reachable by stream id for that, as the example app does. A `ToolCall` that the wait replays is announced once.
123
+
124
+ Breaking out of the loop early does not cut the browser's stream short: leaving the block reads and publishes the rest of the run. Leaving it with an exception stops the run (`handler.cancel_run()`) and closes the stream with `fail`; a cancellation does the same and closes with `close_on_cancel`. `publish(..., on_event=...)` is the same with a callback.
125
+
126
+ An agent's last `AgentOutput`, the one without tool calls, is yielded and published once the next event has arrived, or after 0.25 seconds if that comes first: llama-index-core changes it after writing it to the stream, in the step that follows (a `ReActAgent` strips its `Answer:` scaffolding, the output gains the run's tool calls), so it is published as finalized, as your result has it. The bound matters when a structured output (`structured_output_fn`, `output_cls`) is computed between that output and the end of the run: the answer does not wait for it. A memory that is slow to write can make the bound expire first, and the output is then published as written. If the task is cancelled while the output waits, it is published before the abort frames.
127
+
128
+ ## What the browser needs
129
+
130
+ **`AGUIEncoder`** publishes one AG-UI event per frame, unnamed, as AG-UI's own SSE transport sends them. In the browser, `StreamAgent` from [`@neuron-core/iq-stream/ag-ui`](https://www.npmjs.com/package/@neuron-core/iq-stream) is an `AbstractAgent` of `@ag-ui/client`, so CopilotKit and any AG-UI client can drive it: its `start(input)` posts the run's input to your `/chat` route and returns the ticket. A failed run arrives as `RUN_ERROR` and a stopped one as `RUN_FINISHED` with the `cancelled` outcome, followed by `iq:fail`; `StreamAgent` reads the first and does not report the second as another error. The tests replay what real subscribers received into `StreamAgent.runAgent()` and check the messages it rebuilds: the text, the tool call with its arguments and result, the outcome.
131
+
132
+ **`NativeEncoder`** publishes each event under its class name, with JSON data: `RunStarted`, `AgentStream`, `AgentOutput`, `ToolCall`, `ToolCallResult`, `InputRequiredEvent`, your own events, and the terminal `StopEvent`, `WorkflowFailedEvent`, `WorkflowTimedOutEvent`, `WorkflowCancelledEvent` or `RunAborted`. A page listens to those names, with `addEventListener` on an `EventSource` or with `frames(url, { events: [...] })` from `@neuron-core/iq-stream/client`, and parses each frame's data. It pairs a `ToolCallResult` with its `ToolCall` by `call_id`, not `tool_id`, which repeats when a model has no tool-call ids. It suits pages without a chat framework and workflows whose events are your own.
133
+
134
+ Either way the stream ends with `iq:end` or `iq:fail`, or `iq:gone` for a browser that came after the close and loads the answer from you.
135
+
136
+ ## Event mapping
137
+
138
+ | Stream event | `NativeEncoder`: event name and data | `AGUIEncoder` |
139
+ | --- | --- | --- |
140
+ | (before the first) | `RunStarted` `{run_id}` | `RUN_STARTED` |
141
+ | `AgentInput`, `AgentSetup` | not published: prompts and history stay on the server | a new agent: `STEP_FINISHED` of the previous one, `STEP_STARTED` |
142
+ | `AgentStream` | `AgentStream` `{delta, agent}`, with `thinking_delta` when there is one | `REASONING_*` for a thinking delta, `TEXT_MESSAGE_START` / `CONTENT` for a text delta |
143
+ | `AgentOutput` | `AgentOutput` `{agent, content, tool_calls}`; the last one's `tool_calls` are the run's, as in the result | `TEXT_MESSAGE_END`; the whole text, for an agent built with `streaming=False` |
144
+ | `ToolCall` (a replay left out) | `ToolCall` `{tool_id, call_id, tool_name, tool_kwargs}` | `TOOL_CALL_START`, `TOOL_CALL_ARGS`, `TOOL_CALL_END` |
145
+ | `ToolCallResult` | `ToolCallResult` `{tool_id, call_id, tool_name, content, is_error, return_direct}` | `TOOL_CALL_RESULT` |
146
+ | `AgentStreamStructuredOutput` | `{output}` | `CUSTOM` `structured_output` |
147
+ | `InputRequiredEvent` | its fields | `CUSTOM` `input_required` |
148
+ | An AG-UI event (from `AGUIChatWorkflow`) | its AG-UI JSON | passed through unchanged |
149
+ | Your own event | its fields, undeclared ones included | `CUSTOM` named after its class (`custom_events=False` drops it) |
150
+ | `StopEvent` | `{result}` | `STEP_FINISHED`, `RUN_FINISHED`; first the answer as a text message when a `return_direct` tool gave it |
151
+ | `WorkflowFailedEvent` | `{step_name, message}` | `RUN_ERROR` code `failed` |
152
+ | `WorkflowTimedOutEvent` | `{timeout, active_steps}` | `RUN_ERROR` code `timeout` |
153
+ | `WorkflowCancelledEvent` | `{}` | `RUN_FINISHED` with outcome `cancelled` |
154
+ | (no terminal event; the answer not saved) | `RunAborted` `{reason}` | `RUN_FINISHED` `cancelled`, or `RUN_ERROR` code `aborted` |
155
+
156
+ ## Which close line
157
+
158
+ | The run | Terminal frames | Close |
159
+ | --- | --- | --- |
160
+ | completed | `StopEvent` / `RUN_FINISHED` | `end`, after `before_close` |
161
+ | a step failed for good, or it timed out | `WorkflowFailedEvent`, `WorkflowTimedOutEvent` / `RUN_ERROR` | `fail`, after `before_close` |
162
+ | cancelled with `handler.cancel_run()` | `WorkflowCancelledEvent` / `RUN_FINISHED` `cancelled` | `fail`, or `end` with `close_on_cancel="end"`, after `before_close` |
163
+ | waiting for a human | nothing: the stream stays open | none yet |
164
+ | the task running `publish()` was cancelled | the encoder's abort frames: `RunAborted` `cancelled` / `RUN_FINISHED` `cancelled` | `fail`, or `end` with `close_on_cancel="end"`; the run is stopped and the cancellation goes on |
165
+ | `before_close` raised | the encoder's abort frames instead of the terminal ones | `fail`, and the exception goes on |
166
+ | the run ended, but no terminal event came through its stream | the encoder's abort frames | `fail` |
167
+ | the publisher gave up | none | none: the core client already closed the stream with `fail` |
168
+
169
+ A cancelled run closes with `fail` by default because its answer is incomplete, and a second tab watching the stream should not take it for a finished one; the `cancelled` outcome in the data tells the page that it was a stop.
170
+
171
+ ## Reference
172
+
173
+ ```text
174
+ publish(handler, publisher, *, encoder=None, on_event=None, before_close=None, close_on_cancel="fail",
175
+ raise_run_errors=False) -> RunOutcome
176
+ published(handler, publisher, *, encoder=None, before_close=None, close_on_cancel="fail") -> PublishedStream
177
+ ```
178
+
179
+ | Parameter | |
180
+ | --- | --- |
181
+ | `handler` | What `workflow.run(...)` or `agent.run(...)` returned, whose events nothing has read yet. |
182
+ | `publisher` | `iq.apublisher(stream_id)`, created on the running loop; any `AsyncPublisherLike`. |
183
+ | `encoder` | `NativeEncoder()` by default, `AGUIEncoder(thread_id=...)`, or your own `Encoder`. The run is encoded with a copy of it, so one encoder configured once serves concurrent runs. |
184
+ | `on_event` | Called with each event after its frames were sent, the terminal event before its frames (they follow `before_close`); may be async. Its exceptions propagate. |
185
+ | `before_close` | Called with the `RunOutcome` before the terminal frames and the close line; may be async. Its exceptions propagate, the stream closed with `fail`. |
186
+ | `close_on_cancel` | The close line of a cancelled run, stopped with `handler.cancel_run()` or by cancelling the task: `"fail"` or `"end"` (`iq_stream.Outcome`). |
187
+ | `raise_run_errors` | Raise the run's exception after the close instead of returning it. |
188
+
189
+ `RunOutcome` has `status` (`completed`, `failed`, `timed_out`, `cancelled`), `run_id`, `result` (what `await handler` returned: an agent's `AgentOutput`), `stop_event`, `error` (what `await handler` raised), `frames` (frames the publisher accepted), `published` (false once the publisher gave up) and `publish_result` (the server's answer to the close line, `None` in `before_close`).
190
+
191
+ `NativeEncoder(*, include=(), exclude=(), max_field_bytes=16_384, expose_errors=False)`: `include` and `exclude` choose events by class; the terminal event always goes out.
192
+
193
+ `AGUIEncoder(*, thread_id, run_id=None, emit_steps=True, custom_events=True, max_field_bytes=16_384, expose_errors=False)`: `run_id` defaults to the handler's; `emit_steps` publishes a step per agent; `custom_events` publishes your own events as `CUSTOM`.
194
+
195
+ Both mask the text of the exceptions they encode, a failing tool's included, as `"An error occurred."` unless `expose_errors=True`: an error message can carry what a browser should not see. Events that already are AG-UI events, which `AGUIChatWorkflow` writes itself, pass through as they are: its `MESSAGES_SNAPSHOT` carries each tool message, and for a backend tool that raised, `AGUIChatWorkflow` stores the exception's text as that message, so such a tool should catch its own exceptions and return what the browser may see.
196
+
197
+ Tool calls: a `ToolCall` that a human-input wait replays (the same id, tool and arguments, with no result yet) is announced once. Some model integrations have no tool-call ids and use the tool's name (Ollama, Gemini at times), so two calls can share an id: each call of a run gets an id of its own, LlamaIndex's id for the first, `<id>#2` for the second, `<id>#3` for the third. `AGUIEncoder` publishes it as the call's id; `NativeEncoder` keeps LlamaIndex's `tool_id` and adds it as `call_id`. A result belongs to the open call with the same id, tool and arguments, or else to the oldest open call with the same id and tool: a tool that changes its arguments in place (`numbers.sort()`) changes the result's too.
198
+
199
+ The encoder you pass is copied (`copy.copy`) for each run, and its `start()` begins the run with fresh state, so one instance configured at import serves every request, concurrent ones included. An `Encoder` of your own has four methods, each returning frames, `(event_name_or_None, data)`: `start(run_id)`, `encode(event)` for every event the terminal one included, `abort(error)` for a stream that ends without one, and `fit(frame, fits)`, what to send instead of a frame over the line limit (several frames, a shorter one, or none). Its `start()` gives the state it keeps about a run new objects, which the copy then does not share with the original.
200
+
201
+ ## Sizes
202
+
203
+ - **Large fields are cut.** Tool arguments, tool results and final answers longer than `max_field_bytes` (16 KiB) are cut, with `"truncated": true` in native frames and an ellipsis in AG-UI ones. Tool arguments stay JSON. In AG-UI the final answer is cut when it is published whole (an agent built with `streaming=False`, a `return_direct` tool's result); streamed text is never cut, only split to fit (next point).
204
+ - **Frames fit the publisher's limit.** A frame over the client's `max_frame_bytes` (65,536 by default; set it to your app's limit if the server has a lower one) is handed to the encoder's `fit()`: a long delta or tool-argument text is sent as several frames, which a page concatenates as it would the original; a tool result is cut further. What cannot be made to fit, such as an `AGUIChatWorkflow` `MESSAGES_SNAPSHOT` of a long conversation, is dropped with a warning on the `iq_stream_llamaindex` logger that names the event, never its data.
205
+ - **Text deltas are small.** The native `AgentStream` frame carries the delta, not the cumulative `response` LlamaIndex repeats in every event, so a stream grows with the answer, not with its square.
206
+ - **Every frame is JSON a browser parses.** A non-finite float (`NaN`, `Infinity`) is published as `null`, and a lone surrogate (half of a pair split across two streamed chunks, text decoded with `surrogateescape`) as U+FFFD, which is what the server would make of it, in the events `AGUIChatWorkflow` writes too.
207
+
208
+ ## Limits worth knowing
209
+
210
+ - One reader: a handler whose events something else read, or whose stream a generator of `stream_events()` that was not closed still holds, is refused with an error that says so, and the stream closes with `fail`.
211
+ - The server's stream limits (10 MiB and one hour by default) apply to a run waiting for a human too; `ctx.wait_for_event()` has its own timeout.
212
+ - Tool arguments are published whole at `ToolCall`: LlamaIndex parses them before the step starts, so there is no argument stream to relay.
213
+ - A `ReActAgent`'s text includes its `Thought:` and `Action:` scaffolding, as LlamaIndex streams it, and as its tool steps' `AgentOutput` carries it with `streaming=False`; its last answer is published without `Answer:`, as LlamaIndex saves it, unless it was streamed.
214
+ - A workflow that a tool starts on its own (an agent used as a tool) has its own handler; its events are in the stream only if the tool forwards them with `ctx.write_event_to_stream()`.
215
+ - Reasoning deltas appear when the model integration puts `thinking_delta` in its chunks, as the Anthropic one does.
216
+
217
+ ## Not covered
218
+
219
+ - A tap at the runtime for when another component already reads the handler's stream (LlamaIndex's AG-UI router, `WorkflowServer`): not in this release.
220
+ - AI SDK UI message chunks for `useChat`: no encoder yet; `AGUIEncoder` and `NativeEncoder` are the two formats.
221
+ - Durable runtimes, which replay steps and so events, and `WorkflowServer`.
222
+
223
+ ## Testing your own code
224
+
225
+ `AsyncRecordingPublisher` from `iq_stream.testing` records frames and the close line in memory:
226
+
227
+ ```python
228
+ from iq_stream.testing import AsyncRecordingPublisher
229
+
230
+ from iq_stream_llamaindex import publish
231
+
232
+
233
+ async def test_the_agent_answers_and_the_stream_ends() -> None:
234
+ publisher = AsyncRecordingPublisher()
235
+ outcome = await publish(agent.run(user_msg="Weather in Paris?"), publisher)
236
+ assert outcome.status == "completed"
237
+ assert publisher.outcome == "end"
238
+ assert publisher.frames[-1].event == "StopEvent"
239
+ ```
240
+
241
+ ## Requirements
242
+
243
+ - Python 3.10 to 3.13.
244
+ - `llama-index-workflows` 2.14 or later in 2.x; `llama-index-core` 0.14 for the agents; `ag-ui-protocol` 1.x for AG-UI. The unit tests run against the lowest of each (2.14.0, 0.14.0, 1.0.0) and against 2.26.1, 0.14.25 and 1.0.0.
245
+ - An agent tool that waits for a human (`ctx.wait_for_event()`) pauses the run from `llama-index-core` 0.14.7 on; earlier releases report the wait as the tool's error. Agents take the `run_id` given to `run()` from 0.14.16 on.
246
+ - `iq-stream` 0.1 and an IQ-Stream server 1.x.
247
+
248
+ ## License
249
+
250
+ MIT