|
| 1 | +"""Factory for creating client-side tools that execute on the client SDK.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from contextvars import ContextVar |
| 5 | +from typing import Annotated, Any, TypedDict |
| 6 | + |
| 7 | +from langchain_core.messages import ToolMessage |
| 8 | +from langchain_core.tools import InjectedToolCallId, StructuredTool |
| 9 | +from uipath.agent.models.agent import AgentClientSideToolResourceConfig |
| 10 | +from uipath.eval.mocks import mockable |
| 11 | + |
| 12 | +from uipath_langchain._utils.durable_interrupt import durable_interrupt |
| 13 | +from uipath_langchain.agent.react.jsonschema_pydantic_converter import ( |
| 14 | + create_model as create_model_from_schema, |
| 15 | +) |
| 16 | +from uipath_langchain.chat.hitl import IS_CONVERSATIONAL_CLIENT_SIDE_TOOL |
| 17 | + |
| 18 | +from .utils import sanitize_tool_name |
| 19 | + |
| 20 | +# When set, only tools in this set are available for the current exchange. |
| 21 | +# None means all client-side tools are available (default for CAS/web UI). |
| 22 | +available_client_side_tools: ContextVar[set[str] | None] = ContextVar( |
| 23 | + "available_client_side_tools", default=None |
| 24 | +) |
| 25 | + |
| 26 | +UIPATH_CLIENT_SIDE_TOOLS_INPUT_KEY = "uipath__client_side_tools" |
| 27 | + |
| 28 | + |
| 29 | +class ClientSideToolInfo(TypedDict): |
| 30 | + input_schema: dict[str, Any] | None |
| 31 | + output_schema: dict[str, Any] | None |
| 32 | + |
| 33 | + |
| 34 | +def apply_tool_filter( |
| 35 | + declared_tools: list[str | dict[str, Any]], |
| 36 | + agent_tools: dict[str, ClientSideToolInfo], |
| 37 | +) -> None: |
| 38 | + """Filter available client-side tools to the intersection of declared and agent tools. |
| 39 | +
|
| 40 | + Extracts tool names from the client's declarations, intersects with the agent's |
| 41 | + defined client-side tools, and sets the availability filter. Unknown names are |
| 42 | + silently ignored. |
| 43 | +
|
| 44 | + Args: |
| 45 | + declared_tools: List of tool names (strings) or dicts with a 'name' field |
| 46 | + from uipath__client_side_tools input. |
| 47 | + agent_tools: The agent's client-side tools keyed by name. |
| 48 | + """ |
| 49 | + declared_names: set[str] = set() |
| 50 | + for t in declared_tools: |
| 51 | + if isinstance(t, str): |
| 52 | + declared_names.add(t) |
| 53 | + elif isinstance(t, dict) and "name" in t: |
| 54 | + declared_names.add(t["name"]) |
| 55 | + |
| 56 | + available_client_side_tools.set(declared_names & set(agent_tools.keys())) |
| 57 | + |
| 58 | + |
| 59 | +def create_client_side_tool( |
| 60 | + resource: AgentClientSideToolResourceConfig, |
| 61 | +) -> StructuredTool: |
| 62 | + """Create a client-side tool that pauses the graph and waits for the client to execute it. |
| 63 | +
|
| 64 | + The tool uses @durable_interrupt to suspend the graph. The client receives |
| 65 | + an executingToolCall event, executes its registered handler, and sends |
| 66 | + endToolCall back through CAS. |
| 67 | + """ |
| 68 | + tool_name = sanitize_tool_name(resource.name) |
| 69 | + input_model = create_model_from_schema(resource.input_schema) |
| 70 | + |
| 71 | + async def client_side_tool_fn( |
| 72 | + *, tool_call_id: Annotated[str, InjectedToolCallId], **kwargs: Any |
| 73 | + ) -> Any: |
| 74 | + allowed = available_client_side_tools.get() |
| 75 | + if allowed is not None and tool_name not in allowed: |
| 76 | + return ToolMessage( |
| 77 | + content=f"Tool '{tool_name}' is not available — the client has not registered a handler for it.", |
| 78 | + tool_call_id=tool_call_id, |
| 79 | + status="error", |
| 80 | + ) |
| 81 | + |
| 82 | + @mockable( |
| 83 | + name=resource.name, |
| 84 | + description=resource.description, |
| 85 | + input_schema=input_model.model_json_schema(), |
| 86 | + output_schema=(resource.output_schema or {}), |
| 87 | + example_calls=getattr(resource.properties, "example_calls", None), |
| 88 | + ) |
| 89 | + async def execute_tool() -> dict[str, Any]: |
| 90 | + """Execute client-side tool, pausing for client response.""" |
| 91 | + |
| 92 | + @durable_interrupt |
| 93 | + async def wait_for_client_execution() -> dict[str, Any]: |
| 94 | + return { |
| 95 | + "tool_call_id": tool_call_id, |
| 96 | + "tool_name": tool_name, |
| 97 | + "input": kwargs, |
| 98 | + } |
| 99 | + |
| 100 | + result = await wait_for_client_execution() |
| 101 | + return result if isinstance(result, dict) else {"output": result} |
| 102 | + |
| 103 | + result = await execute_tool() |
| 104 | + |
| 105 | + is_error = result.get("isError", False) |
| 106 | + output = result.get("output", result) |
| 107 | + |
| 108 | + if isinstance(output, dict): |
| 109 | + try: |
| 110 | + content = json.dumps(output) |
| 111 | + except TypeError: |
| 112 | + content = str(output) |
| 113 | + else: |
| 114 | + content = str(output) if output is not None else "" |
| 115 | + |
| 116 | + return ToolMessage( |
| 117 | + content=content, |
| 118 | + tool_call_id=tool_call_id, |
| 119 | + status="error" if is_error else "success", |
| 120 | + response_metadata={IS_CONVERSATIONAL_CLIENT_SIDE_TOOL: True}, |
| 121 | + ) |
| 122 | + |
| 123 | + tool = StructuredTool( |
| 124 | + name=tool_name, |
| 125 | + description=resource.description or f"Client-side tool: {tool_name}", |
| 126 | + args_schema=input_model, |
| 127 | + coroutine=client_side_tool_fn, |
| 128 | + metadata={ |
| 129 | + IS_CONVERSATIONAL_CLIENT_SIDE_TOOL: True, |
| 130 | + "output_schema": resource.output_schema, |
| 131 | + }, |
| 132 | + ) |
| 133 | + |
| 134 | + return tool |
0 commit comments