Skip to content

Commit

Permalink
Fix langchain error (ENG-1236) (#563)
Browse files Browse the repository at this point in the history
  • Loading branch information
kaavee315 authored Sep 10, 2024
1 parent 1f9b5c4 commit 353942d
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 15 deletions.
15 changes: 2 additions & 13 deletions python/composio/tools/base/abs.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from composio.client.enums import Action as ActionEnum
from composio.exceptions import ComposioSDKError
from composio.utils.logging import WithLogger
from composio.utils.pydantic import parse_pydantic_error


GroupID = t.Literal["runtime", "local", "api"]
Expand Down Expand Up @@ -130,19 +131,7 @@ def parse(self, request: t.Dict) -> ModelType:
try:
return self.model(**request)
except pydantic.ValidationError as e:
message = "Invalid request data provided"
missing = []
others = [""]
for error in e.errors():
param = ".".join(map(str, error["loc"]))
if error["type"] == "missing":
missing.append(param)
continue
others.append(error["msg"] + f" on parameter `{param}`")
if len(missing) > 0:
message += f"\n- Following fields are missing: {set(missing)}"
message += "\n- ".join(others)
raise ValueError(message) from e
raise ValueError(parse_pydantic_error(e)) from e


class _Response(t.Generic[ModelType]):
Expand Down
23 changes: 23 additions & 0 deletions python/composio/utils/pydantic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import typing as t

import pydantic
import pydantic.v1.error_wrappers


def parse_pydantic_error(
e: t.Union[pydantic.ValidationError, pydantic.v1.error_wrappers.ValidationError]
) -> str:
"""Parse pydantic validation error."""
message = "Invalid request data provided"
missing = []
others = [""]
for error in e.errors():
param = ".".join(map(str, error["loc"]))
if error["type"] == "missing":
missing.append(param)
continue
others.append(error["msg"] + f" on parameter `{param}`")
if len(missing) > 0:
message += f"\n- Following fields are missing: {set(missing)}"
message += "\n- ".join(others)
return message
20 changes: 18 additions & 2 deletions python/plugins/langchain/composio_langchain/toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,32 @@
import typing as t
from inspect import Signature

import pydantic
import pydantic.error_wrappers
import pydantic.v1.error_wrappers
import typing_extensions as te
from langchain_core.tools import StructuredTool
from langchain_core.tools import StructuredTool as BaseStructuredTool

from composio import Action, ActionType, AppType, TagType
from composio.tools import ComposioToolSet as BaseComposioToolSet
from composio.utils.pydantic import parse_pydantic_error
from composio.utils.shared import (
get_signature_format_from_schema_params,
json_schema_to_model,
)


class StructuredTool(BaseStructuredTool):
def run(self, *args, **kwargs):
try:
return super().run(*args, **kwargs)
except (
pydantic.ValidationError,
pydantic.v1.error_wrappers.ValidationError,
) as e:
return {"successful": False, "error": parse_pydantic_error(e), "data": None}


class ComposioToolSet(
BaseComposioToolSet,
runtime="langchain",
Expand Down Expand Up @@ -108,13 +123,14 @@ def _wrap_tool(
parameters = json_schema_to_model(
json_schema=schema_params,
)
return StructuredTool.from_function(
tool = StructuredTool.from_function(
name=action,
description=description,
args_schema=parameters,
return_schema=True,
func=action_func,
)
return tool # type: ignore

@te.deprecated("Use `ComposioToolSet.get_tools` instead")
def get_actions(
Expand Down
11 changes: 11 additions & 0 deletions python/tests/test_tools/test_local/test_filetool.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,17 @@ def test_filetool_with_toolset(self, file_manager, temp_dir):
)
assert "New content line" in edit_response["data"]["updated_text"]

# Edit file
edit_response = toolset.execute_action(
Action.FILETOOL_EDIT_FILE,
{
"file_path": "file1.txt",
"start_line": 1,
"end_line": 1,
},
)
assert "Invalid request data provided" in edit_response["error"]

# Verify changes
open_response = toolset.execute_action(
Action.FILETOOL_OPEN_FILE, {"file_path": "file1.txt"}
Expand Down

0 comments on commit 353942d

Please sign in to comment.