|
1 | 1 | import json |
2 | 2 | import logging |
| 3 | +import os |
| 4 | +import pickle |
| 5 | +import uuid |
3 | 6 | from contextlib import suppress |
4 | | -from typing import Optional |
| 7 | +from typing import Any, Optional |
5 | 8 |
|
| 9 | +from llama_index.core.workflow import ( |
| 10 | + Context, |
| 11 | + HumanResponseEvent, |
| 12 | + InputRequiredEvent, |
| 13 | + JsonPickleSerializer, |
| 14 | +) |
6 | 15 | from openinference.instrumentation.llama_index import LlamaIndexInstrumentor |
7 | 16 | from opentelemetry import trace |
8 | 17 | from opentelemetry.sdk.trace import TracerProvider |
9 | 18 | from opentelemetry.sdk.trace.export import BatchSpanProcessor |
10 | 19 | from uipath import UiPath |
11 | 20 | from uipath._cli._runtime._contracts import ( |
| 21 | + UiPathApiTrigger, |
12 | 22 | UiPathBaseRuntime, |
13 | 23 | UiPathErrorCategory, |
| 24 | + UiPathResumeTrigger, |
14 | 25 | UiPathRuntimeResult, |
| 26 | + UiPathRuntimeStatus, |
15 | 27 | ) |
16 | 28 |
|
17 | 29 | from .._tracing._oteladapter import LlamaIndexExporter |
@@ -55,19 +67,45 @@ async def execute(self) -> Optional[UiPathRuntimeResult]: |
55 | 67 |
|
56 | 68 | try: |
57 | 69 | start_event_class = self.context.workflow._start_event_class |
58 | | - |
59 | 70 | ev = start_event_class(**self.context.input_json) |
60 | 71 |
|
61 | | - handler = self.context.workflow.run(start_event=ev) |
| 72 | + ctx: Context = self._get_context() |
| 73 | + |
| 74 | + handler = self.context.workflow.run(start_event=ev, ctx=ctx) |
| 75 | + |
| 76 | + resume_trigger: UiPathResumeTrigger = None |
62 | 77 |
|
63 | 78 | async for event in handler.stream_events(): |
| 79 | + if isinstance(event, InputRequiredEvent): |
| 80 | + resume_trigger = UiPathResumeTrigger( |
| 81 | + api_resume=UiPathApiTrigger( |
| 82 | + inbox_id=str(uuid.uuid4()), request=event.prefix |
| 83 | + ) |
| 84 | + ) |
| 85 | + break |
64 | 86 | print(event) |
65 | 87 |
|
66 | | - output = await handler |
| 88 | + if resume_trigger is None: |
| 89 | + output = await handler |
| 90 | + self.context.result = UiPathRuntimeResult( |
| 91 | + output=self._serialize_object(output), |
| 92 | + status=UiPathRuntimeStatus.SUCCESSFUL, |
| 93 | + ) |
| 94 | + else: |
| 95 | + self.context.result = UiPathRuntimeResult( |
| 96 | + output=self._serialize_object(output), |
| 97 | + status=UiPathRuntimeStatus.SUSPENDED, |
| 98 | + resume=resume_trigger, |
| 99 | + ) |
67 | 100 |
|
68 | | - self.context.result = UiPathRuntimeResult( |
69 | | - output=self._serialize_object(output) |
70 | | - ) |
| 101 | + if self.context.state_file: |
| 102 | + serializer = JsonPickleSerializer() |
| 103 | + ctx_dict = ctx.to_dict(serializer=serializer) |
| 104 | + ctx_dict["uipath_resume_trigger"] = ( |
| 105 | + serializer.serialize(resume_trigger) if resume_trigger else None |
| 106 | + ) |
| 107 | + with open(self.context.state_file, "wb") as f: |
| 108 | + pickle.dump(ctx_dict, f) |
71 | 109 |
|
72 | 110 | return self.context.result |
73 | 111 |
|
@@ -172,6 +210,73 @@ async def cleanup(self) -> None: |
172 | 210 | """Clean up all resources.""" |
173 | 211 | pass |
174 | 212 |
|
| 213 | + async def _get_context(self) -> Context: |
| 214 | + """ |
| 215 | + Get the context for the LlamaIndex agent. |
| 216 | +
|
| 217 | + Returns: |
| 218 | + The context object for the LlamaIndex agent. |
| 219 | + """ |
| 220 | + logger.debug(f"Resumed: {self.context.resume} Input: {self.context.input_json}") |
| 221 | + |
| 222 | + if not self.context.resume: |
| 223 | + return Context(self.context.workflow) |
| 224 | + |
| 225 | + if not self.context.state_file or not os.path.exists(self.context.state_file): |
| 226 | + return Context(self.context.workflow) |
| 227 | + |
| 228 | + serializer = JsonPickleSerializer() |
| 229 | + ctx: Context = None |
| 230 | + |
| 231 | + with open(self.context.state_file, "rb") as f: |
| 232 | + loaded_ctx_dict = pickle.load(f) |
| 233 | + ctx = Context.from_dict( |
| 234 | + self.context.workflow, |
| 235 | + loaded_ctx_dict, |
| 236 | + serializer=serializer, |
| 237 | + ) |
| 238 | + |
| 239 | + if self.context.input_json: |
| 240 | + ctx.send_event(HumanResponseEvent(response=self.context.input_json)) |
| 241 | + |
| 242 | + resumed_trigger_data = loaded_ctx_dict["uipath_resume_trigger"] |
| 243 | + if resumed_trigger_data: |
| 244 | + resumed_trigger: UiPathResumeTrigger = serializer.deserialize( |
| 245 | + resumed_trigger_data, UiPathResumeTrigger |
| 246 | + ) |
| 247 | + inbox_id = resumed_trigger.api_resume.inbox_id |
| 248 | + payload = await self._get_api_payload(inbox_id) |
| 249 | + ctx.send_event(HumanResponseEvent(response=payload)) |
| 250 | + |
| 251 | + return ctx |
| 252 | + |
| 253 | + async def _get_api_payload(self, inbox_id: str) -> Any: |
| 254 | + """ |
| 255 | + Fetch payload data for API triggers. |
| 256 | +
|
| 257 | + Args: |
| 258 | + inbox_id: The Id of the inbox to fetch the payload for. |
| 259 | +
|
| 260 | + Returns: |
| 261 | + The value field from the API response payload, or None if an error occurs. |
| 262 | + """ |
| 263 | + try: |
| 264 | + response = self._uipath.api_client.request( |
| 265 | + "GET", |
| 266 | + f"/orchestrator_/api/JobTriggers/GetPayload/{inbox_id}", |
| 267 | + include_folder_headers=True, |
| 268 | + ) |
| 269 | + data = response.json() |
| 270 | + return data.get("payload") |
| 271 | + except Exception as e: |
| 272 | + raise UiPathLlamaIndexRuntimeError( |
| 273 | + "API_CONNECTION_ERROR", |
| 274 | + "Failed to get trigger payload", |
| 275 | + f"Error fetching API trigger payload for inbox {inbox_id}: {str(e)}", |
| 276 | + UiPathErrorCategory.SYSTEM, |
| 277 | + response.status_code, |
| 278 | + ) from e |
| 279 | + |
175 | 280 | def _serialize_object(self, obj): |
176 | 281 | """Recursively serializes an object and all its nested components.""" |
177 | 282 | # Handle Pydantic models |
|
0 commit comments