-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcontext_tool.py
More file actions
640 lines (540 loc) · 21.7 KB
/
context_tool.py
File metadata and controls
640 lines (540 loc) · 21.7 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
"""Context tool creation for semantic index retrieval."""
import logging
import uuid
from typing import Any, Optional
from jsonpath_ng import parse # type: ignore[import-untyped]
from langchain_core.documents import Document
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import ToolCall
from langchain_core.tools import BaseTool, StructuredTool
from pydantic import BaseModel, Field, create_model
from uipath.agent.models.agent import (
AgentContextResourceConfig,
AgentContextRetrievalMode,
AgentContextType,
AgentMessageRole,
AgentToolArgumentArgumentProperties,
AgentToolArgumentProperties,
LowCodeAgentDefinition,
)
from uipath.eval.mocks import mockable
from uipath.platform import UiPath
from uipath.platform.common import CreateBatchTransform, CreateDeepRag, UiPathConfig
from uipath.platform.context_grounding import (
BatchTransformOutputColumn,
CitationMode,
DeepRagContent,
)
from uipath.platform.errors import EnrichedException
from uipath.runtime.errors import UiPathErrorCategory
from uipath_langchain._utils import get_execution_folder_path
from uipath_langchain._utils.durable_interrupt import durable_interrupt
from uipath_langchain.agent.exceptions import (
AgentStartupError,
AgentStartupErrorCode,
raise_for_enriched,
)
from uipath_langchain.agent.react.jsonschema_pydantic_converter import (
create_model as create_model_from_schema,
)
from uipath_langchain.agent.react.types import AgentGraphState
from uipath_langchain.agent.tools.internal_tools.schema_utils import (
BATCH_TRANSFORM_OUTPUT_SCHEMA,
)
from uipath_langchain.agent.tools.tool_node import ToolWrapperReturnType
from uipath_langchain.retrievers import ContextGroundingRetriever
from .structured_tool_with_argument_properties import (
StructuredToolWithArgumentProperties,
)
from .structured_tool_with_output_type import StructuredToolWithOutputType
from .utils import sanitize_tool_name
logger = logging.getLogger(__name__)
_CONTEXT_GROUNDING_ERRORS: dict[
tuple[int, str | None], tuple[str, UiPathErrorCategory]
] = {
(400, None): (
"Context grounding returned an error for index '{index}': {message}",
UiPathErrorCategory.USER,
),
}
def _build_arg_props_from_settings(
resource: AgentContextResourceConfig,
) -> dict[str, AgentToolArgumentProperties]:
"""Build argument_properties from context resource settings.
Context resources don't receive argumentProperties from the frontend.
Instead, we derive them from the settings when variant="argument".
Only includes fields that belong in the tool's args_schema (i.e. query).
"""
assert resource.settings is not None
arg_props: dict[str, AgentToolArgumentProperties] = {}
if resource.settings.query and resource.settings.query.variant == "argument":
argument_path = (resource.settings.query.value or "").strip("{}")
arg_props["query"] = AgentToolArgumentArgumentProperties(
is_sensitive=False,
argument_path=argument_path,
)
return arg_props
def _resolve_folder_path_prefix_from_state(
resource: AgentContextResourceConfig,
state: dict[str, Any],
) -> str | None:
"""Resolve folder_path_prefix from agent state using jsonpath from settings."""
assert resource.settings is not None
setting = resource.settings.folder_path_prefix
if not setting or setting.variant != "argument" or not setting.value:
return None
argument_path = "$." + setting.value.strip("{}")
matches = parse(argument_path).find(state)
return matches[0].value if matches else None
def _resolve_file_extension(resource: AgentContextResourceConfig) -> str | None:
"""Resolve file extension from settings, returning None for 'All' or empty."""
assert resource.settings is not None
if resource.settings.file_extension and resource.settings.file_extension.value:
ext = resource.settings.file_extension.value
if ext.lower() == "all":
return None
return ext
return None
def _resolve_static_folder_path_prefix(
resource: AgentContextResourceConfig,
) -> str | None:
"""Resolve static folder_path_prefix from settings."""
assert resource.settings is not None
if (
resource.settings.folder_path_prefix
and resource.settings.folder_path_prefix.value
and resource.settings.folder_path_prefix.variant == "static"
):
return resource.settings.folder_path_prefix.value
return None
def is_static_query(resource: AgentContextResourceConfig) -> bool:
"""Check if the resource configuration uses a static query variant."""
assert resource.settings is not None
if resource.settings.query is None or resource.settings.query.variant is None:
return False
return resource.settings.query.variant.lower() == "static"
def _extract_system_prompt(agent: LowCodeAgentDefinition | None) -> str:
"""Extract system prompt from agent definition messages."""
if agent is None:
return ""
return "\n\n".join(
msg.content
for msg in agent.messages
if msg.role == AgentMessageRole.SYSTEM and msg.content
)
def create_context_tool(
resource: AgentContextResourceConfig,
llm: BaseChatModel | None = None,
agent: LowCodeAgentDefinition | None = None,
) -> StructuredTool | BaseTool | None:
assert resource.context_type is not None
tool_name = sanitize_tool_name(resource.name)
if resource.context_type == AgentContextType.DATA_FABRIC_ENTITY_SET:
if llm is None:
raise ValueError("Data Fabric entity set tools require an LLM instance")
from .datafabric_tool import create_datafabric_query_tool
from .datafabric_tool.datafabric_tool import BASE_SYSTEM_PROMPT
return create_datafabric_query_tool(
resource,
llm,
tool_name=tool_name,
agent_config={BASE_SYSTEM_PROMPT: _extract_system_prompt(agent)},
)
assert resource.settings is not None
retrieval_mode = resource.settings.retrieval_mode.lower()
if retrieval_mode == AgentContextRetrievalMode.DEEP_RAG.value.lower():
return handle_deep_rag(tool_name, resource)
if retrieval_mode == AgentContextRetrievalMode.BATCH_TRANSFORM.value.lower():
return handle_batch_transform(tool_name, resource)
return handle_semantic_search(tool_name, resource)
def handle_semantic_search(
tool_name: str, resource: AgentContextResourceConfig
) -> StructuredTool:
ensure_valid_fields(resource)
assert resource.settings is not None
assert resource.settings.query.variant is not None
file_extension = _resolve_file_extension(resource)
static_folder_path_prefix = _resolve_static_folder_path_prefix(resource)
result_count = resource.settings.result_count
threshold = resource.settings.threshold
static = is_static_query(resource)
prompt = resource.settings.query.value if static else None
if static:
assert prompt is not None
arg_props = _build_arg_props_from_settings(resource)
class ContextOutputSchemaModel(BaseModel):
documents: list[Document] = Field(
..., description="List of retrieved documents."
)
output_model = ContextOutputSchemaModel
schema_fields: dict[str, Any] = {}
if "query" in arg_props:
schema_fields["query"] = (
str,
Field(
default=None,
description="The query to search for in the knowledge base",
),
)
elif not static:
schema_fields["query"] = (
str,
Field(
...,
description="The query to search for in the knowledge base",
),
)
has_arg_folder = (
resource.settings.folder_path_prefix
and resource.settings.folder_path_prefix.variant == "argument"
and resource.settings.folder_path_prefix.value
)
_resolved_arg_folder_prefix: str | None = None
input_model = create_model("SemanticSearchInput", **schema_fields)
@mockable(
name=resource.name,
description=resource.description,
input_schema=input_model.model_json_schema(),
output_schema=output_model.model_json_schema(),
example_calls=[], # Examples cannot be provided for context.
)
async def context_tool_fn(
query: Optional[str] = None,
) -> dict[str, Any]:
resolved_folder_path_prefix = (
static_folder_path_prefix or _resolved_arg_folder_prefix
)
debug_run = UiPathConfig.is_studio_project
retriever = ContextGroundingRetriever(
index_name=resource.index_name,
folder_path=get_execution_folder_path(),
number_of_results=result_count,
threshold=threshold,
scope_folder=resolved_folder_path_prefix,
scope_extension=file_extension,
include_system_indexes=debug_run,
)
actual_query = prompt or query
assert actual_query is not None
try:
docs = await retriever.ainvoke(actual_query)
except EnrichedException as e:
raise_for_enriched(
e,
_CONTEXT_GROUNDING_ERRORS,
title=f"Failed to search context index '{resource.index_name}'",
index=resource.index_name or "<unknown>",
)
raise
return {
"documents": [
{"metadata": doc.metadata, "page_content": doc.page_content}
for doc in docs
]
}
if arg_props or has_arg_folder:
async def context_semantic_search_wrapper(
tool: BaseTool,
call: ToolCall,
state: AgentGraphState,
) -> ToolWrapperReturnType:
nonlocal _resolved_arg_folder_prefix
_resolved_arg_folder_prefix = _resolve_folder_path_prefix_from_state(
resource, dict(state)
)
return await tool.ainvoke(call)
tool = StructuredToolWithArgumentProperties(
name=tool_name,
description=resource.description,
args_schema=input_model,
coroutine=context_tool_fn,
output_type=output_model,
argument_properties=arg_props,
metadata={
"tool_type": "context",
"display_name": resource.name,
"index_name": resource.index_name,
"context_retrieval_mode": resource.settings.retrieval_mode,
},
)
tool.set_tool_wrappers(awrapper=context_semantic_search_wrapper)
return tool
return StructuredToolWithOutputType(
name=tool_name,
description=resource.description,
args_schema=input_model,
coroutine=context_tool_fn,
output_type=output_model,
metadata={
"tool_type": "context",
"display_name": resource.name,
"index_name": resource.index_name,
"context_retrieval_mode": resource.settings.retrieval_mode,
},
)
def handle_deep_rag(
tool_name: str, resource: AgentContextResourceConfig
) -> StructuredToolWithArgumentProperties:
ensure_valid_fields(resource)
assert resource.settings is not None
assert resource.settings.query.variant is not None
index_name = resource.index_name
if not resource.settings.citation_mode:
raise AgentStartupError(
code=AgentStartupErrorCode.INVALID_TOOL_CONFIG,
title="Missing citation mode",
detail="Citation mode is required for Deep RAG. Please set the citation_mode field in context settings.",
category=UiPathErrorCategory.USER,
)
citation_mode = CitationMode(resource.settings.citation_mode.value)
static = is_static_query(resource)
prompt = resource.settings.query.value if static else None
if static:
assert prompt is not None
static_folder_path_prefix = _resolve_static_folder_path_prefix(resource)
file_extension = _resolve_file_extension(resource)
output_model = create_model(
"DeepRagOutputModel",
__base__=DeepRagContent,
deep_rag_id=(str, Field(alias="deepRagId")),
)
arg_props = _build_arg_props_from_settings(resource)
schema_fields: dict[str, Any] = (
{}
if static
else {
"query": (
str,
Field(
...,
description="Describe the task: what to research across documents, what to synthesize, and how to cite sources",
),
),
}
)
input_model = create_model("DeepRagInput", **schema_fields)
_resolved_arg_folder_prefix: str | None = None
@mockable(
name=resource.name,
description=resource.description,
input_schema=input_model.model_json_schema(),
output_schema=output_model.model_json_schema(),
example_calls=[], # Examples cannot be provided for context.
)
async def context_tool_fn(
query: Optional[str] = None,
) -> dict[str, Any]:
actual_prompt = prompt or query
glob_pattern = build_glob_pattern(
folder_path_prefix=static_folder_path_prefix or _resolved_arg_folder_prefix,
file_extension=file_extension,
)
@durable_interrupt
async def create_deep_rag():
return CreateDeepRag(
name=f"task-{uuid.uuid4()}",
index_name=index_name,
prompt=actual_prompt,
citation_mode=citation_mode,
index_folder_path=get_execution_folder_path(),
glob_pattern=glob_pattern,
)
return await create_deep_rag()
async def context_deep_rag_wrapper(
tool: BaseTool,
call: ToolCall,
state: AgentGraphState,
) -> ToolWrapperReturnType:
nonlocal _resolved_arg_folder_prefix
_resolved_arg_folder_prefix = _resolve_folder_path_prefix_from_state(
resource, dict(state)
)
return await tool.ainvoke(call)
tool = StructuredToolWithArgumentProperties(
name=tool_name,
description=resource.description,
args_schema=input_model,
coroutine=context_tool_fn,
output_type=output_model,
argument_properties=arg_props,
metadata={
"tool_type": "context",
"display_name": resource.name,
"index_name": resource.index_name,
"context_retrieval_mode": resource.settings.retrieval_mode,
},
)
tool.set_tool_wrappers(awrapper=context_deep_rag_wrapper)
return tool
def handle_batch_transform(
tool_name: str, resource: AgentContextResourceConfig
) -> StructuredToolWithArgumentProperties:
ensure_valid_fields(resource)
assert resource.settings is not None
assert resource.settings.query is not None
assert resource.settings.query.variant is not None
index_name = resource.index_name
index_folder_path = get_execution_folder_path()
if not resource.settings.web_search_grounding:
raise AgentStartupError(
code=AgentStartupErrorCode.INVALID_TOOL_CONFIG,
title="Missing web search grounding",
detail="Web search grounding field is required for Batch Transform. Please set the web_search_grounding field in context settings.",
category=UiPathErrorCategory.USER,
)
enable_web_search_grounding = (
resource.settings.web_search_grounding.value.lower() == "enabled"
)
batch_transform_output_columns: list[BatchTransformOutputColumn] = []
if (output_columns := resource.settings.output_columns) is None or not len(
output_columns
):
raise AgentStartupError(
code=AgentStartupErrorCode.INVALID_TOOL_CONFIG,
title="Missing output columns",
detail="Batch transform requires at least one output column to be specified in settings.output_columns. Please add output columns to the context configuration.",
category=UiPathErrorCategory.USER,
)
for column in output_columns:
batch_transform_output_columns.append(
BatchTransformOutputColumn(
name=column.name,
description=column.description,
)
)
static = is_static_query(resource)
prompt = resource.settings.query.value if static else None
if static:
assert prompt is not None
static_folder_path_prefix = _resolve_static_folder_path_prefix(resource)
arg_props = _build_arg_props_from_settings(resource)
output_model = create_model_from_schema(BATCH_TRANSFORM_OUTPUT_SCHEMA)
schema_fields: dict[str, Any] = {}
if not static:
schema_fields["query"] = (
str,
Field(
...,
description="Describe the task for each row: what to analyze, what to extract, and how to populate the output columns",
),
)
schema_fields["destination_path"] = (
str,
Field(
default="output.csv",
description="The relative file path destination for the modified csv file",
),
)
input_model = create_model("BatchTransformInput", **schema_fields)
_resolved_arg_folder_prefix: str | None = None
@mockable(
name=resource.name,
description=resource.description,
input_schema=input_model.model_json_schema(),
output_schema=output_model.model_json_schema(),
example_calls=[], # Examples cannot be provided for context.
)
async def context_tool_fn(
query: Optional[str] = None,
destination_path: str = "output.csv",
) -> dict[str, Any]:
actual_prompt = prompt or query
glob_pattern = build_glob_pattern(
folder_path_prefix=static_folder_path_prefix or _resolved_arg_folder_prefix,
file_extension=None,
)
@durable_interrupt
async def create_batch_transform():
return CreateBatchTransform(
name=f"task-{uuid.uuid4()}",
index_name=index_name,
prompt=actual_prompt,
destination_path=destination_path,
index_folder_path=index_folder_path,
enable_web_search_grounding=enable_web_search_grounding,
output_columns=batch_transform_output_columns,
storage_bucket_folder_path_prefix=glob_pattern,
)
await create_batch_transform()
uipath = UiPath()
result_attachment_id = await uipath.jobs.create_attachment_async(
name=destination_path,
source_path=destination_path,
job_key=UiPathConfig.job_key,
)
return {
"result": {
"ID": str(result_attachment_id),
"FullName": destination_path,
"MimeType": "text/csv",
}
}
from uipath_langchain.agent.wrappers import get_job_attachment_wrapper
job_attachment_wrapper = get_job_attachment_wrapper(output_type=output_model)
async def context_batch_transform_wrapper(
tool: BaseTool,
call: ToolCall,
state: AgentGraphState,
) -> ToolWrapperReturnType:
nonlocal _resolved_arg_folder_prefix
_resolved_arg_folder_prefix = _resolve_folder_path_prefix_from_state(
resource, dict(state)
)
return await job_attachment_wrapper(tool, call, state)
tool = StructuredToolWithArgumentProperties(
name=tool_name,
description=resource.description,
args_schema=input_model,
coroutine=context_tool_fn,
output_type=output_model,
argument_properties=arg_props,
metadata={
"tool_type": "context",
"display_name": resource.name,
"index_name": resource.index_name,
"context_retrieval_mode": resource.settings.retrieval_mode,
"output_schema": output_model,
},
)
tool.set_tool_wrappers(awrapper=job_attachment_wrapper)
return tool
def ensure_valid_fields(resource_config: AgentContextResourceConfig):
assert resource_config.settings is not None
if not resource_config.settings.query.variant:
raise AgentStartupError(
code=AgentStartupErrorCode.INVALID_TOOL_CONFIG,
title="Missing query variant",
detail="Query variant is required. Please set the query variant in context settings.",
category=UiPathErrorCategory.USER,
)
if is_static_query(resource_config) and not resource_config.settings.query.value:
raise AgentStartupError(
code=AgentStartupErrorCode.INVALID_TOOL_CONFIG,
title="Missing static query value",
detail="Static query requires a query value to be set. Please provide a value for the static query in context settings.",
category=UiPathErrorCategory.USER,
)
def _normalize_folder_prefix(folder_path_prefix: str | None) -> str:
"""Normalize a folder path prefix to a clean directory-only pattern.
Strips leading/trailing slashes and trailing file-matching globs
(e.g. /*, /**, /**/*) since the caller appends the file extension part.
"""
if not folder_path_prefix:
return "**"
prefix = folder_path_prefix.strip("/").rstrip("/*")
if not prefix:
return "**"
return prefix
def build_glob_pattern(
folder_path_prefix: str | None, file_extension: str | None
) -> str:
prefix = _normalize_folder_prefix(folder_path_prefix)
# Handle extension
extension = "*"
if file_extension:
ext = file_extension.lower()
extension = f"*.{ext}"
# Final pattern logic
if prefix == "**":
return "**/*" if extension == "*" else f"**/{extension}"
return f"{prefix}/{extension}"