-
Notifications
You must be signed in to change notification settings - Fork 29
feat: add ToolRuntime injection for interruptible tools #381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
saksharthakkar
wants to merge
3
commits into
main
Choose a base branch
from
feat/tool-runtime-injection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,47 @@ | ||
| """Tests for tool_node.py module.""" | ||
|
|
||
| import importlib.util | ||
| import sys | ||
| from typing import Any, Dict | ||
|
|
||
| import pytest | ||
| from langchain.tools import ToolRuntime | ||
| from langchain_core.messages import AIMessage, HumanMessage | ||
| from langchain_core.messages.tool import ToolCall, ToolMessage | ||
| from langchain_core.tools import BaseTool | ||
| from langchain_core.tools import BaseTool, StructuredTool | ||
| from langgraph.types import Command | ||
| from pydantic import BaseModel | ||
|
|
||
| from uipath_langchain.agent.tools.tool_node import ( | ||
| ToolWrapperMixin, | ||
| UiPathToolNode, | ||
| create_tool_node, | ||
| ) | ||
| from pydantic import BaseModel, Field | ||
|
|
||
|
|
||
| # Import directly from module file to avoid circular import through __init__.py | ||
| def _import_tool_node() -> Any: | ||
| """Import tool_node module directly to bypass circular import.""" | ||
| import os | ||
|
|
||
| module_path = os.path.join( | ||
| os.path.dirname(__file__), | ||
| "..", | ||
| "..", | ||
| "..", | ||
| "src", | ||
| "uipath_langchain", | ||
| "agent", | ||
| "tools", | ||
| "tool_node.py", | ||
| ) | ||
| module_path = os.path.abspath(module_path) | ||
| spec = importlib.util.spec_from_file_location("tool_node", module_path) | ||
| assert spec is not None and spec.loader is not None | ||
| module = importlib.util.module_from_spec(spec) | ||
| sys.modules["tool_node"] = module | ||
| spec.loader.exec_module(module) | ||
| return module | ||
|
|
||
|
|
||
| _tool_node_module = _import_tool_node() | ||
|
Comment on lines
+17
to
+41
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm really not a fan of introducing such hacks to "solve" circular imports. |
||
| ToolWrapperMixin: Any = _tool_node_module.ToolWrapperMixin | ||
| UiPathToolNode: Any = _tool_node_module.UiPathToolNode | ||
| create_tool_node: Any = _tool_node_module.create_tool_node | ||
|
|
||
|
|
||
| class MockTool(BaseTool): | ||
|
|
@@ -317,3 +345,206 @@ def test_create_tool_node_empty_tools(self): | |
| result = create_tool_node([]) | ||
|
|
||
| assert result == {} | ||
|
|
||
|
|
||
| class RuntimeToolInput(BaseModel): | ||
| """Input schema for runtime tools.""" | ||
|
|
||
| input_text: str = Field(default="", description="Input text") | ||
|
|
||
|
|
||
| class RegularToolInput(BaseModel): | ||
| """Input schema for regular tools.""" | ||
|
|
||
| input_text: str = Field(default="", description="Input text") | ||
|
|
||
|
|
||
| class TestRuntimeInjection: | ||
| """Test cases for ToolRuntime injection feature.""" | ||
|
|
||
| @pytest.fixture | ||
| def mock_state(self): | ||
| """Fixture for mock state with tool call.""" | ||
| tool_call = { | ||
| "name": "runtime_tool", | ||
| "args": {"input_text": "test input"}, | ||
| "id": "test_call_id_123", | ||
| } | ||
| ai_message = AIMessage(content="Using tool", tool_calls=[tool_call]) | ||
| return MockState(messages=[ai_message]) | ||
|
|
||
| @pytest.fixture | ||
| def mock_state_regular(self): | ||
| """Fixture for mock state with regular tool call.""" | ||
| tool_call = { | ||
| "name": "regular_tool", | ||
| "args": {"input_text": "test input"}, | ||
| "id": "regular_call_id", | ||
| } | ||
| ai_message = AIMessage(content="Using tool", tool_calls=[tool_call]) | ||
| return MockState(messages=[ai_message]) | ||
|
|
||
| def test_detect_runtime_injection_true(self): | ||
| """Test _detect_runtime_injection returns True for tools with runtime param.""" | ||
|
|
||
| async def tool_with_runtime(runtime: ToolRuntime, **kwargs: Any) -> str: | ||
| return f"Got runtime with tool_call_id: {runtime.tool_call_id}" | ||
|
|
||
| tool = StructuredTool( | ||
| name="runtime_tool", | ||
| description="Tool that requires runtime", | ||
| args_schema=RuntimeToolInput, | ||
| coroutine=tool_with_runtime, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
| assert node._needs_runtime is True | ||
|
|
||
| def test_detect_runtime_injection_false(self): | ||
| """Test _detect_runtime_injection returns False for tools without runtime.""" | ||
|
|
||
| async def tool_without_runtime(input_text: str = "") -> str: | ||
| return f"Result: {input_text}" | ||
|
|
||
| tool = StructuredTool( | ||
| name="regular_tool", | ||
| description="Tool without runtime", | ||
| args_schema=RegularToolInput, | ||
| coroutine=tool_without_runtime, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
| assert node._needs_runtime is False | ||
|
|
||
| def test_detect_runtime_injection_base_tool(self): | ||
| """Test _detect_runtime_injection returns False for BaseTool subclass.""" | ||
| tool = MockTool() | ||
| node = UiPathToolNode(tool) | ||
| assert node._needs_runtime is False | ||
|
|
||
| async def test_async_tool_execution_with_runtime_injection(self, mock_state): | ||
| """Test async tool execution with runtime injection.""" | ||
| captured_runtime: Dict[str, Any] = {} | ||
|
|
||
| async def tool_with_runtime(runtime: ToolRuntime, **kwargs: Any) -> str: | ||
| captured_runtime["tool_call_id"] = runtime.tool_call_id | ||
| captured_runtime["state"] = runtime.state | ||
| return f"Success with id: {runtime.tool_call_id}" | ||
|
|
||
| tool = StructuredTool( | ||
| name="runtime_tool", | ||
| description="Tool that requires runtime", | ||
| args_schema=RuntimeToolInput, | ||
| coroutine=tool_with_runtime, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
|
|
||
| result = await node._afunc(mock_state) | ||
|
|
||
| assert result is not None | ||
| assert "messages" in result | ||
| tool_message = result["messages"][0] | ||
| assert "Success with id: test_call_id_123" in tool_message.content | ||
| assert captured_runtime["tool_call_id"] == "test_call_id_123" | ||
| assert captured_runtime["state"] == mock_state | ||
|
|
||
| def test_sync_tool_execution_with_runtime_injection(self, mock_state): | ||
| """Test sync tool execution with runtime injection.""" | ||
| captured_runtime: Dict[str, Any] = {} | ||
|
|
||
| def tool_with_runtime(runtime: ToolRuntime, **kwargs: Any) -> str: | ||
| captured_runtime["tool_call_id"] = runtime.tool_call_id | ||
| return f"Sync success with id: {runtime.tool_call_id}" | ||
|
|
||
| tool = StructuredTool( | ||
| name="runtime_tool", | ||
| description="Tool that requires runtime", | ||
| args_schema=RuntimeToolInput, | ||
| func=tool_with_runtime, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
|
|
||
| result = node._func(mock_state) | ||
|
|
||
| assert result is not None | ||
| assert "messages" in result | ||
| tool_message = result["messages"][0] | ||
| assert "Sync success with id: test_call_id_123" in tool_message.content | ||
| assert captured_runtime["tool_call_id"] == "test_call_id_123" | ||
|
|
||
| async def test_regular_tool_no_runtime_injection(self, mock_state_regular): | ||
| """Test regular tool execution without runtime injection.""" | ||
|
|
||
| async def regular_tool(input_text: str = "") -> str: | ||
| return f"Regular result: {input_text}" | ||
|
|
||
| tool = StructuredTool( | ||
| name="regular_tool", | ||
| description="Regular tool", | ||
| args_schema=RegularToolInput, | ||
| coroutine=regular_tool, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
|
|
||
| result = await node._afunc(mock_state_regular) | ||
|
|
||
| assert result is not None | ||
| assert "messages" in result | ||
| tool_message = result["messages"][0] | ||
| assert "Regular result: test input" in tool_message.content | ||
|
|
||
| async def test_tool_returning_command_with_runtime(self, mock_state): | ||
| """Test tool with runtime returning a Command.""" | ||
|
|
||
| async def tool_with_command( | ||
| runtime: ToolRuntime, **kwargs: Any | ||
| ) -> Command[Any]: | ||
| return Command( | ||
| update={ | ||
| "messages": [ | ||
| ToolMessage( | ||
| content="Completed", | ||
| tool_call_id=runtime.tool_call_id, | ||
| ) | ||
| ] | ||
| }, | ||
| goto="next_node", | ||
| ) | ||
|
|
||
| tool = StructuredTool( | ||
| name="runtime_tool", | ||
| description="Tool with runtime returning command", | ||
| args_schema=RuntimeToolInput, | ||
| coroutine=tool_with_command, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
|
|
||
| result = await node._afunc(mock_state) | ||
|
|
||
| assert isinstance(result, Command) | ||
| assert result.goto == "next_node" | ||
| assert result.update is not None | ||
| assert result.update["messages"][0].tool_call_id == "test_call_id_123" | ||
|
|
||
| def test_get_tool_args_with_runtime(self): | ||
| """Test _get_tool_args injects ToolRuntime when needed.""" | ||
|
|
||
| async def tool_with_runtime(runtime: ToolRuntime, **kwargs: Any) -> str: | ||
| return "ok" | ||
|
|
||
| tool = StructuredTool( | ||
| name="runtime_tool", | ||
| description="Tool with runtime", | ||
| args_schema=RuntimeToolInput, | ||
| coroutine=tool_with_runtime, | ||
| ) | ||
| node = UiPathToolNode(tool) | ||
|
|
||
| call = {"name": "test", "args": {"input_text": "hi"}, "id": "call_123"} | ||
| state = MockState(messages=[]) | ||
| config = {"configurable": {"thread_id": "test_thread"}} | ||
|
|
||
| args = node._get_tool_args(call, state, config) | ||
|
|
||
| assert "runtime" in args | ||
| assert args["runtime"].tool_call_id == "call_123" | ||
| assert args["runtime"].state == state | ||
| assert args["input_text"] == "hi" | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Personally I would take an entirely different approach here.
I'd say tools themselves should never return messages or commands. A tool should only ever return its output schema.
Keep them completely graph-agnostic.
In the custom tool node design, the idea is for the wrappers to return commands if needed.
If anything, escalation tool should be refactored to no longer be coupled to the graph, which is something that should be in the works already.