|
1 | 1 | """Input handler for tool wrapper deserialization. |
2 | 2 |
|
3 | 3 | Converts serialized tool wrapper dicts into callable LangChain StructuredTool |
4 | | -objects. |
| 4 | +objects whose invocation executes the wrapped Langflow component. |
5 | 5 | """ |
6 | 6 |
|
7 | 7 | from __future__ import annotations |
@@ -57,84 +57,127 @@ def _eval_expr(node: ast.AST) -> float: |
57 | 57 | raise TypeError(f"Unsupported operation or expression type: {type(node).__name__}") |
58 | 58 |
|
59 | 59 |
|
60 | | -def _create_tool_from_wrapper(tool_wrapper: dict[str, Any]) -> Any: |
61 | | - """Create a LangChain StructuredTool from a tool wrapper.""" |
| 60 | +def _build_blob_data(component_code: dict[str, Any], component_type: str) -> dict[str, Any]: |
| 61 | + """Reshape a raw component definition into the executor's enhanced blob shape. |
| 62 | +
|
| 63 | + ``component_tool`` stores the raw component node (``node["data"]["node"]``) as |
| 64 | + the tool blob: the Python source lives under ``template.code.value`` and the |
| 65 | + declared outputs under ``outputs``. ``CustomCodeExecutor._compile_component`` |
| 66 | + instead expects ``code`` and the ``template`` (sans code) at the top level, so |
| 67 | + reshape here, mirroring ``NodeProcessor._prepare_udf_blob``. The tool runs the |
| 68 | + component's first declared output. |
| 69 | + """ |
| 70 | + template = component_code.get("template", {}) |
| 71 | + code = template.get("code", {}).get("value", "") |
| 72 | + outputs = component_code.get("outputs", []) |
| 73 | + selected_output = outputs[0].get("name") if outputs else None |
| 74 | + prepared_template = {name: cfg for name, cfg in template.items() if name != "code"} |
| 75 | + return { |
| 76 | + "code": code, |
| 77 | + "template": prepared_template, |
| 78 | + "component_type": component_type, |
| 79 | + "outputs": outputs, |
| 80 | + "selected_output": selected_output, |
| 81 | + "base_classes": component_code.get("base_classes", []), |
| 82 | + "display_name": component_code.get("display_name", component_type), |
| 83 | + "description": component_code.get("description", ""), |
| 84 | + "documentation": component_code.get("documentation", ""), |
| 85 | + "metadata": component_code.get("metadata", {}), |
| 86 | + "field_order": component_code.get("field_order", []), |
| 87 | + "icon": component_code.get("icon", ""), |
| 88 | + } |
| 89 | + |
| 90 | + |
| 91 | +def _build_input_schema(tool_input_schema: dict[str, Any]) -> Any: |
| 92 | + """Build the StructuredTool args schema from the tool's input schema.""" |
| 93 | + from pydantic import BaseModel, create_model |
| 94 | + |
| 95 | + properties = tool_input_schema.get("properties", {}) |
| 96 | + field_definitions: dict[str, tuple[type, Any]] = {} |
| 97 | + for field_name, field_def in properties.items(): |
| 98 | + field_definitions[field_name] = (str, field_def.get("default", "")) |
| 99 | + |
| 100 | + if field_definitions: |
| 101 | + return create_model("ToolInputSchema", **field_definitions) # type: ignore[call-overload] |
| 102 | + |
| 103 | + class EmptySchema(BaseModel): |
| 104 | + pass |
| 105 | + |
| 106 | + return EmptySchema |
| 107 | + |
| 108 | + |
| 109 | +async def _create_tool_from_wrapper(tool_wrapper: dict[str, Any], context: Any = None) -> Any: |
| 110 | + """Create a LangChain StructuredTool from a tool wrapper. |
| 111 | +
|
| 112 | + The returned tool executes the wrapped Langflow component on invocation. The |
| 113 | + component is compiled once here, where the Stepflow ``context`` is available to |
| 114 | + fetch its code blob, then executed without context on each call, matching the |
| 115 | + custom-code executor's pre-compile-then-execute design. |
| 116 | + """ |
62 | 117 | try: |
63 | 118 | from langchain_core.tools import StructuredTool |
64 | | - from pydantic import BaseModel, create_model |
65 | 119 |
|
66 | 120 | tool_metadata = tool_wrapper.get("tool_metadata", {}) |
67 | | - tool_input_schema = tool_wrapper.get("tool_input_schema", {}) |
68 | 121 | static_inputs = tool_wrapper.get("static_inputs", {}) |
69 | 122 | component_type = tool_wrapper.get("component_type", "unknown") |
70 | 123 | session_id = tool_wrapper.get("session_id", "default_session") |
71 | 124 |
|
| 125 | + input_schema = _build_input_schema(tool_wrapper.get("tool_input_schema", {})) |
| 126 | + |
| 127 | + # Calculator fast-path: the CalculatorComponent's expression evaluator is |
| 128 | + # pure and self-contained, so run it directly without compiling a component. |
| 129 | + if tool_metadata.get("name") == "evaluate_expression": |
| 130 | + |
| 131 | + def calculator_func(**kwargs) -> dict[str, Any]: |
| 132 | + return {"result": _execute_calculator_tool(kwargs.get("expression", ""))} |
| 133 | + |
| 134 | + return StructuredTool.from_function( |
| 135 | + func=calculator_func, |
| 136 | + name=tool_metadata.get("name", "unknown_tool"), |
| 137 | + description=tool_metadata.get("description", ""), |
| 138 | + args_schema=input_schema, |
| 139 | + ) |
| 140 | + |
72 | 141 | component_code = tool_wrapper.get("component_code") |
73 | 142 | code_blob_id = tool_wrapper.get("code_blob_id") |
74 | | - |
75 | 143 | if component_code is None and code_blob_id is None: |
76 | 144 | raise ValueError("Tool wrapper missing both component_code and code_blob_id") |
77 | 145 |
|
78 | | - properties = tool_input_schema.get("properties", {}) |
79 | | - |
80 | | - field_definitions: dict[str, tuple[type, Any]] = {} |
81 | | - for field_name, field_def in properties.items(): |
82 | | - field_type: type = str |
83 | | - default_value = field_def.get("default", "") |
84 | | - field_definitions[field_name] = (field_type, default_value) |
85 | | - |
86 | | - input_schema: type[BaseModel] |
87 | | - if field_definitions: |
88 | | - input_schema = create_model("ToolInputSchema", **field_definitions) # type: ignore[call-overload] |
| 146 | + # Resolve the raw component definition: component_tool stores it as a blob |
| 147 | + # and references it by id; an inline component_code dict is also accepted. |
| 148 | + if code_blob_id is not None: |
| 149 | + if context is None: |
| 150 | + raise ValueError("code_blob_id requires a Stepflow context to fetch the component blob") |
| 151 | + raw_component = await context.get_blob(code_blob_id) |
89 | 152 | else: |
| 153 | + raw_component = component_code |
| 154 | + if not isinstance(raw_component, dict): |
| 155 | + raise TypeError(f"Component code must be a component definition dict, got {type(raw_component).__name__}") |
90 | 156 |
|
91 | | - class EmptySchema(BaseModel): |
92 | | - pass |
| 157 | + # Imported lazily: custom_code_executor imports this handler, so a top-level |
| 158 | + # import would be circular. |
| 159 | + from ..custom_code_executor import CustomCodeExecutor |
93 | 160 |
|
94 | | - input_schema = EmptySchema |
| 161 | + executor = CustomCodeExecutor() |
| 162 | + blob_data = _build_blob_data(raw_component, component_type) |
| 163 | + compiled_component = await executor._compile_component(blob_data, code_blob_id) |
95 | 164 |
|
96 | | - def tool_func(**kwargs) -> dict[str, Any]: |
97 | | - """Execute the tool by running the component.""" |
| 165 | + async def tool_func(**kwargs) -> Any: |
| 166 | + """Execute the wrapped component with the tool's merged inputs.""" |
98 | 167 | try: |
99 | | - if tool_metadata.get("name") == "evaluate_expression" and "expression" in kwargs: |
100 | | - result = _execute_calculator_tool(kwargs["expression"]) |
101 | | - return {"result": result} |
102 | | - |
103 | | - merged_inputs = { |
104 | | - **static_inputs, |
105 | | - **kwargs, |
106 | | - "session_id": session_id, |
107 | | - } |
108 | | - |
109 | | - tool_name = tool_metadata.get("name", "unknown") |
110 | | - result_data = { |
111 | | - "result": (f"Tool {tool_name} executed with inputs: {merged_inputs}"), |
112 | | - "component_type": component_type, |
113 | | - "inputs": merged_inputs, |
114 | | - "status": "tool_wrapper_execution", |
115 | | - } |
116 | | - |
117 | | - if code_blob_id: |
118 | | - result_data["code_blob_id"] = code_blob_id |
119 | | - elif component_code: |
120 | | - result_data["has_component_code"] = True |
121 | | - |
122 | | - return result_data |
123 | | - |
124 | | - except Exception as e: |
125 | | - return { |
126 | | - "error": f"Tool execution failed: {str(e)}", |
127 | | - "component_type": component_type, |
128 | | - } |
| 168 | + runtime_inputs = {**static_inputs, **kwargs, "session_id": session_id} |
| 169 | + return await executor._execute_compiled_component(compiled_component, runtime_inputs) |
| 170 | + except Exception as e: # noqa: BLE001 - surface a tool-shaped error to the agent |
| 171 | + return {"error": f"Tool execution failed: {str(e)}", "component_type": component_type} |
129 | 172 |
|
130 | 173 | return StructuredTool.from_function( |
131 | | - func=tool_func, |
| 174 | + coroutine=tool_func, |
132 | 175 | name=tool_metadata.get("name", "unknown_tool"), |
133 | 176 | description=tool_metadata.get("description", ""), |
134 | 177 | args_schema=input_schema, |
135 | 178 | ) |
136 | 179 |
|
137 | | - except Exception as e: |
| 180 | + except Exception as e: # noqa: BLE001 - any wrapper-build failure degrades to a failed tool |
138 | 181 |
|
139 | 182 | class FailedToolWrapper: |
140 | 183 | def __init__(self, tool_wrapper, error): |
@@ -167,11 +210,14 @@ async def prepare(self, fields: dict[str, tuple[Any, dict[str, Any]]], context: |
167 | 210 |
|
168 | 211 | for key, (value, _template_field) in fields.items(): |
169 | 212 | if isinstance(value, dict) and value.get("__tool_wrapper__"): |
170 | | - result[key] = _create_tool_from_wrapper(value) |
| 213 | + result[key] = await _create_tool_from_wrapper(value, context) |
171 | 214 | elif isinstance(value, list): |
172 | | - result[key] = [ |
173 | | - _create_tool_from_wrapper(item) if isinstance(item, dict) and item.get("__tool_wrapper__") else item |
174 | | - for item in value |
175 | | - ] |
| 215 | + resolved: list[Any] = [] |
| 216 | + for item in value: |
| 217 | + if isinstance(item, dict) and item.get("__tool_wrapper__"): |
| 218 | + resolved.append(await _create_tool_from_wrapper(item, context)) |
| 219 | + else: |
| 220 | + resolved.append(item) |
| 221 | + result[key] = resolved |
176 | 222 |
|
177 | 223 | return result |
0 commit comments