iq-stream-crewai 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,256 @@
1
+ Metadata-Version: 2.5
2
+ Name: iq-stream-crewai
3
+ Version: 0.1.0
4
+ Summary: Publish a CrewAI run to browsers through an IQ-Stream server, as AG-UI events or CrewAI's own
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-crewai
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,crewai,iq-stream,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.14,>=3.10
26
+ Requires-Dist: ag-ui-protocol<2,>=1.0
27
+ Requires-Dist: crewai<2,>=1.15.2
28
+ Requires-Dist: iq-stream<0.2,>=0.1.0
29
+ Description-Content-Type: text/markdown
30
+
31
+ # iq-stream-crewai
32
+
33
+ Publishes a [CrewAI](https://github.com/crewAIInc/crewAI) run to browsers through an [IQ-Stream server](https://github.com/neuron-core/iq-stream). Everything CrewAI emits inside a `with publish(...)` block (the model's tokens, tool calls and their results, tasks, flow steps) goes to one stream as it happens, as [AG-UI](https://docs.ag-ui.com) events by default or as CrewAI's own events. The block closes the stream with `end` when it exits normally and with `fail` when it raises. The browser reads the stream with `StreamAgent` from [`@neuron-core/iq-stream`](https://www.npmjs.com/package/@neuron-core/iq-stream), or with any AG-UI client.
34
+
35
+ It is a thin layer over the core client, [`iq-stream`](https://pypi.org/project/iq-stream/), which owns the connection to the server: one request per answer, keepalives while a tool runs, resuming after a lost request, and the close line.
36
+
37
+ ```sh
38
+ pip install iq-stream-crewai
39
+ ```
40
+
41
+ ## Publish a crew
42
+
43
+ ```python
44
+ from iq_stream import IQClient
45
+ from iq_stream_crewai import publish
46
+
47
+ iq = IQClient() # IQ_STREAM_URL, IQ_STREAM_APP_KEY and IQ_STREAM_APP_SECRET
48
+
49
+
50
+ def answer(stream_id: str, question: str) -> None:
51
+ """Runs where the crew runs: a thread, a task or a queue job."""
52
+ with publish(iq, stream_id): # the request to the server opens now
53
+ result = crew.kickoff(inputs={"question": question})
54
+ save_answer(stream_id, result.raw) # before the close line: a late browser loads it from you
55
+ # the block closes the stream with "end", or with "fail" if it raised
56
+
57
+
58
+ ticket = iq.ticket() # what the browser needs: stream_id, token, url, expires_at
59
+ answer(ticket.stream_id, "What is the capital of France?")
60
+ ```
61
+
62
+ `crew` stands for your crew and `save_answer()` for your own persistence. The block may hold anything that makes CrewAI emit events: `crew.kickoff()`, `flow.kickoff()`, `agent.kickoff()`, several kickoffs, or a `Crew(stream=True)` whose chunks your code iterates itself, inside the block. CrewAI needs to know nothing about the stream: no id goes into `inputs`.
63
+
64
+ The block taps CrewAI through a scoped stream sink, the mechanism CrewAI's own frame streaming is built on. It sees every event emitted in the block's context and in the threads CrewAI starts from it, in the thread that emits it, before any listener of the global event bus: several crews in one process never see each other's events, nothing overtakes an event on its way to the stream, and nothing is left to flush when `kickoff()` returns. Each event is copied, encoded under one lock per stream and handed to the core's `send()`, which only queues.
65
+
66
+ In asyncio, the same object is used with `async with`. The adapter still uses the core's synchronous publisher, because CrewAI emits from worker threads even in `akickoff()`; the closing frames go out before anything is awaited, and the server's answer is awaited in a thread of its own, not in the loop's default executor, where each `kickoff_async()` holds a thread for its whole run.
67
+
68
+ ```python
69
+ import asyncio
70
+
71
+ from iq_stream import IQClient
72
+ from iq_stream_crewai import publish
73
+
74
+ iq = IQClient()
75
+
76
+
77
+ async def answer(stream_id: str, question: str) -> None:
78
+ async with publish(iq, stream_id): # a cancelled task closes the stream with "fail"
79
+ result = await crew.akickoff(inputs={"question": question})
80
+ await asave_answer(stream_id, result.raw)
81
+
82
+
83
+ asyncio.run(answer(iq.new_stream_id(), "What is the capital of France?"))
84
+ ```
85
+
86
+ ### Behind a route
87
+
88
+ CrewAI serves no HTTP of its own; a route starts the run in a worker and answers with the ticket at once. With `StreamAgent` in the browser, the request body is AG-UI's `RunAgentInput`, and the run's `threadId` and `runId` are the client's own:
89
+
90
+ ```python
91
+ from concurrent.futures import ThreadPoolExecutor
92
+
93
+ from ag_ui.core import RunAgentInput
94
+ from fastapi import FastAPI
95
+
96
+ from iq_stream import IQClient
97
+ from iq_stream_crewai import publish
98
+
99
+ app = FastAPI()
100
+ iq = IQClient()
101
+ workers = ThreadPoolExecutor(max_workers=8)
102
+ answers: dict[str, str] = {} # stands for your database
103
+
104
+
105
+ def answer(stream_id: str, run: RunAgentInput) -> None:
106
+ question = next(message.content for message in reversed(run.messages) if message.role == "user")
107
+ with publish(iq, stream_id, thread_id=run.thread_id, run_id=run.run_id):
108
+ result = build_crew().kickoff(inputs={"question": question})
109
+ answers[stream_id] = result.raw
110
+
111
+
112
+ @app.post("/chat")
113
+ def chat(run: RunAgentInput) -> dict[str, str | int]:
114
+ ticket = iq.ticket()
115
+ workers.submit(answer, ticket.stream_id, run)
116
+ return ticket.to_dict() # streamId, token, url, expiresAt
117
+
118
+
119
+ @app.get("/chat/{stream_id}")
120
+ def saved(stream_id: str) -> dict[str, str | None]:
121
+ """What a browser that missed the stream (iq:gone) loads instead."""
122
+ return {"answer": answers.get(stream_id)}
123
+ ```
124
+
125
+ The worker must enter the block within 30 seconds of the browser subscribing, the time a stream waits for its publisher; a queue that can be slower calls `iq.reserve(stream_id)` in the route. The core holds the close line back until the stream is three seconds old (`min_open`), so a browser that subscribes just after a quick answer still receives it.
126
+
127
+ ### CrewAI's own events, and tokens
128
+
129
+ Without streaming on the model, a run publishes its tool calls, tasks and steps, and each answer as one block when the model call returns. `enable_token_streaming()` turns streaming on for the models of crews, agents or models, as `Crew(stream=True)` does inside its kickoff (`LLM(stream=True)` does it for one model). `protocol="crewai"` publishes CrewAI's own events instead of AG-UI's:
130
+
131
+ ```python
132
+ from iq_stream import IQClient
133
+ from iq_stream_crewai import enable_token_streaming, publish
134
+
135
+ iq = IQClient()
136
+ enable_token_streaming(crew)
137
+
138
+ with publish(iq, protocol="crewai") as run: # without a stream id, a new one: run.stream_id
139
+ crew.kickoff(inputs={"question": "What is the capital of France?"})
140
+ print(run.stream_id, run.frames_sent, run.result)
141
+ ```
142
+
143
+ ## What the browser needs
144
+
145
+ With the default protocol the frames are AG-UI events, unnamed, as AG-UI's own SSE encoding writes them. `StreamAgent` from `@neuron-core/iq-stream/ag-ui` is an `AbstractAgent` of `@ag-ui/client` that posts the run's input with your `start()` and reads the events from the ticket's URL, so CopilotKit or any UI built on `@ag-ui/client` uses it as it would an `HttpAgent`:
146
+
147
+ ```ts
148
+ import { StreamAgent } from '@neuron-core/iq-stream/ag-ui';
149
+
150
+ const agent = new StreamAgent({
151
+ start: async (input) =>
152
+ (await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) })).json(),
153
+ });
154
+ await agent.runAgent(); // agent.messages: the assistant's text, its tool calls and their results
155
+ ```
156
+
157
+ A failed or cancelled run reaches the page twice, as `RUN_ERROR` (or `RUN_FINISHED` with the `cancelled` outcome) and then as `iq:fail` with reason `publisher`; `StreamAgent` ends the run once, on the first. A flow paused for human feedback ends with `RUN_FINISHED` and AG-UI's `interrupt` outcome, which `@ag-ui/client` hands to `onRunFinishedEvent` as `outcome: "interrupt"` with the `interrupts`. With `protocol="crewai"` each frame is named after its CrewAI event type, and the page listens for the names it wants: `subscribe(url, handlers, { events: ['llm_stream_chunk', 'tool_usage_finished', …] })` from `@neuron-core/iq-stream/client`. There is no front-end client for CrewAI's native events; the page keeps its own state.
158
+
159
+ ## What is published
160
+
161
+ | CrewAI event | `ag-ui` frames | `crewai` frame members |
162
+ | --- | --- | --- |
163
+ | block entered | `RUN_STARTED` | none |
164
+ | `llm_stream_chunk`, text | `TEXT_MESSAGE_START` (once per model call, `messageId` = its `call_id`, `name` = the agent's role), `TEXT_MESSAGE_CONTENT` | `call_id`, `chunk` |
165
+ | `llm_stream_chunk`, tool call | `TOOL_CALL_START` (`parentMessageId` = the call), `TOOL_CALL_ARGS` | `call_id`, `chunk`, `tool_call` (`id`, `name`, `index`; never the accumulated arguments) |
166
+ | `llm_thinking_chunk` | `REASONING_START`, `REASONING_MESSAGE_START`, `REASONING_MESSAGE_CONTENT`, closed by the call's next event | `call_id`, `chunk` |
167
+ | `llm_call_completed`, `llm_call_failed` | ends what the call left open; a call that streamed nothing and returned text: the whole text message | `call_id`, `finish_reason`, `usage` / `error` |
168
+ | `tool_usage_started` | binds to the streamed call of that tool and agent with the same arguments (else the oldest); a call no model streamed is announced whole | `tool_name`, `tool_args`, `agent_id`, `agent_role`, `task_id` |
169
+ | `tool_usage_finished`, `tool_usage_error` | `TOOL_CALL_RESULT` (`{"error": …}` for an error) | the same, with `output`, `from_cache` / `error` |
170
+ | `task_started`, `task_completed`, `task_failed` | `STEP_STARTED`, `STEP_FINISHED` (`task:<name>`) | `task_id`, `task_name`, `output` / `error` |
171
+ | `method_execution_started`, `_finished`, `_failed` | `STEP_STARTED`, `STEP_FINISHED` (`flow:<method>`) | `flow_name`, `method_name`, `error` |
172
+ | `human_feedback_requested`, `flow_paused` | `CUSTOM` named `crewai.<type>`; a paused flow also makes the run end interrupted | `flow_name`, `method_name`, `message`, `emit`, `request_id` / `flow_id` |
173
+ | `agent_execution_*`, `crew_kickoff_*`, `flow_started`, `flow_finished`, `flow_failed`, `human_feedback_received` | none | their ids (`flow_id` included), names, `output`, `error`, `total_tokens` |
174
+ | block exits | `RUN_FINISHED`; with outcome `interrupt` while a flow is paused, or `cancelled`; or `RUN_ERROR` | none |
175
+
176
+ Every `crewai` frame also has `seq`, the event's `emission_sequence`. Members without a value are left out. An event that is already an AG-UI event (as flows written for `ag-ui-crewai` emit them) is forwarded as it is.
177
+
178
+ What CrewAI does for itself is left out of both protocols:
179
+
180
+ - the flows it runs inside every agent and for memory;
181
+ - its own agents and tasks, with everything they emit: a task's guardrail (the "Guardrail Agent"), an agent's plan (`planning_config`, `reasoning=True`), the planner of `Crew(planning=True)`, memory's saves and searches, knowledge queries;
182
+ - the model calls that name no agent which it makes around an agent's run: memory's analysis, the conversion of an output (`output_pydantic`, `output_json`, `response_format`), and the summary of a context window that is full.
183
+
184
+ Every other model call is published, whoever made it: the agent's own (its final answer forced at `max_iter` included, and those of a model wrapper that does not pass the agent on), and `llm.call()` in the block, in a flow method or in a tool, a flow your tool kicks off included. A model call your task callback makes itself is left out: in CrewAI's events nothing tells it from an output's conversion.
185
+
186
+ ## Which close line
187
+
188
+ - **The block exits normally**: `RUN_FINISHED`, then `end`. Save the answer inside the block, after `kickoff()`: a browser that arrives after the close receives `iq:gone` and loads it from you. CrewAI has finished its own writes (task callbacks, `output_file`, memory) when `kickoff()` returns.
189
+ - **The block raises**: `RUN_ERROR` with `code` `"error"` and the message masked (with `expose_errors=True`, the exception's class and text), then `fail`; the exception goes on unchanged.
190
+ - **The block is cancelled** (`asyncio.CancelledError`, `KeyboardInterrupt`): `RUN_FINISHED` with the `cancelled` outcome, so the page can tell a stop from a failure, then `fail`, or `end` with `close_on_cancel="end"`. Only asyncio runs can be cancelled; a cancelled run leaves CrewAI's worker threads running to completion, and what they emit after the block is not published.
191
+ - **A flow pauses for human feedback** (`@human_feedback` with an asynchronous provider): `kickoff()` returns `HumanFeedbackPending`, the block exits normally, and the stream ends with `end` after a `CUSTOM` `crewai.flow_paused` frame and `RUN_FINISHED` with the `interrupt` outcome: one interrupt per paused flow, whose `id` is the flow's id (what `Flow.from_pending()` takes), `reason` `"human_feedback"` and `message` the flow's question. The resumed flow is a new run on a new stream.
192
+ - **The process dies**: nothing closes the stream; its browsers get `iq:fail` with `publisher_idle` after the server's idle timeout.
193
+
194
+ Publishing never breaks the run. When the publisher gives up (the server refused, or cannot be reached), the adapter stops encoding and the crew goes on; the reason is in `run.publisher.error`. With the client's `on_error="raise"`, the block raises that error when it exits normally, after your code has run. The adapter's own failures, which never leave the sink, are in `run.errors` and logged once per stream, without event data, on the `iq_stream_crewai` logger.
195
+
196
+ ## Reference
197
+
198
+ ```text
199
+ publish(target, stream_id=None, *, protocol="ag-ui", thread_id=None, run_id=None, include=None, exclude=(),
200
+ max_field_bytes=16_384, expose_errors=False, close_on_cancel="fail", transport="auto") -> CrewAIStream
201
+ ```
202
+
203
+ `target` is an `IQClient`, whose publisher for `stream_id` (a new id when `None`) is created when the block is entered, or a synchronous publisher (`PublisherLike`) that the block takes over and closes. `publish()` itself sends nothing.
204
+
205
+ | Option | Default | |
206
+ | --- | --- | --- |
207
+ | `protocol` | `"ag-ui"` | `"ag-ui"`, `"crewai"`, or an `Encoder` of your own. |
208
+ | `thread_id`, `run_id` | the stream id, a new uuid | AG-UI's ids of the run. |
209
+ | `include`, `exclude` | `EVENT_TYPES` | The CrewAI event types the encoder sees. Without `llm_stream_chunk`, each answer is published when its call returns. |
210
+ | `max_field_bytes` | `16_384` | Tool results, task outputs and other text values are cut to this many bytes of UTF-8, at a character's boundary, with a marker (`… [N bytes truncated]`); `None` cuts nothing. |
211
+ | `expose_errors` | `False` | Publish error messages as they are; by default each one is `An error occurred.` |
212
+ | `close_on_cancel` | `"fail"` | The close line after a cancellation (`iq_stream.Outcome`). |
213
+ | `transport` | `"auto"` | `"sink"` (CrewAI's scoped stream sink), or `"bus"` (handlers on the global event bus). `"auto"` takes the sink. |
214
+
215
+ `CrewAIStream` has `stream_id`, `thread_id`, `run_id`, `publisher` (the core's, once entered), `frames_sent`, `errors` and `result` (the core's `PublishResult` once the block has exited), and `send(data, event=None)` for a frame of your own, in order with the run's. `enable_token_streaming(*crews_agents_or_models)` turns streaming on for their models. `EVENT_TYPES` lists the event types the adapter knows.
216
+
217
+ An `Encoder` has four methods: `snapshot(source, event)` runs in the emitting thread and copies what the encoder needs (or returns `None` to skip the event), and `start()`, `frames(snapshot)` and `finish(error)` return `(event name or None, data)` pairs, under the stream's lock.
218
+
219
+ ## Limits
220
+
221
+ - **Frame size.** A frame must fit the publisher's `max_frame_bytes` (64 KiB, or the app's own limit). Text, reasoning and tool-argument deltas longer than that are split over several frames; a value that cannot be split (a tool result, an error message, a long name) is cut with a marker; a frame that still does not fit is dropped and recorded in `run.errors`. A stream holds at most 10 MiB and lasts at most 30 minutes by default: about 90,000 tokens of answer, since an AG-UI text frame costs about 100 bytes per token.
222
+ - **Tool results are matched by tool, agent and arguments.** CrewAI's tool events carry no tool call id; two concurrent calls of the same tool by the same agent with the same arguments get their results in the order they started.
223
+ - **Models without function calling** stream CrewAI's ReAct text (`Thought:`, `Action:`, `Final Answer:`), published as the model wrote it; the tool call is announced when the tool starts.
224
+ - **Every model call is a message.** A crew with several tasks or agents publishes one assistant message per model call of its agents, intermediate ones included; the `name` of each message is the agent's role (none for a call that names no agent, such as the answer forced at `max_iter`). A CrewAI that does not announce its summary of a full context window publishes that summary too: 1.15.2 makes it, unannounced, when the model refuses a request as too long.
225
+ - **What does not run in the block's context is not published.** Work CrewAI starts is included, nested crews and delegated agents among it. Work your code hands to its own threads or pools is not, wherever they were created (a Python thread does not inherit the context), unless it runs in a copy: `pool.submit(contextvars.copy_context().run, crew.kickoff)`, or `asyncio.to_thread()`, which copies it. Neither is a job handed to another process.
226
+ - **CrewAI's own model calls in a flow method are published**: `@human_feedback(llm=...)` classifies the feedback with a model call inside your method, which the adapter cannot tell from yours.
227
+ - **The sink is not a declared public API of CrewAI**, though its own frame streaming and the AG-UI bridge use it. `transport="bus"` is the fallback for a CrewAI without it: handlers on the global event bus run in a thread pool, after other listeners and out of order, so a writer thread holds each event for 50 ms and releases them in the order they were emitted (by kickoff, then by `emission_sequence`, which restarts at every top-level kickoff; kickoffs are ordered by when their first event was made), and the block's exit waits for the bus to flush. It adds latency and depends on that margin.
228
+
229
+ Not covered: serving HTTP or receiving the user's message, AG-UI's shared state and messages snapshots, resuming a paused flow, memory, knowledge, MCP and A2A events, a task's `human_input=True` (it reads the terminal and emits no event), and the AI SDK's UI message stream, for which CrewAI has no converter.
230
+
231
+ ## Testing your own code
232
+
233
+ `iq_stream.testing.RecordingPublisher` records frames in memory. A crew on a fake model (a `BaseLLM` subclass) runs without network:
234
+
235
+ ```python
236
+ from iq_stream.testing import RecordingPublisher
237
+ from iq_stream_crewai import publish
238
+
239
+
240
+ def test_the_crew_reaches_the_stream() -> None:
241
+ publisher = RecordingPublisher()
242
+ with publish(publisher) as run:
243
+ crew.kickoff(inputs={"question": "What is the capital of France?"})
244
+ assert publisher.outcome == "end"
245
+ assert '"type":"RUN_FINISHED"' in publisher.data[-1]
246
+ assert run.errors == []
247
+ ```
248
+
249
+ ## Requirements
250
+
251
+ - Python 3.10 to 3.13, `crewai` 1.15.2 or later (below 2), `ag-ui-protocol` 1.x, `iq-stream` 0.1.
252
+ - An IQ-Stream server 1.x.
253
+
254
+ ## License
255
+
256
+ MIT
@@ -0,0 +1,226 @@
1
+ # iq-stream-crewai
2
+
3
+ Publishes a [CrewAI](https://github.com/crewAIInc/crewAI) run to browsers through an [IQ-Stream server](https://github.com/neuron-core/iq-stream). Everything CrewAI emits inside a `with publish(...)` block (the model's tokens, tool calls and their results, tasks, flow steps) goes to one stream as it happens, as [AG-UI](https://docs.ag-ui.com) events by default or as CrewAI's own events. The block closes the stream with `end` when it exits normally and with `fail` when it raises. The browser reads the stream with `StreamAgent` from [`@neuron-core/iq-stream`](https://www.npmjs.com/package/@neuron-core/iq-stream), or with any AG-UI client.
4
+
5
+ It is a thin layer over the core client, [`iq-stream`](https://pypi.org/project/iq-stream/), which owns the connection to the server: one request per answer, keepalives while a tool runs, resuming after a lost request, and the close line.
6
+
7
+ ```sh
8
+ pip install iq-stream-crewai
9
+ ```
10
+
11
+ ## Publish a crew
12
+
13
+ ```python
14
+ from iq_stream import IQClient
15
+ from iq_stream_crewai import publish
16
+
17
+ iq = IQClient() # IQ_STREAM_URL, IQ_STREAM_APP_KEY and IQ_STREAM_APP_SECRET
18
+
19
+
20
+ def answer(stream_id: str, question: str) -> None:
21
+ """Runs where the crew runs: a thread, a task or a queue job."""
22
+ with publish(iq, stream_id): # the request to the server opens now
23
+ result = crew.kickoff(inputs={"question": question})
24
+ save_answer(stream_id, result.raw) # before the close line: a late browser loads it from you
25
+ # the block closes the stream with "end", or with "fail" if it raised
26
+
27
+
28
+ ticket = iq.ticket() # what the browser needs: stream_id, token, url, expires_at
29
+ answer(ticket.stream_id, "What is the capital of France?")
30
+ ```
31
+
32
+ `crew` stands for your crew and `save_answer()` for your own persistence. The block may hold anything that makes CrewAI emit events: `crew.kickoff()`, `flow.kickoff()`, `agent.kickoff()`, several kickoffs, or a `Crew(stream=True)` whose chunks your code iterates itself, inside the block. CrewAI needs to know nothing about the stream: no id goes into `inputs`.
33
+
34
+ The block taps CrewAI through a scoped stream sink, the mechanism CrewAI's own frame streaming is built on. It sees every event emitted in the block's context and in the threads CrewAI starts from it, in the thread that emits it, before any listener of the global event bus: several crews in one process never see each other's events, nothing overtakes an event on its way to the stream, and nothing is left to flush when `kickoff()` returns. Each event is copied, encoded under one lock per stream and handed to the core's `send()`, which only queues.
35
+
36
+ In asyncio, the same object is used with `async with`. The adapter still uses the core's synchronous publisher, because CrewAI emits from worker threads even in `akickoff()`; the closing frames go out before anything is awaited, and the server's answer is awaited in a thread of its own, not in the loop's default executor, where each `kickoff_async()` holds a thread for its whole run.
37
+
38
+ ```python
39
+ import asyncio
40
+
41
+ from iq_stream import IQClient
42
+ from iq_stream_crewai import publish
43
+
44
+ iq = IQClient()
45
+
46
+
47
+ async def answer(stream_id: str, question: str) -> None:
48
+ async with publish(iq, stream_id): # a cancelled task closes the stream with "fail"
49
+ result = await crew.akickoff(inputs={"question": question})
50
+ await asave_answer(stream_id, result.raw)
51
+
52
+
53
+ asyncio.run(answer(iq.new_stream_id(), "What is the capital of France?"))
54
+ ```
55
+
56
+ ### Behind a route
57
+
58
+ CrewAI serves no HTTP of its own; a route starts the run in a worker and answers with the ticket at once. With `StreamAgent` in the browser, the request body is AG-UI's `RunAgentInput`, and the run's `threadId` and `runId` are the client's own:
59
+
60
+ ```python
61
+ from concurrent.futures import ThreadPoolExecutor
62
+
63
+ from ag_ui.core import RunAgentInput
64
+ from fastapi import FastAPI
65
+
66
+ from iq_stream import IQClient
67
+ from iq_stream_crewai import publish
68
+
69
+ app = FastAPI()
70
+ iq = IQClient()
71
+ workers = ThreadPoolExecutor(max_workers=8)
72
+ answers: dict[str, str] = {} # stands for your database
73
+
74
+
75
+ def answer(stream_id: str, run: RunAgentInput) -> None:
76
+ question = next(message.content for message in reversed(run.messages) if message.role == "user")
77
+ with publish(iq, stream_id, thread_id=run.thread_id, run_id=run.run_id):
78
+ result = build_crew().kickoff(inputs={"question": question})
79
+ answers[stream_id] = result.raw
80
+
81
+
82
+ @app.post("/chat")
83
+ def chat(run: RunAgentInput) -> dict[str, str | int]:
84
+ ticket = iq.ticket()
85
+ workers.submit(answer, ticket.stream_id, run)
86
+ return ticket.to_dict() # streamId, token, url, expiresAt
87
+
88
+
89
+ @app.get("/chat/{stream_id}")
90
+ def saved(stream_id: str) -> dict[str, str | None]:
91
+ """What a browser that missed the stream (iq:gone) loads instead."""
92
+ return {"answer": answers.get(stream_id)}
93
+ ```
94
+
95
+ The worker must enter the block within 30 seconds of the browser subscribing, the time a stream waits for its publisher; a queue that can be slower calls `iq.reserve(stream_id)` in the route. The core holds the close line back until the stream is three seconds old (`min_open`), so a browser that subscribes just after a quick answer still receives it.
96
+
97
+ ### CrewAI's own events, and tokens
98
+
99
+ Without streaming on the model, a run publishes its tool calls, tasks and steps, and each answer as one block when the model call returns. `enable_token_streaming()` turns streaming on for the models of crews, agents or models, as `Crew(stream=True)` does inside its kickoff (`LLM(stream=True)` does it for one model). `protocol="crewai"` publishes CrewAI's own events instead of AG-UI's:
100
+
101
+ ```python
102
+ from iq_stream import IQClient
103
+ from iq_stream_crewai import enable_token_streaming, publish
104
+
105
+ iq = IQClient()
106
+ enable_token_streaming(crew)
107
+
108
+ with publish(iq, protocol="crewai") as run: # without a stream id, a new one: run.stream_id
109
+ crew.kickoff(inputs={"question": "What is the capital of France?"})
110
+ print(run.stream_id, run.frames_sent, run.result)
111
+ ```
112
+
113
+ ## What the browser needs
114
+
115
+ With the default protocol the frames are AG-UI events, unnamed, as AG-UI's own SSE encoding writes them. `StreamAgent` from `@neuron-core/iq-stream/ag-ui` is an `AbstractAgent` of `@ag-ui/client` that posts the run's input with your `start()` and reads the events from the ticket's URL, so CopilotKit or any UI built on `@ag-ui/client` uses it as it would an `HttpAgent`:
116
+
117
+ ```ts
118
+ import { StreamAgent } from '@neuron-core/iq-stream/ag-ui';
119
+
120
+ const agent = new StreamAgent({
121
+ start: async (input) =>
122
+ (await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) })).json(),
123
+ });
124
+ await agent.runAgent(); // agent.messages: the assistant's text, its tool calls and their results
125
+ ```
126
+
127
+ A failed or cancelled run reaches the page twice, as `RUN_ERROR` (or `RUN_FINISHED` with the `cancelled` outcome) and then as `iq:fail` with reason `publisher`; `StreamAgent` ends the run once, on the first. A flow paused for human feedback ends with `RUN_FINISHED` and AG-UI's `interrupt` outcome, which `@ag-ui/client` hands to `onRunFinishedEvent` as `outcome: "interrupt"` with the `interrupts`. With `protocol="crewai"` each frame is named after its CrewAI event type, and the page listens for the names it wants: `subscribe(url, handlers, { events: ['llm_stream_chunk', 'tool_usage_finished', …] })` from `@neuron-core/iq-stream/client`. There is no front-end client for CrewAI's native events; the page keeps its own state.
128
+
129
+ ## What is published
130
+
131
+ | CrewAI event | `ag-ui` frames | `crewai` frame members |
132
+ | --- | --- | --- |
133
+ | block entered | `RUN_STARTED` | none |
134
+ | `llm_stream_chunk`, text | `TEXT_MESSAGE_START` (once per model call, `messageId` = its `call_id`, `name` = the agent's role), `TEXT_MESSAGE_CONTENT` | `call_id`, `chunk` |
135
+ | `llm_stream_chunk`, tool call | `TOOL_CALL_START` (`parentMessageId` = the call), `TOOL_CALL_ARGS` | `call_id`, `chunk`, `tool_call` (`id`, `name`, `index`; never the accumulated arguments) |
136
+ | `llm_thinking_chunk` | `REASONING_START`, `REASONING_MESSAGE_START`, `REASONING_MESSAGE_CONTENT`, closed by the call's next event | `call_id`, `chunk` |
137
+ | `llm_call_completed`, `llm_call_failed` | ends what the call left open; a call that streamed nothing and returned text: the whole text message | `call_id`, `finish_reason`, `usage` / `error` |
138
+ | `tool_usage_started` | binds to the streamed call of that tool and agent with the same arguments (else the oldest); a call no model streamed is announced whole | `tool_name`, `tool_args`, `agent_id`, `agent_role`, `task_id` |
139
+ | `tool_usage_finished`, `tool_usage_error` | `TOOL_CALL_RESULT` (`{"error": …}` for an error) | the same, with `output`, `from_cache` / `error` |
140
+ | `task_started`, `task_completed`, `task_failed` | `STEP_STARTED`, `STEP_FINISHED` (`task:<name>`) | `task_id`, `task_name`, `output` / `error` |
141
+ | `method_execution_started`, `_finished`, `_failed` | `STEP_STARTED`, `STEP_FINISHED` (`flow:<method>`) | `flow_name`, `method_name`, `error` |
142
+ | `human_feedback_requested`, `flow_paused` | `CUSTOM` named `crewai.<type>`; a paused flow also makes the run end interrupted | `flow_name`, `method_name`, `message`, `emit`, `request_id` / `flow_id` |
143
+ | `agent_execution_*`, `crew_kickoff_*`, `flow_started`, `flow_finished`, `flow_failed`, `human_feedback_received` | none | their ids (`flow_id` included), names, `output`, `error`, `total_tokens` |
144
+ | block exits | `RUN_FINISHED`; with outcome `interrupt` while a flow is paused, or `cancelled`; or `RUN_ERROR` | none |
145
+
146
+ Every `crewai` frame also has `seq`, the event's `emission_sequence`. Members without a value are left out. An event that is already an AG-UI event (as flows written for `ag-ui-crewai` emit them) is forwarded as it is.
147
+
148
+ What CrewAI does for itself is left out of both protocols:
149
+
150
+ - the flows it runs inside every agent and for memory;
151
+ - its own agents and tasks, with everything they emit: a task's guardrail (the "Guardrail Agent"), an agent's plan (`planning_config`, `reasoning=True`), the planner of `Crew(planning=True)`, memory's saves and searches, knowledge queries;
152
+ - the model calls that name no agent which it makes around an agent's run: memory's analysis, the conversion of an output (`output_pydantic`, `output_json`, `response_format`), and the summary of a context window that is full.
153
+
154
+ Every other model call is published, whoever made it: the agent's own (its final answer forced at `max_iter` included, and those of a model wrapper that does not pass the agent on), and `llm.call()` in the block, in a flow method or in a tool, a flow your tool kicks off included. A model call your task callback makes itself is left out: in CrewAI's events nothing tells it from an output's conversion.
155
+
156
+ ## Which close line
157
+
158
+ - **The block exits normally**: `RUN_FINISHED`, then `end`. Save the answer inside the block, after `kickoff()`: a browser that arrives after the close receives `iq:gone` and loads it from you. CrewAI has finished its own writes (task callbacks, `output_file`, memory) when `kickoff()` returns.
159
+ - **The block raises**: `RUN_ERROR` with `code` `"error"` and the message masked (with `expose_errors=True`, the exception's class and text), then `fail`; the exception goes on unchanged.
160
+ - **The block is cancelled** (`asyncio.CancelledError`, `KeyboardInterrupt`): `RUN_FINISHED` with the `cancelled` outcome, so the page can tell a stop from a failure, then `fail`, or `end` with `close_on_cancel="end"`. Only asyncio runs can be cancelled; a cancelled run leaves CrewAI's worker threads running to completion, and what they emit after the block is not published.
161
+ - **A flow pauses for human feedback** (`@human_feedback` with an asynchronous provider): `kickoff()` returns `HumanFeedbackPending`, the block exits normally, and the stream ends with `end` after a `CUSTOM` `crewai.flow_paused` frame and `RUN_FINISHED` with the `interrupt` outcome: one interrupt per paused flow, whose `id` is the flow's id (what `Flow.from_pending()` takes), `reason` `"human_feedback"` and `message` the flow's question. The resumed flow is a new run on a new stream.
162
+ - **The process dies**: nothing closes the stream; its browsers get `iq:fail` with `publisher_idle` after the server's idle timeout.
163
+
164
+ Publishing never breaks the run. When the publisher gives up (the server refused, or cannot be reached), the adapter stops encoding and the crew goes on; the reason is in `run.publisher.error`. With the client's `on_error="raise"`, the block raises that error when it exits normally, after your code has run. The adapter's own failures, which never leave the sink, are in `run.errors` and logged once per stream, without event data, on the `iq_stream_crewai` logger.
165
+
166
+ ## Reference
167
+
168
+ ```text
169
+ publish(target, stream_id=None, *, protocol="ag-ui", thread_id=None, run_id=None, include=None, exclude=(),
170
+ max_field_bytes=16_384, expose_errors=False, close_on_cancel="fail", transport="auto") -> CrewAIStream
171
+ ```
172
+
173
+ `target` is an `IQClient`, whose publisher for `stream_id` (a new id when `None`) is created when the block is entered, or a synchronous publisher (`PublisherLike`) that the block takes over and closes. `publish()` itself sends nothing.
174
+
175
+ | Option | Default | |
176
+ | --- | --- | --- |
177
+ | `protocol` | `"ag-ui"` | `"ag-ui"`, `"crewai"`, or an `Encoder` of your own. |
178
+ | `thread_id`, `run_id` | the stream id, a new uuid | AG-UI's ids of the run. |
179
+ | `include`, `exclude` | `EVENT_TYPES` | The CrewAI event types the encoder sees. Without `llm_stream_chunk`, each answer is published when its call returns. |
180
+ | `max_field_bytes` | `16_384` | Tool results, task outputs and other text values are cut to this many bytes of UTF-8, at a character's boundary, with a marker (`… [N bytes truncated]`); `None` cuts nothing. |
181
+ | `expose_errors` | `False` | Publish error messages as they are; by default each one is `An error occurred.` |
182
+ | `close_on_cancel` | `"fail"` | The close line after a cancellation (`iq_stream.Outcome`). |
183
+ | `transport` | `"auto"` | `"sink"` (CrewAI's scoped stream sink), or `"bus"` (handlers on the global event bus). `"auto"` takes the sink. |
184
+
185
+ `CrewAIStream` has `stream_id`, `thread_id`, `run_id`, `publisher` (the core's, once entered), `frames_sent`, `errors` and `result` (the core's `PublishResult` once the block has exited), and `send(data, event=None)` for a frame of your own, in order with the run's. `enable_token_streaming(*crews_agents_or_models)` turns streaming on for their models. `EVENT_TYPES` lists the event types the adapter knows.
186
+
187
+ An `Encoder` has four methods: `snapshot(source, event)` runs in the emitting thread and copies what the encoder needs (or returns `None` to skip the event), and `start()`, `frames(snapshot)` and `finish(error)` return `(event name or None, data)` pairs, under the stream's lock.
188
+
189
+ ## Limits
190
+
191
+ - **Frame size.** A frame must fit the publisher's `max_frame_bytes` (64 KiB, or the app's own limit). Text, reasoning and tool-argument deltas longer than that are split over several frames; a value that cannot be split (a tool result, an error message, a long name) is cut with a marker; a frame that still does not fit is dropped and recorded in `run.errors`. A stream holds at most 10 MiB and lasts at most 30 minutes by default: about 90,000 tokens of answer, since an AG-UI text frame costs about 100 bytes per token.
192
+ - **Tool results are matched by tool, agent and arguments.** CrewAI's tool events carry no tool call id; two concurrent calls of the same tool by the same agent with the same arguments get their results in the order they started.
193
+ - **Models without function calling** stream CrewAI's ReAct text (`Thought:`, `Action:`, `Final Answer:`), published as the model wrote it; the tool call is announced when the tool starts.
194
+ - **Every model call is a message.** A crew with several tasks or agents publishes one assistant message per model call of its agents, intermediate ones included; the `name` of each message is the agent's role (none for a call that names no agent, such as the answer forced at `max_iter`). A CrewAI that does not announce its summary of a full context window publishes that summary too: 1.15.2 makes it, unannounced, when the model refuses a request as too long.
195
+ - **What does not run in the block's context is not published.** Work CrewAI starts is included, nested crews and delegated agents among it. Work your code hands to its own threads or pools is not, wherever they were created (a Python thread does not inherit the context), unless it runs in a copy: `pool.submit(contextvars.copy_context().run, crew.kickoff)`, or `asyncio.to_thread()`, which copies it. Neither is a job handed to another process.
196
+ - **CrewAI's own model calls in a flow method are published**: `@human_feedback(llm=...)` classifies the feedback with a model call inside your method, which the adapter cannot tell from yours.
197
+ - **The sink is not a declared public API of CrewAI**, though its own frame streaming and the AG-UI bridge use it. `transport="bus"` is the fallback for a CrewAI without it: handlers on the global event bus run in a thread pool, after other listeners and out of order, so a writer thread holds each event for 50 ms and releases them in the order they were emitted (by kickoff, then by `emission_sequence`, which restarts at every top-level kickoff; kickoffs are ordered by when their first event was made), and the block's exit waits for the bus to flush. It adds latency and depends on that margin.
198
+
199
+ Not covered: serving HTTP or receiving the user's message, AG-UI's shared state and messages snapshots, resuming a paused flow, memory, knowledge, MCP and A2A events, a task's `human_input=True` (it reads the terminal and emits no event), and the AI SDK's UI message stream, for which CrewAI has no converter.
200
+
201
+ ## Testing your own code
202
+
203
+ `iq_stream.testing.RecordingPublisher` records frames in memory. A crew on a fake model (a `BaseLLM` subclass) runs without network:
204
+
205
+ ```python
206
+ from iq_stream.testing import RecordingPublisher
207
+ from iq_stream_crewai import publish
208
+
209
+
210
+ def test_the_crew_reaches_the_stream() -> None:
211
+ publisher = RecordingPublisher()
212
+ with publish(publisher) as run:
213
+ crew.kickoff(inputs={"question": "What is the capital of France?"})
214
+ assert publisher.outcome == "end"
215
+ assert '"type":"RUN_FINISHED"' in publisher.data[-1]
216
+ assert run.errors == []
217
+ ```
218
+
219
+ ## Requirements
220
+
221
+ - Python 3.10 to 3.13, `crewai` 1.15.2 or later (below 2), `ag-ui-protocol` 1.x, `iq-stream` 0.1.
222
+ - An IQ-Stream server 1.x.
223
+
224
+ ## License
225
+
226
+ MIT
@@ -0,0 +1,108 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "iq-stream-crewai"
7
+ version = "0.1.0"
8
+ description = "Publish a CrewAI run to browsers through an IQ-Stream server, as AG-UI events or CrewAI's own"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ # CrewAI's own range (crewai 1.15: >=3.10,<3.14).
13
+ requires-python = ">=3.10,<3.14"
14
+ authors = [{ name = "Neuron Core" }]
15
+ keywords = ["crewai", "ag-ui", "sse", "server-sent-events", "streaming", "agents", "iq-stream"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Framework :: AsyncIO",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Internet :: WWW/HTTP",
28
+ "Topic :: Software Development :: Libraries",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = [
32
+ "iq-stream>=0.1.0,<0.2",
33
+ # 1.15.2 is the first release with crewai.events.stream_context.
34
+ "crewai>=1.15.2,<2",
35
+ # The pydantic models of AG-UI events, which is the default protocol.
36
+ "ag-ui-protocol>=1.0,<2",
37
+ ]
38
+
39
+ [project.urls]
40
+ Repository = "https://github.com/neuron-core/iq-stream-python"
41
+ Source = "https://github.com/neuron-core/iq-stream-python/tree/main/packages/iq-stream-crewai"
42
+ Issues = "https://github.com/neuron-core/iq-stream-python/issues"
43
+
44
+ [dependency-groups]
45
+ dev = [
46
+ "pytest>=8",
47
+ "pytest-asyncio>=1.0",
48
+ "ruff",
49
+ "pyright",
50
+ # The server-route example of the README, run over HTTP by the integration tests.
51
+ "fastapi>=0.115",
52
+ "uvicorn>=0.30",
53
+ ]
54
+
55
+ # uv.lock holds the versions the plan was researched against (crewai 1.15.41, ag-ui-protocol 1.0.0), locked with
56
+ # `uv lock --upgrade-package`: a constraint here would also bind `uv pip install`, which the floor run needs.
57
+ [tool.uv]
58
+ constraint-dependencies = [
59
+ # chromadb's, through CrewAI: 1.24 declares Python 3.10 but publishes no wheel for it.
60
+ "onnxruntime<1.24 ; python_full_version < '3.11'",
61
+ ]
62
+
63
+ [tool.uv.sources]
64
+ iq-stream = { path = "../iq-stream", editable = true }
65
+
66
+ # The lowest versions of the ranges above, which CI installs over the lockfile to run the unit tests on Python 3.10.
67
+ [tool.iq-stream]
68
+ floor = ["crewai==1.15.2", "ag-ui-protocol==1.0.0"]
69
+
70
+ [tool.hatch.build.targets.wheel]
71
+ packages = ["src/iq_stream_crewai"]
72
+
73
+ # The tests need the repository (its servers and the core), and the lockfile is for development: neither ships.
74
+ [tool.hatch.build.targets.sdist]
75
+ only-include = ["src/iq_stream_crewai", "README.md", "LICENSE", "pyproject.toml"]
76
+
77
+ [tool.pytest.ini_options]
78
+ asyncio_mode = "auto"
79
+ asyncio_default_fixture_loop_scope = "function"
80
+ testpaths = ["tests/unit"]
81
+ filterwarnings = [
82
+ "error",
83
+ # CrewAI's own, at import: crewai.rag refuses the attribute Python sets for a child module.
84
+ "ignore:Cannot set an attribute on 'crewai.rag':ImportWarning",
85
+ # CrewAI reading its own deprecated fields.
86
+ "ignore:function_calling_llm is deprecated:DeprecationWarning:crewai",
87
+ "ignore:deprecated:DeprecationWarning:crewai",
88
+ # CrewAI's memory on Python 3.12 and later, partly through its models' default factories, which pydantic calls.
89
+ "ignore:datetime.datetime.utcnow:DeprecationWarning:(crewai|pydantic)",
90
+ # CrewAI 1.15.2, the lowest supported, leaves connections to its own sqlite databases open; Python 3.13 warns
91
+ # when one is collected.
92
+ "ignore:unclosed database in <sqlite3.Connection object:ResourceWarning",
93
+ "ignore:Exception ignored in. <sqlite3.Connection object:pytest.PytestUnraisableExceptionWarning",
94
+ # The opentelemetry-api CrewAI 1.15.2 pins, on Python 3.10, reading entry points the way 3.10 deprecates.
95
+ "ignore:SelectableGroups dict interface is deprecated:DeprecationWarning:opentelemetry",
96
+ ]
97
+
98
+ [tool.ruff]
99
+ line-length = 120
100
+ target-version = "py310"
101
+
102
+ [tool.ruff.lint]
103
+ select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF", "ASYNC"]
104
+
105
+ [tool.pyright]
106
+ include = ["src"]
107
+ typeCheckingMode = "strict"
108
+ pythonVersion = "3.10"