-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy path_output.py
More file actions
346 lines (309 loc) · 13.9 KB
/
_output.py
File metadata and controls
346 lines (309 loc) · 13.9 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import json
import logging
import uuid
from dataclasses import asdict, dataclass
from functools import cached_property
from typing import Any, Dict, Optional, Union, cast
from langgraph.types import Interrupt, StateSnapshot
from uipath import UiPath
from uipath._cli._runtime._contracts import (
UiPathApiTrigger,
UiPathErrorCategory,
UiPathResumeTrigger,
UiPathResumeTriggerType,
UiPathRuntimeResult,
UiPathRuntimeStatus,
)
from uipath.models import CreateAction, InvokeProcess, WaitAction, WaitJob
from uipath.models.actions import Action
from ._context import LangGraphRuntimeContext
from ._escalation import Escalation
from ._exception import LangGraphRuntimeError
logger = logging.getLogger(__name__)
@dataclass
class InterruptInfo:
"""Contains all information about an interrupt."""
value: Any
@property
def type(self) -> Optional[UiPathResumeTriggerType]:
"""Returns the type of the interrupt value."""
if isinstance(self.value, CreateAction):
return UiPathResumeTriggerType.ACTION
if isinstance(self.value, WaitAction):
return UiPathResumeTriggerType.ACTION
if isinstance(self.value, InvokeProcess):
return UiPathResumeTriggerType.JOB
if isinstance(self.value, WaitJob):
return UiPathResumeTriggerType.JOB
return None
@property
def identifier(self) -> Optional[str]:
"""Returns the identifier based on the type."""
if isinstance(self.value, Action):
return str(self.value.key)
return None
def serialize(self) -> str:
"""
Converts the interrupt value to a JSON string if possible,
falls back to string representation if not.
"""
try:
if hasattr(self.value, "dict"):
data = self.value.dict()
elif hasattr(self.value, "to_dict"):
data = self.value.to_dict()
elif hasattr(self.value, "__dataclass_fields__"):
data = asdict(self.value)
else:
data = dict(self.value)
return json.dumps(data, default=str)
except (TypeError, ValueError, json.JSONDecodeError):
return str(self.value)
@cached_property
def resume_trigger(self) -> UiPathResumeTrigger:
"""Creates the resume trigger based on interrupt type."""
if self.type is None:
return UiPathResumeTrigger(
api_resume=UiPathApiTrigger(
inbox_id=str(uuid.uuid4()), request=self.serialize()
)
)
else:
return UiPathResumeTrigger(itemKey=self.identifier, triggerType=self.type)
class LangGraphOutputProcessor:
"""
Contains and manages the complete output information from graph execution.
Handles serialization, interrupt data, and file output.
"""
def __init__(self, context: LangGraphRuntimeContext):
"""
Initialize the LangGraphOutputProcessor.
Args:
context: The runtime context for the graph execution.
"""
self.context = context
self._interrupt_info: Optional[InterruptInfo] = None
self._resume_trigger: Optional[UiPathResumeTrigger] = None
# Process interrupt information during initialization
state = cast(StateSnapshot, self.context.state)
if not state or not hasattr(state, "next") or not state.next:
return
for task in state.tasks:
if hasattr(task, "interrupts") and task.interrupts:
for interrupt in task.interrupts:
if isinstance(interrupt, Interrupt):
self._interrupt_info = InterruptInfo(interrupt.value)
self._resume_trigger = self._interrupt_info.resume_trigger
return
@property
def status(self) -> UiPathRuntimeStatus:
"""Determines the execution status based on state."""
return (
UiPathRuntimeStatus.SUSPENDED
if self._interrupt_info
else UiPathRuntimeStatus.SUCCESSFUL
)
@property
def interrupt_value(self) -> Union[Action, InvokeProcess, Any]:
"""Returns the actual value of the interrupt, with its specific type."""
if self.interrupt_info is None:
return None
return self.interrupt_info.value
@property
def interrupt_info(self) -> Optional[InterruptInfo]:
"""Gets interrupt information if available."""
return self._interrupt_info
@property
def resume_trigger(self) -> Optional[UiPathResumeTrigger]:
"""Gets resume trigger if interrupted."""
return self._resume_trigger
@cached_property
def serialized_output(self) -> Dict[str, Any]:
"""Serializes the graph execution result."""
try:
if self.context.output is None:
return {}
return self._serialize_object(self.context.output)
except Exception as e:
raise LangGraphRuntimeError(
"OUTPUT_SERIALIZATION_FAILED",
"Failed to serialize graph output",
f"Error serializing output data: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e
def _serialize_object(self, obj):
"""Recursively serializes an object and all its nested components."""
# Handle Pydantic models
if hasattr(obj, "dict"):
return self._serialize_object(obj.dict())
elif hasattr(obj, "model_dump"):
return self._serialize_object(obj.model_dump(by_alias=True))
elif hasattr(obj, "to_dict"):
return self._serialize_object(obj.to_dict())
# Handle dictionaries
elif isinstance(obj, dict):
return {k: self._serialize_object(v) for k, v in obj.items()}
# Handle lists
elif isinstance(obj, list):
return [self._serialize_object(item) for item in obj]
# Handle other iterable objects (convert to dict first)
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
try:
return self._serialize_object(dict(obj))
except (TypeError, ValueError):
return obj
# Return primitive types as is
else:
return obj
async def process(self) -> UiPathRuntimeResult:
"""
Process the output and prepare the final execution result.
Returns:
UiPathRuntimeResult: The processed execution result.
Raises:
LangGraphRuntimeError: If processing fails.
"""
try:
await self._save_resume_trigger()
return UiPathRuntimeResult(
output=self.serialized_output,
status=self.status,
resume=self.resume_trigger if self.resume_trigger else None,
)
except LangGraphRuntimeError:
raise
except Exception as e:
raise LangGraphRuntimeError(
"OUTPUT_PROCESSING_FAILED",
"Failed to process execution output",
f"Unexpected error during output processing: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e
async def _save_resume_trigger(self) -> None:
"""
Stores the resume trigger in the SQLite database if available.
Raises:
LangGraphRuntimeError: If database operations fail.
"""
if not self.resume_trigger or not self.context.memory:
return
try:
await self.context.memory.setup()
async with (
self.context.memory.lock,
self.context.memory.conn.cursor() as cur,
):
try:
await cur.execute(f"""
CREATE TABLE IF NOT EXISTS {self.context.resume_triggers_table} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
key TEXT,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now', 'utc'))
)
""")
except Exception as e:
raise LangGraphRuntimeError(
"DB_TABLE_CREATION_FAILED",
"Failed to create resume triggers table",
f"Database error while creating table: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e
try:
default_escalation = Escalation()
if default_escalation.enabled and isinstance(
self.interrupt_value, str
):
action = await default_escalation.create(self.interrupt_value)
if action:
self._resume_trigger = UiPathResumeTrigger(
trigger_type=UiPathResumeTriggerType.ACTION,
item_key=action.key,
)
return
if isinstance(self.interrupt_info, InterruptInfo):
uipath_sdk = UiPath()
if self.interrupt_info.type is UiPathResumeTriggerType.JOB:
if isinstance(self.interrupt_value, InvokeProcess):
job = await uipath_sdk.processes.invoke_async(
name=self.interrupt_value.name,
input_arguments=self.interrupt_value.input_arguments,
)
if job:
self._resume_trigger = UiPathResumeTrigger(
trigger_type=UiPathResumeTriggerType.JOB,
item_key=job.key,
)
elif isinstance(self.interrupt_value, WaitJob):
self._resume_trigger = UiPathResumeTrigger(
triggerType=UiPathResumeTriggerType.JOB,
itemKey=self.interrupt_value.job.key,
)
elif self.interrupt_info.type is UiPathResumeTriggerType.ACTION:
if isinstance(self.interrupt_value, CreateAction):
action = uipath_sdk.actions.create(
title=self.interrupt_value.title,
app_name=self.interrupt_value.app_name
if self.interrupt_value.app_name
else "",
app_key=self.interrupt_value.app_key
if self.interrupt_value.app_key
else "",
app_version=self.interrupt_value.app_version
if self.interrupt_value.app_version
else 1,
assignee=self.interrupt_value.assignee
if self.interrupt_value.assignee
else "",
data=self.interrupt_value.data,
)
if action:
self._resume_trigger = UiPathResumeTrigger(
trigger_type=UiPathResumeTriggerType.ACTION,
item_key=action.key,
)
elif isinstance(self.interrupt_value, WaitAction):
self._resume_trigger = UiPathResumeTrigger(
triggerType=UiPathResumeTriggerType.ACTION,
itemKey=self.interrupt_value.action.key,
)
except Exception as e:
raise LangGraphRuntimeError(
"ESCALATION_CREATION_FAILED",
"Failed to create escalation action",
f"Error while creating escalation action: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e
if (
self.resume_trigger.trigger_type.value
== UiPathResumeTriggerType.API.value
and self.resume_trigger.api_resume
):
trigger_key = self.resume_trigger.api_resume.inbox_id
trigger_type = self.resume_trigger.trigger_type.value
else:
trigger_key = self.resume_trigger.item_key
trigger_type = self.resume_trigger.trigger_type.value
try:
logger.debug(f"ResumeTrigger: {trigger_type} {trigger_key}")
await cur.execute(
f"INSERT INTO {self.context.resume_triggers_table} (type, key) VALUES (?, ?)",
(trigger_type, trigger_key),
)
await self.context.memory.conn.commit()
except Exception as e:
raise LangGraphRuntimeError(
"DB_INSERT_FAILED",
"Failed to save resume trigger",
f"Database error while saving resume trigger: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e
except LangGraphRuntimeError:
raise
except Exception as e:
raise LangGraphRuntimeError(
"RESUME_TRIGGER_SAVE_FAILED",
"Failed to save resume trigger",
f"Unexpected error while saving resume trigger: {str(e)}",
UiPathErrorCategory.SYSTEM,
) from e