|
| 1 | +"""Memory recall node for Agent Episodic Memory. |
| 2 | +
|
| 3 | +Queries the UiPath Memory service (via LLMOps) for similar past episodes |
| 4 | +and stores the server-generated systemPromptInjection in graph state so |
| 5 | +the INIT node can append it to the system prompt. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +from contextlib import contextmanager |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +from pydantic import BaseModel |
| 13 | +from uipath.platform import UiPath |
| 14 | +from uipath.platform.memory import ( |
| 15 | + FieldSettings, |
| 16 | + MemorySearchRequest, |
| 17 | + SearchField, |
| 18 | + SearchMode, |
| 19 | + SearchSettings, |
| 20 | +) |
| 21 | + |
| 22 | +from .types import MemoryConfig |
| 23 | +from .utils import extract_input_data_from_state |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | + |
| 28 | +@contextmanager |
| 29 | +def _noop_context(): |
| 30 | + """No-op context manager when OTel is unavailable.""" |
| 31 | + yield None |
| 32 | + |
| 33 | + |
| 34 | +def create_memory_recall_node( |
| 35 | + memory_config: MemoryConfig, |
| 36 | + input_schema: type[BaseModel] | None = None, |
| 37 | +): |
| 38 | + """Create an async graph node that retrieves memory injection. |
| 39 | +
|
| 40 | + The node queries ``sdk.memory.search_async()`` and writes the |
| 41 | + ``systemPromptInjection`` string into ``inner_state.memory_injection``. |
| 42 | + On failure it logs a warning and continues with an empty injection. |
| 43 | +
|
| 44 | + Args: |
| 45 | + memory_config: Memory configuration with space ID and search settings. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + An async callable suitable for ``builder.add_node()``. |
| 49 | + """ |
| 50 | + |
| 51 | + async def memory_recall_node(state: Any) -> dict[str, Any]: |
| 52 | + input_model = input_schema if input_schema is not None else BaseModel |
| 53 | + input_arguments = extract_input_data_from_state(state, input_model) |
| 54 | + if not input_arguments: |
| 55 | + logger.debug("Memory recall: no user inputs found in state") |
| 56 | + return {} |
| 57 | + |
| 58 | + fields = _build_search_fields( |
| 59 | + input_arguments, field_weights=memory_config.field_weights or None |
| 60 | + ) |
| 61 | + if not fields: |
| 62 | + logger.debug( |
| 63 | + "Memory recall: no search fields after filtering (inputs=%s, weights=%s)", |
| 64 | + list(input_arguments.keys()), |
| 65 | + memory_config.field_weights, |
| 66 | + ) |
| 67 | + return {} |
| 68 | + |
| 69 | + request = MemorySearchRequest( |
| 70 | + fields=fields, |
| 71 | + settings=SearchSettings( |
| 72 | + threshold=memory_config.threshold, |
| 73 | + result_count=memory_config.result_count, |
| 74 | + search_mode=SearchMode.Hybrid, |
| 75 | + ), |
| 76 | + definition_system_prompt="", |
| 77 | + ) |
| 78 | + |
| 79 | + results_count = 0 |
| 80 | + # Wrap the search in OTel spans so "Find previous memories" and |
| 81 | + # "Apply dynamic few shot" appear in the Execution Trace with |
| 82 | + # correct timing. The LlmOpsHttpExporter picks these up. |
| 83 | + injection = "" |
| 84 | + try: |
| 85 | + from opentelemetry import trace as otel_trace |
| 86 | + |
| 87 | + tracer = otel_trace.get_tracer("uipath_langchain.memory") |
| 88 | + except ImportError: |
| 89 | + tracer = None |
| 90 | + otel_trace = None # type: ignore[assignment] |
| 91 | + |
| 92 | + # Span attribute keys matching what the LlmOpsHttpExporter and |
| 93 | + # Studio UI expect. "openinference.span.kind" sets SpanType. |
| 94 | + lookup_span_ctx = ( |
| 95 | + tracer.start_as_current_span( |
| 96 | + "Find previous memories", |
| 97 | + attributes={ |
| 98 | + "openinference.span.kind": "agentMemoryLookup", |
| 99 | + "type": "agentMemoryLookup", |
| 100 | + "span_type": "agentMemoryLookup", |
| 101 | + "uipath.custom_instrumentation": True, |
| 102 | + "memorySpaceName": memory_config.memory_space_name or "", |
| 103 | + "memorySpaceId": memory_config.memory_space_id, |
| 104 | + "strategy": "DynamicFewShotPrompt", |
| 105 | + }, |
| 106 | + ) |
| 107 | + if tracer |
| 108 | + else _noop_context() |
| 109 | + ) |
| 110 | + |
| 111 | + with lookup_span_ctx as lookup_span: |
| 112 | + fewshot_span_ctx = ( |
| 113 | + tracer.start_as_current_span( |
| 114 | + "Apply dynamic few shot", |
| 115 | + attributes={ |
| 116 | + "openinference.span.kind": "applyDynamicFewShot", |
| 117 | + "type": "applyDynamicFewShot", |
| 118 | + "span_type": "applyDynamicFewShot", |
| 119 | + "uipath.custom_instrumentation": True, |
| 120 | + "memorySpaceName": memory_config.memory_space_name or "", |
| 121 | + "memorySpaceId": memory_config.memory_space_id, |
| 122 | + }, |
| 123 | + ) |
| 124 | + if tracer |
| 125 | + else _noop_context() |
| 126 | + ) |
| 127 | + |
| 128 | + with fewshot_span_ctx as fewshot_span: |
| 129 | + try: |
| 130 | + sdk = UiPath() |
| 131 | + folder_key = memory_config.folder_key |
| 132 | + if not folder_key and memory_config.folder_path: |
| 133 | + folder_key = await sdk.folders.retrieve_folder_key_async( |
| 134 | + memory_config.folder_path |
| 135 | + ) |
| 136 | + response = await sdk.memory.search_async( |
| 137 | + memory_space_id=memory_config.memory_space_id, |
| 138 | + request=request, |
| 139 | + folder_key=folder_key, |
| 140 | + ) |
| 141 | + injection = response.system_prompt_injection |
| 142 | + results_count = len(response.results) |
| 143 | + logger.info( |
| 144 | + "Memory recall returned %d results for space '%s'", |
| 145 | + results_count, |
| 146 | + memory_config.memory_space_id, |
| 147 | + ) |
| 148 | + # Set request/response on fewshot span as JSON strings. |
| 149 | + # The exporter parses JSON strings back to objects. |
| 150 | + # The UI reads "response" to display matched memory items. |
| 151 | + if fewshot_span and hasattr(fewshot_span, "set_attribute"): |
| 152 | + import json |
| 153 | + |
| 154 | + fewshot_span.set_attribute( |
| 155 | + "request", |
| 156 | + json.dumps( |
| 157 | + request.model_dump(by_alias=True, exclude_none=True) |
| 158 | + ), |
| 159 | + ) |
| 160 | + fewshot_span.set_attribute( |
| 161 | + "response", |
| 162 | + json.dumps( |
| 163 | + response.model_dump(by_alias=True, exclude_none=True) |
| 164 | + ), |
| 165 | + ) |
| 166 | + except Exception as e: |
| 167 | + from uipath.platform.errors import EnrichedException |
| 168 | + |
| 169 | + if isinstance(e, EnrichedException): |
| 170 | + error_detail = ( |
| 171 | + f"{e} | status={e.status_code} body={e.response_content}" |
| 172 | + ) |
| 173 | + else: |
| 174 | + error_detail = repr(e) |
| 175 | + logger.warning( |
| 176 | + "Memory recall failed for space '%s': %s", |
| 177 | + memory_config.memory_space_id, |
| 178 | + error_detail, |
| 179 | + ) |
| 180 | + if lookup_span and hasattr(lookup_span, "set_status"): |
| 181 | + lookup_span.set_status( |
| 182 | + otel_trace.StatusCode.ERROR, error_detail |
| 183 | + ) |
| 184 | + |
| 185 | + # Set result attributes after search completes |
| 186 | + if lookup_span and hasattr(lookup_span, "set_attribute"): |
| 187 | + lookup_span.set_attribute("memoryItemsMatched", results_count) |
| 188 | + if injection: |
| 189 | + lookup_span.set_attribute("result", injection) |
| 190 | + |
| 191 | + if not injection: |
| 192 | + return {} |
| 193 | + |
| 194 | + return {"inner_state": {"memory_injection": injection}} |
| 195 | + |
| 196 | + return memory_recall_node |
| 197 | + |
| 198 | + |
| 199 | +def _build_search_fields( |
| 200 | + input_arguments: dict[str, Any], |
| 201 | + field_weights: dict[str, float] | None = None, |
| 202 | + field_type: str = "agent-input", |
| 203 | +) -> list[SearchField]: |
| 204 | + """Convert agent input arguments to SearchField objects. |
| 205 | +
|
| 206 | + The key_path must be prefixed with the field type: |
| 207 | + keyPath = [fieldType, fieldName] |
| 208 | + e.g. ["agent-input", "a"] for episodic memory. |
| 209 | + """ |
| 210 | + fields: list[SearchField] = [] |
| 211 | + for name, value in input_arguments.items(): |
| 212 | + value_str = str(value) if value is not None else "" |
| 213 | + if not value_str or name.startswith("uipath__"): |
| 214 | + continue |
| 215 | + # When field_weights is specified, only include fields with configured weights |
| 216 | + if field_weights and name not in field_weights: |
| 217 | + continue |
| 218 | + settings = FieldSettings() |
| 219 | + if field_weights and name in field_weights: |
| 220 | + settings = FieldSettings(weight=field_weights[name]) |
| 221 | + fields.append( |
| 222 | + SearchField(key_path=[field_type, name], value=value_str, settings=settings) |
| 223 | + ) |
| 224 | + return fields |
0 commit comments