ag-ui-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,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: ag-ui-crewai
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author: Markus Ecker
6
+ Author-email: markus.ecker@gmail.com
7
+ Requires-Python: >=3.10,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Dist: ag-ui-protocol (==0.1.5)
13
+ Requires-Dist: crewai (>=0.130.0,<0.131.0)
14
+ Requires-Dist: fastapi (>=0.115.12,<0.116.0)
15
+ Requires-Dist: uvicorn (>=0.34.3,<0.35.0)
16
+ Description-Content-Type: text/markdown
17
+
18
+
File without changes
@@ -0,0 +1,18 @@
1
+ from .endpoint import add_crewai_flow_fastapi_endpoint
2
+ from .sdk import (
3
+ CopilotKitState,
4
+ copilotkit_predict_state,
5
+ copilotkit_emit_state,
6
+ copilotkit_stream
7
+ )
8
+ from .enterprise import CrewEnterpriseEventListener
9
+
10
+ CREW_ENTERPRISE_EVENT_LISTENER = CrewEnterpriseEventListener()
11
+
12
+ __all__ = [
13
+ "add_crewai_flow_fastapi_endpoint",
14
+ "CopilotKitState",
15
+ "copilotkit_predict_state",
16
+ "copilotkit_emit_state",
17
+ "copilotkit_stream"
18
+ ]
@@ -0,0 +1,7 @@
1
+ import contextvars
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from crewai.flow.flow import Flow
6
+
7
+ flow_context: contextvars.ContextVar['Flow'] = contextvars.ContextVar('flow')
@@ -0,0 +1,152 @@
1
+ import uuid
2
+ import copy
3
+ import json
4
+ from typing import Any, cast
5
+ from crewai import Crew, Flow
6
+ from crewai.flow import start
7
+ from crewai.cli.crew_chat import (
8
+ initialize_chat_llm as crew_chat_initialize_chat_llm,
9
+ generate_crew_chat_inputs as crew_chat_generate_crew_chat_inputs,
10
+ generate_crew_tool_schema as crew_chat_generate_crew_tool_schema,
11
+ build_system_message as crew_chat_build_system_message,
12
+ create_tool_function as crew_chat_create_tool_function
13
+ )
14
+ from litellm import completion
15
+ from .sdk import (
16
+ copilotkit_stream,
17
+ copilotkit_exit,
18
+ )
19
+
20
+ _CREW_INPUTS_CACHE = {}
21
+
22
+
23
+ CREW_EXIT_TOOL = {
24
+ "type": "function",
25
+ "function": {
26
+ "name": "crew_exit",
27
+ "description": "Call this when the user has indicated that they are done with the crew",
28
+ "parameters": {
29
+ "type": "object",
30
+ "properties": {},
31
+ "required": [],
32
+ },
33
+ },
34
+ }
35
+
36
+
37
+ class ChatWithCrewFlow(Flow):
38
+ """Chat with crew"""
39
+
40
+ def __init__(
41
+ self, *,
42
+ crew: Crew
43
+ ):
44
+ super().__init__()
45
+
46
+
47
+ self.crew = copy.deepcopy(cast(Any, crew).crew())
48
+
49
+ if self.crew.chat_llm is None:
50
+ raise ValueError("Crew chat LLM is not set")
51
+
52
+ self.crew_name = crew.name
53
+ self.chat_llm = crew_chat_initialize_chat_llm(self.crew)
54
+
55
+ if crew.name not in _CREW_INPUTS_CACHE:
56
+ self.crew_chat_inputs = crew_chat_generate_crew_chat_inputs(
57
+ self.crew,
58
+ self.crew_name,
59
+ self.chat_llm
60
+ )
61
+ _CREW_INPUTS_CACHE[ crew.name] = self.crew_chat_inputs
62
+ else:
63
+ self.crew_chat_inputs = _CREW_INPUTS_CACHE[ crew.name]
64
+
65
+ self.crew_tool_schema = crew_chat_generate_crew_tool_schema(self.crew_chat_inputs)
66
+ self.system_message = crew_chat_build_system_message(self.crew_chat_inputs)
67
+
68
+ super().__init__()
69
+
70
+ @start()
71
+ async def chat(self):
72
+ """Chat with the crew"""
73
+
74
+ system_message = self.system_message
75
+ if self.state.get("inputs"):
76
+ system_message += "\n\nCurrent inputs: " + json.dumps(self.state["inputs"])
77
+
78
+ messages = [
79
+ {
80
+ "role": "system",
81
+ "content": system_message,
82
+ "id": str(uuid.uuid4()) + "-system"
83
+ },
84
+ *self.state["messages"]
85
+ ]
86
+
87
+ tools = [action for action in self.state["copilotkit"]["actions"]
88
+ if action["function"]["name"] != self.crew_name]
89
+
90
+ tools += [self.crew_tool_schema, CREW_EXIT_TOOL]
91
+
92
+ response = await copilotkit_stream(
93
+ completion(
94
+ model=self.crew.chat_llm,
95
+ messages=messages,
96
+ tools=tools,
97
+ parallel_tool_calls=False,
98
+ stream=True
99
+ )
100
+ )
101
+
102
+ message = cast(Any, response).choices[0]["message"]
103
+ self.state["messages"].append(message)
104
+
105
+ if message.get("tool_calls"):
106
+ if message["tool_calls"][0]["function"]["name"] == self.crew_name:
107
+ # run the crew
108
+ crew_function = crew_chat_create_tool_function(self.crew, messages)
109
+ args = json.loads(message["tool_calls"][0]["function"]["arguments"])
110
+ result = crew_function(**args)
111
+
112
+ if isinstance(result, str):
113
+ self.state["outputs"] = result
114
+ elif hasattr(result, "json_dict"):
115
+ self.state["outputs"] = result.json_dict
116
+ elif hasattr(result, "raw"):
117
+ self.state["outputs"] = result.raw
118
+ else:
119
+ raise ValueError("Unexpected result type", type(result))
120
+
121
+ self.state["messages"].append({
122
+ "role": "tool",
123
+ "content": result,
124
+ "tool_call_id": message["tool_calls"][0]["id"]
125
+ })
126
+ elif message["tool_calls"][0]["function"]["name"] == CREW_EXIT_TOOL["function"]["name"]:
127
+ await copilotkit_exit()
128
+ self.state["messages"].append({
129
+ "role": "tool",
130
+ "content": "Crew exited",
131
+ "tool_call_id": message["tool_calls"][0]["id"]
132
+ })
133
+
134
+ response = await copilotkit_stream(
135
+ completion( # pylint: disable=too-many-arguments
136
+ model=self.crew.chat_llm,
137
+ messages = [
138
+ {
139
+ "role": "system",
140
+ "content": "Indicate to the user that the crew has exited",
141
+ "id": str(uuid.uuid4()) + "-system"
142
+ },
143
+ *self.state["messages"]
144
+ ],
145
+ tools=tools,
146
+ parallel_tool_calls=False,
147
+ stream=True,
148
+ tool_choice="none"
149
+ )
150
+ )
151
+ message = cast(Any, response).choices[0]["message"]
152
+ self.state["messages"].append(message)
@@ -0,0 +1,236 @@
1
+ """
2
+ AG-UI FastAPI server for CrewAI.
3
+ """
4
+ import copy
5
+ import asyncio
6
+ from typing import List
7
+ from fastapi import FastAPI, Request
8
+ from fastapi.responses import StreamingResponse
9
+
10
+ from crewai.utilities.events import (
11
+ crewai_event_bus,
12
+ FlowStartedEvent,
13
+ FlowFinishedEvent,
14
+ MethodExecutionStartedEvent,
15
+ MethodExecutionFinishedEvent,
16
+ )
17
+ from crewai.flow.flow import Flow
18
+ from crewai import Crew
19
+
20
+ from ag_ui.core import (
21
+ RunAgentInput,
22
+ EventType,
23
+ RunStartedEvent,
24
+ RunFinishedEvent,
25
+ RunErrorEvent,
26
+ Message,
27
+ Tool
28
+ )
29
+ from ag_ui.core.events import (
30
+ TextMessageChunkEvent,
31
+ ToolCallChunkEvent,
32
+ StepStartedEvent,
33
+ StepFinishedEvent,
34
+ MessagesSnapshotEvent,
35
+ StateSnapshotEvent,
36
+ CustomEvent,
37
+ )
38
+ from ag_ui.encoder import EventEncoder
39
+
40
+ from .events import (
41
+ BridgedTextMessageChunkEvent,
42
+ BridgedToolCallChunkEvent,
43
+ BridgedCustomEvent,
44
+ BridgedStateSnapshotEvent
45
+ )
46
+ from .context import flow_context
47
+ from .sdk import litellm_messages_to_ag_ui_messages
48
+ from .crews import ChatWithCrewFlow
49
+
50
+
51
+ def add_crewai_flow_fastapi_endpoint(app: FastAPI, flow: Flow, path: str = "/"):
52
+ """Adds a CrewAI endpoint to the FastAPI app."""
53
+
54
+
55
+ @app.post(path)
56
+ async def agentic_chat_endpoint(input_data: RunAgentInput, request: Request):
57
+ """Agentic chat endpoint"""
58
+
59
+ flow_copy = copy.deepcopy(flow)
60
+
61
+ # Get the accept header from the request
62
+ accept_header = request.headers.get("accept")
63
+
64
+ # Create an event encoder to properly format SSE events
65
+ encoder = EventEncoder(accept=accept_header)
66
+
67
+ inputs = crewai_prepare_inputs(
68
+ state=input_data.state,
69
+ messages=input_data.messages,
70
+ tools=input_data.tools,
71
+ )
72
+
73
+ async def event_generator():
74
+ queue = asyncio.Queue()
75
+ token = flow_context.set(flow_copy)
76
+ try:
77
+ with crewai_event_bus.scoped_handlers():
78
+
79
+ @crewai_event_bus.on(FlowStartedEvent)
80
+ def _(source, event): # pylint: disable=unused-argument
81
+ if source == flow_copy:
82
+ queue.put_nowait(
83
+ RunStartedEvent(
84
+ type=EventType.RUN_STARTED,
85
+ thread_id=input_data.thread_id,
86
+ run_id=input_data.run_id,
87
+ ),
88
+ )
89
+
90
+ @crewai_event_bus.on(FlowFinishedEvent)
91
+ def _(source, event): # pylint: disable=unused-argument
92
+ if source == flow_copy:
93
+ queue.put_nowait(
94
+ RunFinishedEvent(
95
+ type=EventType.RUN_FINISHED,
96
+ thread_id=input_data.thread_id,
97
+ run_id=input_data.run_id,
98
+ ),
99
+ )
100
+ queue.put_nowait(None)
101
+
102
+ @crewai_event_bus.on(MethodExecutionStartedEvent)
103
+ def _(source, event):
104
+ if source == flow_copy:
105
+ queue.put_nowait(
106
+ StepStartedEvent(
107
+ type=EventType.STEP_STARTED,
108
+ step_name=event.method_name
109
+ )
110
+ )
111
+
112
+ @crewai_event_bus.on(MethodExecutionFinishedEvent)
113
+ def _(source, event):
114
+ if source == flow_copy:
115
+ messages = litellm_messages_to_ag_ui_messages(source.state.messages)
116
+
117
+ queue.put_nowait(
118
+ MessagesSnapshotEvent(
119
+ type=EventType.MESSAGES_SNAPSHOT,
120
+ messages=messages
121
+ )
122
+ )
123
+ queue.put_nowait(
124
+ StateSnapshotEvent(
125
+ type=EventType.STATE_SNAPSHOT,
126
+ snapshot=source.state
127
+ )
128
+ )
129
+ queue.put_nowait(
130
+ StepFinishedEvent(
131
+ type=EventType.STEP_FINISHED,
132
+ step_name=event.method_name
133
+ )
134
+ )
135
+
136
+ @crewai_event_bus.on(BridgedTextMessageChunkEvent)
137
+ def _(source, event):
138
+ if source == flow_copy:
139
+ queue.put_nowait(
140
+ TextMessageChunkEvent(
141
+ type=EventType.TEXT_MESSAGE_CHUNK,
142
+ message_id=event.message_id,
143
+ role=event.role,
144
+ delta=event.delta,
145
+ )
146
+ )
147
+
148
+ @crewai_event_bus.on(BridgedToolCallChunkEvent)
149
+ def _(source, event):
150
+ if source == flow_copy:
151
+ queue.put_nowait(
152
+ ToolCallChunkEvent(
153
+ type=EventType.TOOL_CALL_CHUNK,
154
+ tool_call_id=event.tool_call_id,
155
+ tool_call_name=event.tool_call_name,
156
+ delta=event.delta,
157
+ )
158
+ )
159
+
160
+ @crewai_event_bus.on(BridgedCustomEvent)
161
+ def _(source, event):
162
+ if source == flow_copy:
163
+ queue.put_nowait(
164
+ CustomEvent(
165
+ type=EventType.CUSTOM,
166
+ name=event.name,
167
+ value=event.value
168
+ )
169
+ )
170
+
171
+ @crewai_event_bus.on(BridgedStateSnapshotEvent)
172
+ def _(source, event):
173
+ if source == flow_copy:
174
+ queue.put_nowait(
175
+ StateSnapshotEvent(
176
+ type=EventType.STATE_SNAPSHOT,
177
+ snapshot=event.snapshot
178
+ )
179
+ )
180
+
181
+ asyncio.create_task(flow_copy.kickoff_async(inputs=inputs))
182
+
183
+ while True:
184
+ item = await queue.get()
185
+ if item is None:
186
+ break
187
+ yield encoder.encode(item)
188
+
189
+ except Exception as e: # pylint: disable=broad-exception-caught
190
+ yield encoder.encode(
191
+ RunErrorEvent(
192
+ type=EventType.RUN_ERROR,
193
+ thread_id=input_data.thread_id,
194
+ run_id=input_data.run_id,
195
+ error=str(e),
196
+ )
197
+ )
198
+ finally:
199
+ flow_context.reset(token)
200
+
201
+ return StreamingResponse(event_generator(), media_type=encoder.get_content_type())
202
+
203
+ def add_crewai_crew_fastapi_endpoint(app: FastAPI, crew: Crew, path: str = "/"):
204
+ """Adds a CrewAI crew endpoint to the FastAPI app."""
205
+ add_crewai_flow_fastapi_endpoint(app, ChatWithCrewFlow(crew=crew), path)
206
+
207
+
208
+ def crewai_prepare_inputs( # pylint: disable=unused-argument, too-many-arguments
209
+ *,
210
+ state: dict,
211
+ messages: List[Message],
212
+ tools: List[Tool],
213
+ ):
214
+ """Default merge state for CrewAI"""
215
+ messages = [message.model_dump() for message in messages]
216
+
217
+ if len(messages) > 0:
218
+ if "role" in messages[0] and messages[0]["role"] == "system":
219
+ messages = messages[1:]
220
+
221
+ actions = [{
222
+ "type": "function",
223
+ "function": {
224
+ **tool.model_dump(),
225
+ }
226
+ } for tool in tools]
227
+
228
+ new_state = {
229
+ **state,
230
+ "messages": messages,
231
+ "copilotkit": {
232
+ "actions": actions
233
+ }
234
+ }
235
+
236
+ return new_state
@@ -0,0 +1,163 @@
1
+ from typing import Literal, List, Any
2
+ from crewai.utilities.events import (
3
+ FlowStartedEvent,
4
+ FlowFinishedEvent,
5
+ MethodExecutionStartedEvent,
6
+ MethodExecutionFinishedEvent
7
+ )
8
+ from crewai.utilities.events.base_event_listener import BaseEventListener
9
+ from crewai.utilities.events.base_events import BaseEvent
10
+
11
+ from ag_ui.core import EventType, Message, State
12
+
13
+ from .sdk import (
14
+ litellm_messages_to_ag_ui_messages,
15
+ BridgedTextMessageChunkEvent,
16
+ BridgedToolCallChunkEvent,
17
+ BridgedCustomEvent,
18
+ BridgedStateSnapshotEvent,
19
+ )
20
+
21
+ class EnterpriseRunStartedEvent(BaseEvent):
22
+ """Enterprise run started event"""
23
+ type: Literal[EventType.RUN_STARTED]
24
+
25
+ class EnterpriseRunFinishedEvent(BaseEvent):
26
+ """Enterprise run finished event"""
27
+ type: Literal[EventType.RUN_FINISHED]
28
+
29
+ class EnterpriseStepStartedEvent(BaseEvent):
30
+ """Enterprise step started event"""
31
+ type: Literal[EventType.STEP_STARTED]
32
+
33
+ class EnterpriseStepFinishedEvent(BaseEvent):
34
+ """Enterprise step finished event"""
35
+ type: Literal[EventType.STEP_FINISHED]
36
+
37
+ class EnterpriseMessagesSnapshotEvent(BaseEvent):
38
+ """Enterprise messages snapshot event"""
39
+ type: Literal[EventType.MESSAGES_SNAPSHOT]
40
+ messages: List[Message]
41
+
42
+ class EnterpriseStateSnapshotEvent(BaseEvent):
43
+ """Enterprise state snapshot event"""
44
+ type: Literal[EventType.STATE_SNAPSHOT]
45
+ snapshot: State
46
+
47
+ class EnterpriseTextMessageChunkEvent(BaseEvent):
48
+ """Enterprise text message chunk event"""
49
+ type: Literal[EventType.TEXT_MESSAGE_CHUNK]
50
+ message_id: str
51
+ role: Literal["assistant"]
52
+ delta: str
53
+
54
+ class EnterpriseToolCallChunkEvent(BaseEvent):
55
+ """Enterprise tool call chunk event"""
56
+ type: Literal[EventType.TOOL_CALL_CHUNK]
57
+ tool_call_id: str
58
+ tool_call_name: str
59
+ delta: str
60
+
61
+ class EnterpriseCustomEvent(BaseEvent):
62
+ """Enterprise custom event"""
63
+ type: Literal[EventType.CUSTOM]
64
+ name: str
65
+ value: Any
66
+
67
+ class CrewEnterpriseEventListener(BaseEventListener):
68
+ """
69
+ This class is used to produce custom events when running a crewai flow on CrewAI Enterprise.
70
+ NOTE: These listeners only fire when the Flow is not run on enterprise.
71
+ """
72
+ def setup_listeners(self, crewai_event_bus):
73
+ @crewai_event_bus.on(FlowStartedEvent)
74
+ def _(source, event): # pylint: disable=unused-argument
75
+ crewai_event_bus.emit(
76
+ EnterpriseRunStartedEvent(
77
+ type=EventType.RUN_STARTED
78
+ )
79
+ )
80
+
81
+ @crewai_event_bus.on(FlowFinishedEvent)
82
+ def _(source, event): # pylint: disable=unused-argument
83
+ crewai_event_bus.emit(
84
+ EnterpriseRunFinishedEvent(
85
+ type=EventType.RUN_FINISHED
86
+ )
87
+ )
88
+
89
+ @crewai_event_bus.on(MethodExecutionStartedEvent)
90
+ def _(source, event): # pylint: disable=unused-argument
91
+ crewai_event_bus.emit(
92
+ EnterpriseStepStartedEvent(
93
+ type=EventType.STEP_STARTED,
94
+ step_name=event.method_name
95
+ )
96
+ )
97
+
98
+ @crewai_event_bus.on(MethodExecutionFinishedEvent)
99
+ def _(source, event):
100
+ messages = litellm_messages_to_ag_ui_messages(source.state.messages)
101
+
102
+ crewai_event_bus.emit(
103
+ EnterpriseMessagesSnapshotEvent(
104
+ type=EventType.MESSAGES_SNAPSHOT,
105
+ messages=messages
106
+ )
107
+ )
108
+
109
+ crewai_event_bus.emit(
110
+ EnterpriseStateSnapshotEvent(
111
+ type=EventType.STATE_SNAPSHOT,
112
+ snapshot=source.state
113
+ )
114
+ )
115
+
116
+ crewai_event_bus.emit(
117
+ EnterpriseStepFinishedEvent(
118
+ type=EventType.STEP_FINISHED,
119
+ step_name=event.method_name
120
+ )
121
+ )
122
+
123
+ @crewai_event_bus.on(BridgedTextMessageChunkEvent)
124
+ def _(source, event): # pylint: disable=unused-argument
125
+ crewai_event_bus.emit(
126
+ EnterpriseTextMessageChunkEvent(
127
+ type=EventType.TEXT_MESSAGE_CHUNK,
128
+ message_id=event.message_id,
129
+ role=event.role,
130
+ delta=event.delta
131
+ )
132
+ )
133
+
134
+ @crewai_event_bus.on(BridgedToolCallChunkEvent)
135
+ def _(source, event): # pylint: disable=unused-argument
136
+ crewai_event_bus.emit(
137
+ EnterpriseToolCallChunkEvent(
138
+ type=EventType.TOOL_CALL_CHUNK,
139
+ tool_call_id=event.tool_call_id,
140
+ tool_call_name=event.tool_call_name,
141
+ delta=event.delta
142
+ )
143
+ )
144
+
145
+
146
+ @crewai_event_bus.on(BridgedCustomEvent)
147
+ def _(source, event): # pylint: disable=unused-argument
148
+ crewai_event_bus.emit(
149
+ EnterpriseCustomEvent(
150
+ type=EventType.CUSTOM,
151
+ name=event.name,
152
+ value=event.value
153
+ )
154
+ )
155
+
156
+ @crewai_event_bus.on(BridgedStateSnapshotEvent)
157
+ def _(source, event): # pylint: disable=unused-argument
158
+ crewai_event_bus.emit(
159
+ EnterpriseStateSnapshotEvent(
160
+ type=EventType.STATE_SNAPSHOT,
161
+ snapshot=event.snapshot
162
+ )
163
+ )
@@ -0,0 +1,23 @@
1
+ """
2
+ This file is used to bridge the events from the crewai event bus to the ag-ui event bus.
3
+ """
4
+
5
+ from crewai.utilities.events.base_events import BaseEvent
6
+ from ag_ui.core.events import (
7
+ ToolCallChunkEvent,
8
+ TextMessageChunkEvent,
9
+ CustomEvent,
10
+ StateSnapshotEvent
11
+ )
12
+
13
+ class BridgedToolCallChunkEvent(BaseEvent, ToolCallChunkEvent):
14
+ """Bridged tool call chunk event"""
15
+
16
+ class BridgedTextMessageChunkEvent(BaseEvent, TextMessageChunkEvent):
17
+ """Bridged text message chunk event"""
18
+
19
+ class BridgedCustomEvent(BaseEvent, CustomEvent):
20
+ """Bridged custom event"""
21
+
22
+ class BridgedStateSnapshotEvent(BaseEvent, StateSnapshotEvent):
23
+ """Bridged state snapshot event"""
@@ -0,0 +1,338 @@
1
+ """
2
+ This is a placeholder for the copilotkit_stream function.
3
+ """
4
+
5
+ import uuid
6
+ from typing import List, Any, Optional, Mapping, Dict, Literal, TypedDict
7
+ from litellm.types.utils import (
8
+ ModelResponse,
9
+ Choices,
10
+ Message as LiteLLMMessage,
11
+ ChatCompletionMessageToolCall,
12
+ Function as LiteLLMFunction
13
+ )
14
+ from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
15
+ from crewai.flow.flow import FlowState
16
+ from crewai.utilities.events import crewai_event_bus
17
+ from pydantic import BaseModel, Field, TypeAdapter
18
+ from ag_ui.core import EventType, Message
19
+ from .context import flow_context
20
+ from .events import (
21
+ BridgedTextMessageChunkEvent,
22
+ BridgedToolCallChunkEvent,
23
+ BridgedCustomEvent,
24
+ BridgedStateSnapshotEvent
25
+ )
26
+ from .utils import yield_control
27
+
28
+ class CopilotKitProperties(BaseModel):
29
+ """CopilotKit properties"""
30
+ actions: List[Any] = Field(default_factory=list)
31
+
32
+ class CopilotKitState(FlowState):
33
+ """CopilotKit state"""
34
+ messages: List[Any] = Field(default_factory=list)
35
+ copilotkit: CopilotKitProperties = Field(default_factory=CopilotKitProperties)
36
+
37
+ class PredictStateConfig(TypedDict):
38
+ """
39
+ Predict State Config
40
+ """
41
+ tool_name: str
42
+ tool_argument: Optional[str]
43
+
44
+ async def copilotkit_predict_state(
45
+ config: Dict[str, PredictStateConfig]
46
+ ) -> Literal[True]:
47
+ """
48
+ Stream tool calls as state to CopilotKit.
49
+
50
+ To emit a tool call as streaming CrewAI state, pass the destination key in state,
51
+ the tool name and optionally the tool argument. (If you don't pass the argument name,
52
+ all arguments are emitted under the state key.)
53
+
54
+ ```python
55
+ from copilotkit.crewai import copilotkit_predict_state
56
+
57
+ await copilotkit_predict_state(
58
+ {
59
+ "steps": {
60
+ "tool": "SearchTool",
61
+ "tool_argument": "steps",
62
+ },
63
+ }
64
+ )
65
+ ```
66
+
67
+ Parameters
68
+ ----------
69
+ config : Dict[str, CopilotKitPredictStateConfig]
70
+ The configuration to predict the state.
71
+
72
+ Returns
73
+ -------
74
+ Awaitable[bool]
75
+ Always return True.
76
+ """
77
+ flow = flow_context.get(None)
78
+
79
+ value = [
80
+ {
81
+ "state_key": k,
82
+ "tool": v["tool_name"],
83
+ "tool_argument": v["tool_argument"]
84
+ } for k, v in config.items()
85
+ ]
86
+ crewai_event_bus.emit(
87
+ flow,
88
+ BridgedCustomEvent(
89
+ type=EventType.CUSTOM,
90
+ name="PredictState",
91
+ value=value
92
+ )
93
+ )
94
+
95
+ await yield_control()
96
+
97
+ return True
98
+
99
+ async def copilotkit_emit_state(state: Any) -> Literal[True]:
100
+ """
101
+ Emits intermediate state to CopilotKit.
102
+ Useful if you have a longer running node and you want to update the user with the current state of the node.
103
+
104
+ To install the CopilotKit SDK, run:
105
+
106
+ ```bash
107
+ pip install copilotkit[crewai]
108
+ ```
109
+
110
+ ### Examples
111
+
112
+ ```python
113
+ from copilotkit.crewai import copilotkit_emit_state
114
+
115
+ for i in range(10):
116
+ await some_long_running_operation(i)
117
+ await copilotkit_emit_state({"progress": i})
118
+ ```
119
+
120
+ Parameters
121
+ ----------
122
+ state : Any
123
+ The state to emit (Must be JSON serializable).
124
+
125
+ Returns
126
+ -------
127
+ Awaitable[bool]
128
+ Always return True.
129
+
130
+ """
131
+ flow = flow_context.get(None)
132
+ crewai_event_bus.emit(
133
+ flow,
134
+ BridgedStateSnapshotEvent(
135
+ type=EventType.STATE_SNAPSHOT,
136
+ snapshot=state
137
+ )
138
+ )
139
+
140
+ await yield_control()
141
+
142
+ return True
143
+
144
+ async def copilotkit_stream(response):
145
+ """
146
+ Stream litellm responses token by token to CopilotKit.
147
+
148
+ ```python
149
+ response = await copilotkit_stream(
150
+ completion(
151
+ model="openai/gpt-4o",
152
+ messages=messages,
153
+ tools=tools,
154
+ stream=True # this must be set to True for streaming
155
+ )
156
+ )
157
+ ```
158
+ """
159
+ if isinstance(response, ModelResponse):
160
+ return _copilotkit_stream_response(response)
161
+ if isinstance(response, CustomStreamWrapper):
162
+ return await _copilotkit_stream_custom_stream_wrapper(response)
163
+ raise ValueError("Invalid response type")
164
+
165
+
166
+ async def _copilotkit_stream_custom_stream_wrapper(response: CustomStreamWrapper):
167
+ flow = flow_context.get(None)
168
+
169
+ message_id: Optional[str] = None
170
+ tool_call_id: str = ""
171
+ content = ""
172
+ created = 0
173
+ model = ""
174
+ system_fingerprint = ""
175
+ finish_reason=None
176
+ all_tool_calls = []
177
+
178
+ async for chunk in response:
179
+ if message_id is None:
180
+ message_id = chunk["id"]
181
+
182
+ text_content = chunk["choices"][0]["delta"]["content"] or None
183
+
184
+ # Stream text messages
185
+ if text_content is not None:
186
+ # add to the current text message
187
+ content += text_content
188
+ crewai_event_bus.emit(
189
+ flow,
190
+ BridgedTextMessageChunkEvent(
191
+ type=EventType.TEXT_MESSAGE_CHUNK,
192
+ message_id=message_id,
193
+ role="assistant",
194
+ delta=text_content,
195
+ )
196
+ )
197
+ # yield control to the event loop
198
+ await yield_control()
199
+
200
+ # Stream tool calls
201
+ tool_calls = chunk["choices"][0]["delta"]["tool_calls"] or None
202
+ tool_call_id = tool_calls[0].id if tool_calls is not None else None
203
+ tool_call_arguments = tool_calls[0].function["arguments"] if tool_calls is not None else None
204
+ tool_call_name = tool_calls[0].function["name"] if tool_calls is not None else None
205
+
206
+ if tool_call_id is not None:
207
+ all_tool_calls.append(
208
+ {
209
+ "id": tool_call_id,
210
+ "name": tool_call_name,
211
+ "arguments": "",
212
+ }
213
+ )
214
+
215
+ if tool_call_arguments is not None:
216
+ # add to the current tool call
217
+ all_tool_calls[-1]["arguments"] += tool_call_arguments
218
+ crewai_event_bus.emit(
219
+ flow,
220
+ BridgedToolCallChunkEvent(
221
+ type=EventType.TOOL_CALL_CHUNK,
222
+ tool_call_id=tool_call_id,
223
+ tool_call_name=tool_call_name,
224
+ delta=tool_call_arguments,
225
+ )
226
+ )
227
+ # yield control to the event loop
228
+ await yield_control()
229
+
230
+ # Stream finish reason
231
+ finish_reason = chunk["choices"][0]["finish_reason"]
232
+ created = chunk["created"]
233
+ model = chunk["model"]
234
+ system_fingerprint = chunk["system_fingerprint"]
235
+
236
+ if finish_reason is not None:
237
+ break
238
+
239
+ tool_calls = [
240
+ ChatCompletionMessageToolCall(
241
+ function=LiteLLMFunction(
242
+ arguments=tool_call["arguments"],
243
+ name=tool_call["name"]
244
+ ),
245
+ id=tool_call["id"],
246
+ type="function"
247
+ )
248
+ for tool_call in all_tool_calls
249
+ ]
250
+ return ModelResponse(
251
+ id=message_id,
252
+ created=created,
253
+ model=model,
254
+ object='chat.completion',
255
+ system_fingerprint=system_fingerprint,
256
+ choices=[
257
+ Choices(
258
+ finish_reason=finish_reason,
259
+ index=0,
260
+ message=LiteLLMMessage(
261
+ content=content,
262
+ role='assistant',
263
+ tool_calls=tool_calls if len(tool_calls) > 0 else None,
264
+ function_call=None
265
+ )
266
+ )
267
+ ]
268
+ )
269
+
270
+ def _copilotkit_stream_response(response: ModelResponse):
271
+ return response
272
+
273
+
274
+ message_adapter = TypeAdapter(Message)
275
+
276
+ def litellm_messages_to_ag_ui_messages(messages: List[LiteLLMMessage]) -> List[Message]:
277
+ """
278
+ Converts a list of LiteLLM messages to a list of ag_ui messages.
279
+ """
280
+ ag_ui_messages: List[Message] = []
281
+ for message in messages:
282
+ message_dict = message.model_dump() if not isinstance(message, Mapping) else message
283
+
284
+ # whitelist the fields we want to keep
285
+ whitelist = ["content", "role", "tool_calls", "id", "name", "tool_call_id"]
286
+ message_dict = {k: v for k, v in message_dict.items() if k in whitelist}
287
+ if not "id" in message_dict:
288
+ message_dict["id"] = str(uuid.uuid4())
289
+ # remove all None values
290
+ message_dict = {k: v for k, v in message_dict.items() if v is not None}
291
+
292
+ if "tool_calls" in message_dict:
293
+ for tool_call in message_dict["tool_calls"]:
294
+ if "type" not in tool_call:
295
+ tool_call["type"] = "function"
296
+
297
+ ag_ui_message = message_adapter.validate_python(message_dict)
298
+ ag_ui_messages.append(ag_ui_message)
299
+
300
+ return ag_ui_messages
301
+
302
+
303
+ async def copilotkit_exit() -> Literal[True]:
304
+ """
305
+ Exits the current agent after the run completes. Calling copilotkit_exit() will
306
+ not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after
307
+ the run completes.
308
+
309
+ ### Examples
310
+
311
+ ```python
312
+ from copilotkit.crewai import copilotkit_exit
313
+
314
+ def my_function():
315
+ await copilotkit_exit()
316
+ return state
317
+ ```
318
+
319
+ Returns
320
+ -------
321
+ Awaitable[bool]
322
+ Always return True.
323
+ """
324
+
325
+ flow = flow_context.get(None)
326
+
327
+ crewai_event_bus.emit(
328
+ flow,
329
+ BridgedCustomEvent(
330
+ type=EventType.CUSTOM,
331
+ name="Exit",
332
+ value=""
333
+ )
334
+ )
335
+
336
+ await yield_control()
337
+
338
+ return True
@@ -0,0 +1,10 @@
1
+ import asyncio
2
+
3
+ async def yield_control():
4
+ """
5
+ Yield control to the event loop.
6
+ """
7
+ loop = asyncio.get_running_loop()
8
+ future = loop.create_future()
9
+ loop.call_soon(future.set_result, None)
10
+ await future
@@ -0,0 +1,24 @@
1
+ [tool.poetry]
2
+ name = "ag-ui-crewai"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Markus Ecker <markus.ecker@gmail.com>"]
6
+ readme = "README.md"
7
+ exclude = [
8
+ "ag_ui_crewai/dojo.py",
9
+ "ag_ui_crewai/examples/**",
10
+ ]
11
+
12
+ [tool.poetry.dependencies]
13
+ python = "<3.14,>=3.10"
14
+ ag-ui-protocol = "==0.1.5"
15
+ fastapi = "^0.115.12"
16
+ uvicorn = "^0.34.3"
17
+ crewai = "^0.130.0"
18
+
19
+ [build-system]
20
+ requires = ["poetry-core"]
21
+ build-backend = "poetry.core.masonry.api"
22
+
23
+ [tool.poetry.scripts]
24
+ dev = "ag_ui_crewai.dojo:main"