Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 113 lines 3.8 KB
Raw
1 """ComposioLangChain class definition"""
2
3 import types
4 import typing as t
5 from inspect import Signature
6
7 import pydantic
8 from langchain_core.tools import StructuredTool as BaseStructuredTool
9
10 from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
11 from composio.types import Tool
12 from composio.utils.pydantic import parse_pydantic_error
13 from composio.utils.shared import (
14 get_signature_format_from_schema_params,
15 json_schema_to_model,
16 normalize_tool_arguments,
17 reinstate_reserved_python_keywords,
18 substitute_reserved_python_keywords,
19 validate_and_serialize_tool_arguments,
20 )
21
22
23 class StructuredTool(BaseStructuredTool): # type: ignore[misc]
24 def _to_args_and_kwargs(
25 self,
26 tool_input: t.Union[str, t.Dict[str, t.Any]],
27 tool_call_id: t.Optional[str],
28 ) -> t.Tuple[t.Tuple[str, ...], t.Dict[str, t.Any]]:
29 """Validate dynamic-only schemas before LangChain's no-field shortcut."""
30 args_schema = self.args_schema
31 if (
32 isinstance(tool_input, dict)
33 and isinstance(args_schema, type)
34 and issubclass(args_schema, pydantic.BaseModel)
35 ):
36 arguments = validate_and_serialize_tool_arguments(args_schema, tool_input)
37 return (), arguments
38 return super()._to_args_and_kwargs(tool_input, tool_call_id)
39
40 def run(self, *args, **kwargs):
41 try:
42 return super().run(*args, **kwargs)
43 except pydantic.ValidationError as e:
44 return {"successful": False, "error": parse_pydantic_error(e), "data": None}
45
46
47 class LangchainProvider(
48 AgenticProvider[StructuredTool, t.List[StructuredTool]],
49 name="langchain",
50 ):
51 """
52 Composio toolset for Langchain framework.
53 """
54
55 runtime = "langchain"
56
57 def wrap_tool(
58 self, tool: Tool, execute_tool: AgenticProviderExecuteFn
59 ) -> StructuredTool:
60 """Wraps composio tool as Langchain StructuredTool object."""
61 # Replace reserved python keywords
62 schema_params, keywords = substitute_reserved_python_keywords(
63 schema=tool.input_parameters
64 )
65
66 def function(**kwargs: t.Any) -> t.Dict:
67 """Wrapper function for composio action."""
68 kwargs = reinstate_reserved_python_keywords(
69 request=kwargs,
70 keywords=keywords,
71 )
72 # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
73 return execute_tool(tool.slug, normalize_tool_arguments(kwargs))
74
75 action_func = types.FunctionType(
76 function.__code__,
77 globals=globals(),
78 name=tool.slug,
79 closure=function.__closure__,
80 )
81 action_func.__signature__ = Signature( # type: ignore
82 parameters=get_signature_format_from_schema_params(
83 schema_params=schema_params,
84 skip_default=self.skip_default,
85 )
86 )
87 action_func.__doc__ = tool.description
88
89 return t.cast(
90 StructuredTool,
91 StructuredTool.from_function(
92 name=tool.slug,
93 description=tool.description,
94 args_schema=json_schema_to_model(
95 json_schema=schema_params,
96 skip_default=self.skip_default,
97 ),
98 return_schema=True,
99 func=action_func,
100 handle_tool_error=True,
101 handle_validation_error=True,
102 ),
103 )
104
105 def wrap_tools(
106 self,
107 tools: t.Sequence[Tool],
108 execute_tool: AgenticProviderExecuteFn,
109 ) -> t.List[StructuredTool]:
110 """
111 Get composio tools wrapped as Langchain StructuredTool objects.
112 """
113 return [self.wrap_tool(tool=tool, execute_tool=execute_tool) for tool in tools]