composio-pydanticai 0.7.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ from composio_pydanticai.toolset import ComposioToolSet
2
+
3
+ from composio import Action, App, Tag, Trigger, WorkspaceType, action
4
+
5
+
6
+ __all__ = (
7
+ "Action",
8
+ "App",
9
+ "Tag",
10
+ "Trigger",
11
+ "WorkspaceType",
12
+ "action",
13
+ "ComposioToolSet",
14
+ )
@@ -0,0 +1,199 @@
1
+ import types
2
+ import typing as t
3
+ from inspect import Parameter, Signature
4
+
5
+ from pydantic import ValidationError
6
+ from pydantic_ai.tools import Tool
7
+
8
+ from composio import Action, ActionType, AppType, TagType
9
+ from composio.tools import ComposioToolSet as BaseComposioToolSet
10
+ from composio.tools.toolset import ProcessorsType
11
+ from composio.utils.pydantic import parse_pydantic_error
12
+ from composio.utils.shared import get_signature_format_from_schema_params
13
+
14
+
15
+ class ComposioToolSet(
16
+ BaseComposioToolSet,
17
+ runtime="pydantic_ai",
18
+ description_char_limit=1024,
19
+ action_name_char_limit=64,
20
+ ):
21
+ """
22
+ Composio toolset for Pydantic-AI framework.
23
+ Example:
24
+ ```python
25
+ from dotenv import load_dotenv # type: ignore
26
+ import os
27
+
28
+ from composio import Action
29
+ from composio_pydanticai import ComposioToolSet
30
+ from pydantic_ai import Agent
31
+
32
+
33
+ # Load environment variables from .env
34
+ load_dotenv(".env")
35
+
36
+ # Initialize toolset
37
+ composio_toolset = ComposioToolSet()
38
+
39
+ # Configure max retries for specific tools
40
+ max_retries = {
41
+ Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER: 5,
42
+ Action.GITHUB_CREATE_REPOSITORY: 2
43
+ }
44
+
45
+ # Get GitHub tools with retry configuration
46
+ tools = composio_toolset.get_tools(
47
+ actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER],
48
+ max_retries=max_retries,
49
+ default_max_retries=3
50
+ )
51
+
52
+ # Create an agent with the tools
53
+ agent = Agent(
54
+ model="openai:gpt-4o", # Using a known model name
55
+ tools=tools,
56
+ system_prompt="You are an AI agent that helps users interact with GitHub.
57
+ You can perform various GitHub operations using the available tools.
58
+ When given a task, analyze it and use the appropriate tool to complete it.",
59
+ )
60
+
61
+ # Define task
62
+ task = "Star a repo composiohq/composio on GitHub"
63
+ # Run the agent
64
+ result = agent.run_sync(task)
65
+ ```
66
+ """
67
+
68
+ def _wrap_action(
69
+ self,
70
+ action: str,
71
+ description: str,
72
+ schema_params: t.Dict[str, t.Any],
73
+ entity_id: t.Optional[str] = None,
74
+ ):
75
+ """Create a wrapper function for the Composio action."""
76
+
77
+ async def function(ctx, **kwargs): # pylint: disable=unused-argument
78
+ """Wrapper function for composio action."""
79
+ try:
80
+ return self.execute_action(
81
+ action=Action(value=action),
82
+ params=kwargs,
83
+ entity_id=entity_id or self.entity_id,
84
+ _check_requested_actions=True,
85
+ )
86
+ except ValidationError as e:
87
+ # Return a structured error response that the agent can understand
88
+ return {
89
+ "error": parse_pydantic_error(e),
90
+ "successful": False,
91
+ "data": None,
92
+ }
93
+
94
+ # Create function with type hints
95
+ action_func = types.FunctionType(
96
+ function.__code__,
97
+ globals=globals(),
98
+ name=action,
99
+ closure=function.__closure__,
100
+ )
101
+
102
+ # Get parameters using shared utility
103
+ parameters = get_signature_format_from_schema_params(schema_params)
104
+
105
+ # Add type hints
106
+ params = {param.name: param.annotation for param in parameters}
107
+ action_func.__annotations__ = {
108
+ "ctx": "RunContext[None]",
109
+ "return": t.Dict,
110
+ **params,
111
+ }
112
+
113
+ # Create signature with context parameter first
114
+ ctx_param = Parameter(
115
+ name="ctx",
116
+ kind=Parameter.POSITIONAL_OR_KEYWORD,
117
+ annotation="RunContext[None]",
118
+ )
119
+ action_func.__signature__ = Signature(parameters=[ctx_param] + parameters) # type: ignore
120
+ action_func.__doc__ = description
121
+
122
+ return action_func
123
+
124
+ def _wrap_tool(
125
+ self,
126
+ schema: t.Dict[str, t.Any],
127
+ entity_id: t.Optional[str] = None,
128
+ max_retries: t.Optional[int] = None,
129
+ ) -> Tool:
130
+ """Wraps composio tool as Pydantic-AI Tool object."""
131
+ action = schema["name"]
132
+ description = schema["description"]
133
+ parameters = schema["parameters"]
134
+
135
+ # Create the wrapper function
136
+ action_func = self._wrap_action(
137
+ action=action,
138
+ description=description,
139
+ schema_params=parameters,
140
+ entity_id=entity_id,
141
+ )
142
+
143
+ return Tool(
144
+ function=action_func,
145
+ name=action,
146
+ description=description,
147
+ takes_ctx=True,
148
+ max_retries=max_retries,
149
+ docstring_format="auto",
150
+ )
151
+
152
+ def get_tools(
153
+ self,
154
+ actions: t.Optional[t.Sequence[ActionType]] = None,
155
+ apps: t.Optional[t.Sequence[AppType]] = None,
156
+ tags: t.Optional[t.List[TagType]] = None,
157
+ entity_id: t.Optional[str] = None,
158
+ *,
159
+ max_retries: t.Optional[t.Dict[Action, int]] = None,
160
+ default_max_retries: int = 3,
161
+ processors: t.Optional[ProcessorsType] = None,
162
+ check_connected_accounts: bool = True,
163
+ ) -> t.Sequence[Tool]:
164
+ """
165
+ Get composio tools wrapped as Pydantic-AI Tool objects.
166
+
167
+ Args:
168
+ actions: Optional sequence of actions to get tools for
169
+ apps: Optional sequence of apps to get tools for
170
+ tags: Optional list of tags to filter tools by
171
+ entity_id: Optional entity ID to use for the tools
172
+ max_retries: Optional dict mapping Action enum values to their max retry counts
173
+ default_max_retries: Default max retries for tools not specified in max_retries
174
+ processors: Optional processors to apply to the tools
175
+ check_connected_accounts: Whether to check for connected accounts
176
+
177
+ Returns:
178
+ Sequence of Pydantic-AI Tool objects
179
+ """
180
+ self.validate_tools(apps=apps, actions=actions, tags=tags)
181
+ if processors is not None:
182
+ self._processor_helpers.merge_processors(processors)
183
+
184
+ max_retries = max_retries or {}
185
+
186
+ return [
187
+ self._wrap_tool(
188
+ schema=tool.model_dump(exclude_none=True),
189
+ entity_id=entity_id or self.entity_id,
190
+ max_retries=max_retries.get(Action(tool.name), default_max_retries),
191
+ )
192
+ for tool in self.get_action_schemas(
193
+ actions=actions,
194
+ apps=apps,
195
+ tags=tags,
196
+ check_connected_accounts=check_connected_accounts,
197
+ _populate_requested=True,
198
+ )
199
+ ]
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.2
2
+ Name: composio_pydanticai
3
+ Version: 0.7.7
4
+ Summary: Use Composio to get array of strongly typed tools for Pydantic AI
5
+ Home-page: https://github.com/ComposioHQ/composio
6
+ Author: Siddharth
7
+ Author-email: tech@composio.dev
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9,<4
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: composio_core<0.8.0,>=0.7.0
14
+ Requires-Dist: pydantic-ai
15
+ Dynamic: author
16
+ Dynamic: author-email
17
+ Dynamic: classifier
18
+ Dynamic: description
19
+ Dynamic: description-content-type
20
+ Dynamic: home-page
21
+ Dynamic: requires-dist
22
+ Dynamic: requires-python
23
+ Dynamic: summary
24
+
25
+ ## 🚀🔗 Leveraging Pydantic-AI with Composio
26
+
27
+ Integrate Pydantic-AI agents with Composio to enable direct interaction with external applications, enhancing their capabilities through strongly-typed, validated tools.
28
+
29
+ ### Objective
30
+
31
+ - **Automate GitHub operations** using type-safe instructions via Pydantic-AI's Tool system.
32
+ - Demonstrate how to use Composio's tools with Pydantic-AI's strict type checking and validation.
33
+
34
+ ### Installation and Setup
35
+
36
+ Install the necessary packages and connect your GitHub account to enable agent interactions with GitHub:
37
+
38
+ ```bash
39
+ # Install Composio Pydantic-AI package
40
+ pip install composio-pydanticai
41
+
42
+ # Connect your GitHub account
43
+ composio add github
44
+
45
+ # View available applications you can connect with
46
+ composio apps
47
+ ```
48
+
49
+ ### Usage Steps
50
+
51
+ #### 1. Import Required Packages
52
+
53
+ Set up your environment by importing the necessary components from Composio & Pydantic-AI:
54
+
55
+ ```python
56
+ from dotenv import load_dotenv
57
+ import os
58
+
59
+ from composio import Action
60
+ from composio_pydanticai import ComposioToolSet
61
+ from pydantic_ai import Agent
62
+ ```
63
+
64
+ #### 2. Initialize Tools with Composio
65
+
66
+ Configure and fetch GitHub tools provided by Composio:
67
+
68
+ ```python
69
+ # Initialize toolset
70
+ composio_toolset = ComposioToolSet()
71
+
72
+ # Configure max retries for specific tools
73
+ max_retries = {
74
+ Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER: 5, # More retries for starring
75
+ Action.GITHUB_CREATE_REPOSITORY: 2 # Fewer retries for creation
76
+ }
77
+
78
+ # Get GitHub tools with retry configuration
79
+ tools = composio_toolset.get_tools(
80
+ actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER],
81
+ max_retries=max_retries,
82
+ default_max_retries=3 # Default retries for tools not specified in max_retries
83
+ )
84
+ ```
85
+
86
+ The `max_retries` parameter lets you configure retry attempts per tool, with a default fallback for unspecified tools.
87
+
88
+ #### 3. Set Up the Pydantic-AI Agent
89
+
90
+ Create and configure a Pydantic-AI agent with the Composio tools:
91
+
92
+ ```python
93
+ # Create an agent with the tools
94
+ agent = Agent(
95
+ model="openai:gpt-4-turbo", # Using a known model name
96
+ tools=tools,
97
+ system_prompt="""You are an AI agent that helps users interact with GitHub.
98
+ You can perform various GitHub operations using the available tools.
99
+ When given a task, analyze it and use the appropriate tool to complete it.""",
100
+ )
101
+ ```
102
+
103
+ #### 4. Execute Tasks
104
+
105
+ Run your agent with specific tasks:
106
+
107
+ ```python
108
+ # Define task
109
+ task = "Star a repo composiohq/composio on GitHub"
110
+
111
+ # Run the agent synchronously
112
+ result = agent.run_sync(task)
113
+ print("Result:", result.data)
114
+ print("Trace:\n\n", result.all_messages())
115
+ ```
116
+
117
+ ### Key Features
118
+
119
+ 1. **Type Safety**: Leverages Pydantic-AI's strong type system for parameter validation
120
+ 2. **Async Support**: Built-in support for asynchronous operations
121
+ 3. **Error Handling**: Proper validation error handling with detailed feedback
122
+ 4. **Tool Context**: Automatic context injection for tool execution
123
+ 5. **Flexible Retry Configuration**: Configure retries per tool with fallback defaults
124
+
125
+ ### Advanced Usage
126
+
127
+ The integration supports more complex scenarios:
128
+
129
+ ```python
130
+ # Using multiple tools
131
+ tools = composio_toolset.get_tools(
132
+ actions=[
133
+ Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER,
134
+ Action.GITHUB_CREATE_REPOSITORY
135
+ ],
136
+ max_retries={
137
+ Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER: 5,
138
+ Action.GITHUB_CREATE_REPOSITORY: 2
139
+ }
140
+ )
141
+
142
+ # Filtering tools by tags
143
+ tools = composio_toolset.get_tools(
144
+ tags=["github", "repository"],
145
+ default_max_retries=3
146
+ )
147
+
148
+ # Using app-specific tools
149
+ tools = composio_toolset.get_tools(
150
+ apps=[App.GITHUB],
151
+ max_retries={
152
+ Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER: 5
153
+ }
154
+ )
155
+ ```
156
+
157
+ ### Best Practices
158
+
159
+ 1. Always use proper type hints in your code
160
+ 2. Handle validation errors appropriately
161
+ 3. Use the latest version of both Pydantic-AI and Composio
162
+ 4. Leverage async operations for better performance
163
+ 5. Keep your API keys secure using environment variables
164
+ 6. Configure retries based on the specific needs of each tool
@@ -0,0 +1,6 @@
1
+ composio_pydanticai/__init__.py,sha256=SrZ3LdmHzr9G_LHUkm2kCGa3IV-L7egPURdHSna60zA,252
2
+ composio_pydanticai/toolset.py,sha256=tgXhPMLW5QTiKDHQQ4B7QQ-frfINC0MO4Bhf9w95z8o,6644
3
+ composio_pydanticai-0.7.7.dist-info/METADATA,sha256=x_qnrrpee1jUK1Thp3g-qDYtpe55IhiIzqfAwBYU82k,4812
4
+ composio_pydanticai-0.7.7.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
5
+ composio_pydanticai-0.7.7.dist-info/top_level.txt,sha256=w5yw2VXoYyhN0vFzDfJAK91LjNwHHSwkIBV0TbQZHcw,20
6
+ composio_pydanticai-0.7.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (76.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ composio_pydanticai