forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanggraph_agui_agent.py
More file actions
298 lines (261 loc) · 11.5 KB
/
Copy pathlanggraph_agui_agent.py
File metadata and controls
298 lines (261 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import json
import logging
from typing import Dict, Any, List, Optional, Union, AsyncGenerator
from enum import Enum
from .exc import CopilotKitMisuseError
logger = logging.getLogger(__name__)
from ag_ui_langgraph import LangGraphAgent
from ag_ui.core import (
EventType,
CustomEvent,
TextMessageStartEvent,
TextMessageContentEvent,
TextMessageEndEvent,
ToolCallStartEvent,
ToolCallArgsEvent,
ToolCallEndEvent,
StateSnapshotEvent,
)
from langgraph.graph.state import CompiledStateGraph
from langchain_core.runnables import RunnableConfig
try:
from langchain.schema import BaseMessage
except ImportError:
# Langchain >= 1.0.0
from langchain_core.messages import BaseMessage
class CustomEventNames(Enum):
"""Custom event names for CopilotKit"""
ManuallyEmitMessage = "copilotkit_manually_emit_message"
ManuallyEmitToolCall = "copilotkit_manually_emit_tool_call"
ManuallyEmitState = "copilotkit_manually_emit_intermediate_state"
class LangGraphEventTypes(Enum):
"""LangGraph event types"""
OnChatModelStream = "on_chat_model_stream"
OnCustomEvent = "on_custom_event"
class PredictStateTool:
def __init__(self, tool: str, state_key: str, tool_argument: str):
self.tool = tool
self.state_key = state_key
self.tool_argument = tool_argument
State = Dict[str, Any]
SchemaKeys = Dict[str, List[str]]
TextMessageEvents = Union[
TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEvent
]
ToolCallEvents = Union[ToolCallStartEvent, ToolCallArgsEvent, ToolCallEndEvent]
class LangGraphAGUIAgent(LangGraphAgent):
def __init__(
self,
*,
name: str,
graph: CompiledStateGraph,
description: Optional[str] = None,
config: Union[Optional[RunnableConfig], dict] = None,
):
super().__init__(name=name, graph=graph, description=description, config=config)
self.constant_schema_keys = self.constant_schema_keys + ["copilotkit"]
def _dispatch_event(self, event) -> str:
"""Override the dispatch event method to handle custom CopilotKit events and filtering.
Note: Returns None for filtered events (which violates the str return type annotation,
but the base class also violates it by returning event objects). The None values are
filtered out in run() before reaching the encoder.
"""
if event.type == EventType.CUSTOM:
custom_event = event
if custom_event.name == CustomEventNames.ManuallyEmitMessage.value:
# Emit the message events
super()._dispatch_event(
TextMessageStartEvent(
type=EventType.TEXT_MESSAGE_START,
role="assistant",
message_id=custom_event.value["message_id"],
raw_event=event,
)
)
super()._dispatch_event(
TextMessageContentEvent(
type=EventType.TEXT_MESSAGE_CONTENT,
message_id=custom_event.value["message_id"],
delta=custom_event.value["message"],
raw_event=event,
)
)
super()._dispatch_event(
TextMessageEndEvent(
type=EventType.TEXT_MESSAGE_END,
message_id=custom_event.value["message_id"],
raw_event=event,
)
)
return super()._dispatch_event(event)
if custom_event.name == CustomEventNames.ManuallyEmitToolCall.value:
value = custom_event.value
if not isinstance(value, dict):
raise CopilotKitMisuseError(
f"ManuallyEmitToolCall event 'value' must be a dict, got {type(value).__name__}"
)
tool_call_id = value.get("id")
tool_call_name = value.get("name")
tool_call_args = value.get("args")
if not isinstance(tool_call_id, str) or not tool_call_id.strip():
raise CopilotKitMisuseError(
f"ManuallyEmitToolCall event missing valid 'id': got {type(tool_call_id).__name__}"
)
if not isinstance(tool_call_name, str) or not tool_call_name.strip():
raise CopilotKitMisuseError(
f"ManuallyEmitToolCall event missing valid 'name': got {type(tool_call_name).__name__}"
)
if tool_call_args is None:
raise CopilotKitMisuseError(
f"ManuallyEmitToolCall event missing 'args' for tool_call_id={tool_call_id}"
)
try:
delta = (
tool_call_args
if isinstance(tool_call_args, str)
else json.dumps(tool_call_args)
)
except (TypeError, ValueError) as e:
raise CopilotKitMisuseError(
f"ManuallyEmitToolCall 'args' is not JSON-serializable for tool_call_id={tool_call_id}: {e}"
) from e
dispatched_start = False
end_dispatched = False
try:
super()._dispatch_event(
ToolCallStartEvent(
type=EventType.TOOL_CALL_START,
tool_call_id=tool_call_id,
tool_call_name=tool_call_name,
parent_message_id=tool_call_id,
raw_event=event,
)
)
dispatched_start = True
super()._dispatch_event(
ToolCallArgsEvent(
type=EventType.TOOL_CALL_ARGS,
tool_call_id=tool_call_id,
delta=delta,
raw_event=event,
)
)
super()._dispatch_event(
ToolCallEndEvent(
type=EventType.TOOL_CALL_END,
tool_call_id=tool_call_id,
raw_event=event,
)
)
end_dispatched = True
except Exception:
if dispatched_start and not end_dispatched:
try:
super()._dispatch_event(
ToolCallEndEvent(
type=EventType.TOOL_CALL_END,
tool_call_id=tool_call_id,
raw_event=event,
)
)
except Exception:
logger.error(
"Failed to emit compensating TOOL_CALL_END for %s",
tool_call_id,
exc_info=True,
)
raise
return super()._dispatch_event(event)
if custom_event.name == CustomEventNames.ManuallyEmitState.value:
self.active_run["manually_emitted_state"] = custom_event.value
return super()._dispatch_event(
StateSnapshotEvent(
type=EventType.STATE_SNAPSHOT,
snapshot=self.get_state_snapshot(
self.active_run["manually_emitted_state"]
),
raw_event=event,
)
)
if custom_event.name == "copilotkit_exit":
return super()._dispatch_event(
CustomEvent(
type=EventType.CUSTOM,
name="Exit",
value=True,
raw_event=event,
)
)
# Handle filtering based on metadata for text messages and tool calls
raw_event = getattr(event, "raw_event", None)
if raw_event:
is_message_event = event.type in [
EventType.TEXT_MESSAGE_START,
EventType.TEXT_MESSAGE_CONTENT,
EventType.TEXT_MESSAGE_END,
]
is_tool_event = event.type in [
EventType.TOOL_CALL_START,
EventType.TOOL_CALL_ARGS,
EventType.TOOL_CALL_END,
]
# Handle both dict and object cases for raw_event
# See: https://github.com/CopilotKit/CopilotKit/issues/2066
metadata = (
raw_event.get("metadata", {})
if isinstance(raw_event, dict)
else getattr(raw_event, "metadata", {})
) or {}
if "copilotkit:emit-tool-calls" in metadata:
if metadata["copilotkit:emit-tool-calls"] is False and is_tool_event:
return None # Don't dispatch this event
if "copilotkit:emit-messages" in metadata:
if metadata["copilotkit:emit-messages"] is False and is_message_event:
return None # Don't dispatch this event
return super()._dispatch_event(event)
async def run(self, input):
"""Override run to filter out None events from _dispatch_event filtering."""
async for event in super().run(input):
if event is not None:
yield event
async def _handle_single_event(
self, event: Any, state: State
) -> AsyncGenerator[str, None]:
"""Override to add custom event processing for PredictState events"""
# First, check if this is a raw event that should generate a PredictState event
if event.get("event") == LangGraphEventTypes.OnChatModelStream.value:
predict_state_metadata = event.get("metadata", {}).get(
"copilotkit:emit-intermediate-state", None
)
if predict_state_metadata is not None:
event["metadata"]["predict_state"] = predict_state_metadata
# Call the parent method to handle all other events
async for event_str in super()._handle_single_event(event, state):
yield event_str
def langgraph_default_merge_state(
self, state: State, messages: List[BaseMessage], input: Any
) -> State:
"""Override to add CopilotKit actions to the state"""
merged_state = super().langgraph_default_merge_state(state, messages, input)
# Extract tools from the merged state and add them as CopilotKit actions
agui_properties = merged_state.get("ag-ui", {}) or merged_state
return {
**merged_state,
"copilotkit": {
"actions": [
a.model_dump() if hasattr(a, "model_dump") else a
for a in agui_properties.get("tools", [])
],
"context": [
c.model_dump() if hasattr(c, "model_dump") else c
for c in agui_properties.get("context", [])
],
},
}
def dict_repr(self):
"""Return dictionary representation of the agent"""
return {
"name": self.name,
"description": self.description or "",
"type": "langgraph_agui",
}