Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 23:15 UTC
docs: add Python custom provider documentation and add provider creation scripts.
balyan.sid@gmail.com committed
Jun 30, 2025 at 17:20 UTC
9185b49d99295a21878aa67bbe7c2dc22a84d05f
3 files changed
+1020
-1
fern/pages/src/providers/py-custom.mdx
+534
-1
@@ -1,6 +1,539 @@
1
---
2
-title: Python Custom Provider
2
+title: Python custom provider
3
image: "https://og.composio.dev/api/og?title=Python%20Custom%20Provider" # image for socials
4
keywords: ""
5
hide-nav-links: false
6
---
7
+
8
+This guide provides a comprehensive walkthrough of creating custom providers for the Composio Python SDK, enabling integration with different AI frameworks and platforms.
9
+
10
+## Quick start
11
+
12
+The fastest way to create a new provider is using the provider scaffolding script:
13
+
14
+```bash
15
+# Create a non-agentic provider
16
+make create-provider name=myprovider
17
+
18
+# Create an agentic provider
19
+make create-provider name=myagent agentic=true
20
+```
21
+
22
+This will create a new provider in `python/providers/<provider-name>/` with:
23
+- Complete package structure with `pyproject.toml` and `setup.py`
24
+- Provider implementation template
25
+- Demo script
26
+- README with usage examples
27
+- Type annotations and proper inheritance
28
+
29
+<Tip>
30
+The scaffolding script creates a fully functional provider template. You just need to implement the tool transformation logic specific to your platform.
31
+</Tip>
32
+
33
+### Generated structure
34
+
35
+The create-provider script generates the following structure:
36
+
37
+```
38
+python/providers/<provider-name>/
39
+├── README.md # Documentation and usage examples
40
+├── pyproject.toml # Poetry configuration
41
+├── setup.py # Setup script for pip compatibility
42
+├── <provider-name>_demo.py # Demo script showing usage
43
+└── composio_<provider-name>/ # Package directory
44
+ ├── __init__.py # Package initialization
45
+ ├── provider.py # Provider implementation
46
+ └── py.typed # PEP 561 type marker
47
+```
48
+
49
+After generation, you can:
50
+1. Navigate to the provider directory: `cd python/providers/<provider-name>`
51
+2. Install in development mode: `uv pip install -e .`
52
+3. Implement your provider logic in `composio_<provider-name>/provider.py`
53
+4. Test with the demo script: `python <provider-name>_demo.py`
54
+
55
+## Provider architecture
56
+
57
+The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:
58
+
59
+1. **Tool format transformation**: Converting Composio tools into formats compatible with specific AI platforms
60
+2. **Tool execution**: Managing the flow of tool execution and results
61
+3. **Platform-specific integration**: Providing helper methods for seamless integration
62
+
63
+## Types of providers
64
+
65
+There are two types of providers:
66
+
67
+1. **Non-agentic providers**: Transform tools for platforms that don't have their own agency (e.g., OpenAI, Anthropic)
68
+2. **Agentic providers**: Transform tools for platforms that have their own agency (e.g., LangChain, CrewAI)
69
+
70
+## Provider class hierarchy
71
+
72
+```
73
+BaseProvider (Abstract)
74
+├── NonAgenticProvider (Abstract)
75
+│ └── OpenAIProvider (Concrete)
76
+│ └── AnthropicProvider (Concrete)
77
+│ └── [Your Custom Non-Agentic Provider] (Concrete)
78
+└── AgenticProvider (Abstract)
79
+ └── LangchainProvider (Concrete)
80
+ └── [Your Custom Agentic Provider] (Concrete)
81
+```
82
+
83
+## Creating a non-agentic provider
84
+
85
+Non-agentic providers inherit from the `NonAgenticProvider` abstract class:
86
+
87
+```python
88
+from typing import List, Optional, Sequence, TypeAlias
89
+from composio.core.provider import NonAgenticProvider
90
+from composio.types import Tool, Modifiers, ToolExecutionResponse
91
+
92
+# Define your tool format
93
+class MyAITool:
94
+ def __init__(self, name: str, description: str, parameters: dict):
95
+ self.name = name
96
+ self.description = description
97
+ self.parameters = parameters
98
+
99
+# Define your tool collection format
100
+MyAIToolCollection: TypeAlias = List[MyAITool]
101
+
102
+# Create your provider
103
+class MyAIProvider(NonAgenticProvider[MyAITool, MyAIToolCollection], name="my-ai-platform"):
104
+ """Custom provider for My AI Platform"""
105
+
106
+ def wrap_tool(self, tool: Tool) -> MyAITool:
107
+ """Transform a single tool to platform format"""
108
+ return MyAITool(
109
+ name=tool.slug,
110
+ description=tool.description or "",
111
+ parameters={
112
+ "type": "object",
113
+ "properties": tool.input_parameters.get("properties", {}),
114
+ "required": tool.input_parameters.get("required", [])
115
+ }
116
+ )
117
+
118
+ def wrap_tools(self, tools: Sequence[Tool]) -> MyAIToolCollection:
119
+ """Transform a collection of tools"""
120
+ return [self.wrap_tool(tool) for tool in tools]
121
+
122
+ # Optional: Custom helper methods for your AI platform
123
+ def execute_my_ai_tool_call(
124
+ self,
125
+ user_id: str,
126
+ tool_call: dict,
127
+ modifiers: Optional[Modifiers] = None
128
+ ) -> ToolExecutionResponse:
129
+ """Execute a tool call in your platform's format"""
130
+ # Use the built-in execute_tool method
131
+ return self.execute_tool(
132
+ slug=tool_call["name"],
133
+ arguments=tool_call["arguments"],
134
+ modifiers=modifiers,
135
+ user_id=user_id
136
+ )
137
+```
138
+
139
+## Creating an agentic provider
140
+
141
+Agentic providers inherit from the `AgenticProvider` abstract class:
142
+
143
+```python
144
+from typing import Callable, Dict, List, Sequence
145
+from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
146
+from composio.types import Tool
147
+
148
+# Define your tool format
149
+class AgentTool:
150
+ def __init__(self, name: str, description: str, execute: Callable, schema: dict):
151
+ self.name = name
152
+ self.description = description
153
+ self.execute = execute
154
+ self.schema = schema
155
+
156
+# Define your tool collection format
157
+class AgentToolkit:
158
+ def __init__(self, tools: List[AgentTool]):
159
+ self.tools = tools
160
+
161
+ def create_agent(self, config: dict):
162
+ """Create an agent using the tools"""
163
+ # Implementation depends on your agent framework
164
+ pass
165
+
166
+# Create your provider
167
+class MyAgentProvider(AgenticProvider[AgentTool, AgentToolkit], name="my-agent-platform"):
168
+ """Custom provider for My Agent Platform"""
169
+
170
+ def wrap_tool(self, tool: Tool, execute_tool: AgenticProviderExecuteFn) -> AgentTool:
171
+ """Transform a single tool with execute function"""
172
+ def execute_wrapper(**kwargs) -> Dict:
173
+ result = execute_tool(tool.slug, kwargs)
174
+ if not result.get("successful", False):
175
+ raise Exception(result.get("error", "Tool execution failed"))
176
+ return result.get("data", {})
177
+
178
+ return AgentTool(
179
+ name=tool.slug,
180
+ description=tool.description or "",
181
+ execute=execute_wrapper,
182
+ schema=tool.input_parameters
183
+ )
184
+
185
+ def wrap_tools(
186
+ self,
187
+ tools: Sequence[Tool],
188
+ execute_tool: AgenticProviderExecuteFn
189
+ ) -> AgentToolkit:
190
+ """Transform a collection of tools with execute function"""
191
+ agent_tools = [self.wrap_tool(tool, execute_tool) for tool in tools]
192
+ return AgentToolkit(tools=agent_tools)
193
+
194
+ # Optional: Custom helper methods for your agent platform
195
+ def run_agent(self, toolkit: AgentToolkit, prompt: str, config: dict = None):
196
+ """Run the agent with a prompt"""
197
+ agent = toolkit.create_agent(config or {})
198
+ return agent.run(prompt)
199
+```
200
+
201
+## Using your custom provider
202
+
203
+After creating your provider, use it with the Composio SDK:
204
+
205
+```python
206
+from composio import Composio
207
+from my_providers import MyAIProvider
208
+
209
+# Create your provider instance
210
+my_provider = MyAIProvider()
211
+
212
+# Initialize Composio with your provider
213
+composio = Composio(
214
+ api_key="your-composio-api-key",
215
+ provider=my_provider
216
+)
217
+
218
+# Get tools - they will be transformed by your provider
219
+tools = composio.tools.get(
220
+ user_id="default",
221
+ toolkits=["github"]
222
+)
223
+
224
+# Use the tools with your AI platform
225
+print(tools) # These will be in your custom format
226
+
227
+# For non-agentic providers, use helper methods
228
+response = my_provider.execute_my_ai_tool_call(
229
+ user_id="default",
230
+ tool_call={"name": "GITHUB_CREATE_REPO", "arguments": {...}}
231
+)
232
+```
233
+
234
+## Provider state and context
235
+
236
+Your provider can maintain state and context:
237
+
238
+```python
239
+from typing import Dict, Optional
240
+from composio.core.provider import NonAgenticProvider
241
+
242
+class StatefulProvider(NonAgenticProvider[ProviderTool, ProviderToolCollection], name="stateful-provider"):
243
+ """Provider with state management"""
244
+
245
+ def __init__(self, config: Dict):
246
+ # Provider state
247
+ self.request_count = 0
248
+ self.tool_cache: Dict[str, ProviderTool] = {}
249
+ self.config = config
250
+
251
+ def wrap_tool(self, tool: Tool) -> ProviderTool:
252
+ """Transform tool with state tracking"""
253
+ self.request_count += 1
254
+
255
+ # Use the provider state/config
256
+ enhanced_tool = ProviderTool(
257
+ name=tool.slug.upper() if self.config.get("use_uppercase") else tool.slug,
258
+ description=tool.description,
259
+ schema=tool.input_parameters
260
+ )
261
+
262
+ # Cache the transformed tool
263
+ self.tool_cache[tool.slug] = enhanced_tool
264
+
265
+ return enhanced_tool
266
+
267
+ def wrap_tools(self, tools: Sequence[Tool]) -> ProviderToolCollection:
268
+ """Transform tools"""
269
+ return [self.wrap_tool(tool) for tool in tools]
270
+
271
+ # Custom methods that use provider state
272
+ def get_request_count(self) -> int:
273
+ """Get the number of tool transformation requests"""
274
+ return self.request_count
275
+
276
+ def get_cached_tool(self, slug: str) -> Optional[ProviderTool]:
277
+ """Retrieve a cached tool"""
278
+ return self.tool_cache.get(slug)
279
+```
280
+
281
+## Advanced: Provider composition
282
+
283
+You can compose functionality by extending existing providers:
284
+
285
+```python
286
+from composio_openai import OpenAIProvider
287
+from typing import Optional
288
+from composio.types import Modifiers
289
+
290
+# Extend the OpenAI provider with custom functionality
291
+class EnhancedOpenAIProvider(OpenAIProvider):
292
+ """OpenAI provider with analytics and retry logic"""
293
+
294
+ def __init__(self):
295
+ super().__init__()
296
+ # Add properties
297
+ self.analytics = {
298
+ "tool_calls": 0,
299
+ "errors": 0
300
+ }
301
+
302
+ def execute_tool_call(
303
+ self,
304
+ user_id: str,
305
+ tool_call,
306
+ modifiers: Optional[Modifiers] = None
307
+ ):
308
+ """Execute tool call with analytics"""
309
+ self.analytics["tool_calls"] += 1
310
+
311
+ try:
312
+ # Call the parent implementation
313
+ result = super().execute_tool_call(user_id, tool_call, modifiers)
314
+ return result
315
+ except Exception as error:
316
+ self.analytics["errors"] += 1
317
+ raise error
318
+
319
+ # Add new methods
320
+ def get_analytics(self) -> dict:
321
+ """Get provider analytics"""
322
+ return self.analytics.copy()
323
+
324
+ def execute_with_retry(
325
+ self,
326
+ user_id: str,
327
+ tool_call,
328
+ modifiers: Optional[Modifiers] = None,
329
+ max_retries: int = 3
330
+ ):
331
+ """Execute tool call with retry logic"""
332
+ attempts = 0
333
+ last_error = None
334
+
335
+ while attempts < max_retries:
336
+ try:
337
+ return self.execute_tool_call(user_id, tool_call, modifiers)
338
+ except Exception as error:
339
+ last_error = error
340
+ attempts += 1
341
+ time.sleep(1.0 * attempts)
342
+
343
+ raise last_error
344
+```
345
+
346
+## Example: Anthropic Claude provider
347
+
348
+Here's a complete example for Anthropic's Claude:
349
+
350
+```python
351
+import typing as t
352
+from anthropic import Anthropic
353
+from anthropic.types.message import Message
354
+from anthropic.types.tool_param import ToolParam
355
+from anthropic.types.tool_use_block import ToolUseBlock
356
+
357
+from composio.core.provider import NonAgenticProvider
358
+from composio.types import Tool, Modifiers, ToolExecutionResponse
359
+
360
+class ClaudeProvider(NonAgenticProvider[ToolParam, list[ToolParam]], name="claude"):
361
+ """Provider for Anthropic Claude"""
362
+
363
+ def __init__(self, api_key: str):
364
+ self.client = Anthropic(api_key=api_key)
365
+
366
+ def wrap_tool(self, tool: Tool) -> ToolParam:
367
+ """Convert Composio tool to Claude format"""
368
+ return ToolParam(
369
+ name=tool.slug,
370
+ description=tool.description,
371
+ input_schema=tool.input_parameters
372
+ )
373
+
374
+ def wrap_tools(self, tools: t.Sequence[Tool]) -> list[ToolParam]:
375
+ """Convert multiple tools"""
376
+ return [self.wrap_tool(tool) for tool in tools]
377
+
378
+ def execute_tool_call(
379
+ self,
380
+ user_id: str,
381
+ tool_use: ToolUseBlock,
382
+ modifiers: t.Optional[Modifiers] = None
383
+ ) -> ToolExecutionResponse:
384
+ """Execute a Claude tool call"""
385
+ return self.execute_tool(
386
+ slug=tool_use.name,
387
+ arguments=dict(tool_use.input),
388
+ modifiers=modifiers,
389
+ user_id=user_id
390
+ )
391
+
392
+ # Helper method to create a Claude message with tools
393
+ async def create_message(
394
+ self,
395
+ prompt: str,
396
+ tools: list[ToolParam],
397
+ user_id: str
398
+ ) -> Message:
399
+ """Create a message and handle tool calls"""
400
+ response = self.client.messages.create(
401
+ model="claude-3-opus-20240229",
402
+ max_tokens=1024,
403
+ messages=[{"role": "user", "content": prompt}],
404
+ tools=tools
405
+ )
406
+
407
+ # Process tool calls if any
408
+ tool_results = []
409
+ for content in response.content:
410
+ if content.type == "tool_use":
411
+ result = self.execute_tool_call(
412
+ user_id=user_id,
413
+ tool_use=content,
414
+ )
415
+ tool_results.append({
416
+ "type": "tool_result",
417
+ "tool_use_id": content.id,
418
+ "content": str(result.data)
419
+ })
420
+
421
+ # Continue conversation with tool results if needed
422
+ if tool_results:
423
+ response = self.client.messages.create(
424
+ model="claude-3-opus-20240229",
425
+ max_tokens=1024,
426
+ messages=[
427
+ {"role": "user", "content": prompt},
428
+ {"role": "assistant", "content": response.content},
429
+ {"role": "user", "content": tool_results}
430
+ ],
431
+ tools=tools
432
+ )
433
+
434
+ return response
435
+```
436
+
437
+## Example: LangChain provider
438
+
439
+Here's an example for LangChain:
440
+
441
+```python
442
+import types
443
+from typing import List, Sequence, Dict, Any
444
+from inspect import Signature
445
+
446
+from langchain_core.tools import StructuredTool
447
+from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
448
+from composio.types import Tool
449
+from composio.utils.shared import (
450
+ get_signature_format_from_schema_params,
451
+ json_schema_to_model
452
+)
453
+
454
+class LangChainProvider(
455
+ AgenticProvider[StructuredTool, List[StructuredTool]],
456
+ name="langchain"
457
+):
458
+ """Provider for LangChain framework"""
459
+
460
+ def _create_tool_function(
461
+ self,
462
+ tool_slug: str,
463
+ description: str,
464
+ schema_params: Dict,
465
+ execute_tool: AgenticProviderExecuteFn
466
+ ):
467
+ """Create a wrapped function for the tool"""
468
+ def function(**kwargs: Any) -> Dict:
469
+ """Wrapper function for composio action"""
470
+ return execute_tool(tool_slug, kwargs)
471
+
472
+ # Create a new function with proper metadata
473
+ action_func = types.FunctionType(
474
+ function.__code__,
475
+ globals=globals(),
476
+ name=tool_slug,
477
+ closure=function.__closure__
478
+ )
479
+ action_func.__signature__ = Signature(
480
+ parameters=get_signature_format_from_schema_params(
481
+ schema_params=schema_params
482
+ )
483
+ )
484
+ action_func.__doc__ = description
485
+ return action_func
486
+
487
+ def wrap_tool(
488
+ self,
489
+ tool: Tool,
490
+ execute_tool: AgenticProviderExecuteFn
491
+ ) -> StructuredTool:
492
+ """Wrap tool as LangChain StructuredTool"""
493
+ return StructuredTool.from_function(
494
+ name=tool.slug,
495
+ description=tool.description,
496
+ args_schema=json_schema_to_model(
497
+ json_schema=tool.input_parameters,
498
+ skip_default=True
499
+ ),
500
+ func=self._create_tool_function(
501
+ tool_slug=tool.slug,
502
+ description=tool.description,
503
+ schema_params=tool.input_parameters,
504
+ execute_tool=execute_tool
505
+ ),
506
+ handle_tool_error=True
507
+ )
508
+
509
+ def wrap_tools(
510
+ self,
511
+ tools: Sequence[Tool],
512
+ execute_tool: AgenticProviderExecuteFn
513
+ ) -> List[StructuredTool]:
514
+ """Wrap multiple tools for LangChain"""
515
+ return [self.wrap_tool(tool, execute_tool) for tool in tools]
516
+
517
+ # Helper method to create and run an agent
518
+ def create_agent_executor(self, tools: List[StructuredTool], llm):
519
+ """Create a LangChain agent with tools"""
520
+ from langchain.agents import initialize_agent, AgentType
521
+
522
+ return initialize_agent(
523
+ tools=tools,
524
+ llm=llm,
525
+ agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
526
+ verbose=True
527
+ )
528
+```
529
+
530
+## Best practices
531
+
532
+1. **Keep providers focused**: Each provider should integrate with one specific platform
533
+2. **Handle errors gracefully**: Catch and transform errors from tool execution
534
+3. **Follow platform conventions**: Adopt naming and structural conventions of the target platform
535
+4. **Use type annotations**: Leverage Python's typing system for better IDE support and documentation
536
+5. **Cache transformed tools**: Store transformed tools when appropriate to improve performance
537
+6. **Add helper methods**: Provide convenient methods for common platform-specific operations
538
+7. **Document your provider**: Include docstrings and usage examples
539
+8. **Set meaningful provider names**: Use the name parameter for telemetry and debugging
\ No newline at end of file
python/Makefile
+11
@@ -13,6 +13,17 @@ provider:
13
uv pip install $$provider;\
14
done
15
16
+create-provider:
17
+ @if [ -z "$(name)" ]; then\
18
+ echo "Please provide a provider name: make create-provider name=<provider-name> [agentic=true]";\
19
+ exit 1;\
20
+ fi
21
+ @if [ "$(agentic)" = "true" ]; then\
22
+ bash scripts/create-provider.sh $(name) --agentic;\
23
+ else\
24
+ bash scripts/create-provider.sh $(name);\
25
+ fi
26
+
27
env:
28
@echo "* creating new environment"
29
@if [ -z "$$VIRTUAL_ENV" ];\
python/scripts/create-provider.sh
new
+475
@@ -0,0 +1,475 @@
1
+#!/bin/bash
2
+
3
+# Check if provider name is provided
4
+if [ -z "$1" ]; then
5
+ echo "Please provide a provider name"
6
+ echo "Usage: ./scripts/create-provider.sh <provider-name> [--agentic]"
7
+ exit 1
8
+fi
9
+
10
+PROVIDER_NAME=$1
11
+PROVIDER_PATH="python/providers/$PROVIDER_NAME"
12
+CAPITAL_PROVIDER_NAME="$(tr '[:lower:]' '[:upper:]' <<< ${PROVIDER_NAME:0:1})${PROVIDER_NAME:1}"
13
+PACKAGE_NAME="composio_$PROVIDER_NAME"
14
+
15
+# Check if provider should be agentic
16
+IS_AGENTIC=false
17
+if [ "$2" = "--agentic" ]; then
18
+ IS_AGENTIC=true
19
+fi
20
+
21
+# Check if provider directory already exists
22
+if [ -d "$PROVIDER_PATH" ]; then
23
+ echo "❌ Provider '$PROVIDER_NAME' already exists in $PROVIDER_PATH"
24
+ exit 1
25
+fi
26
+
27
+# Create directory structure
28
+mkdir -p "$PROVIDER_PATH/$PACKAGE_NAME"
29
+
30
+# Create pyproject.toml
31
+cat > "$PROVIDER_PATH/pyproject.toml" << EOL
32
+[tool.poetry]
33
+name = "$PACKAGE_NAME"
34
+version = "0.1.0"
35
+description = "${IS_AGENTIC:+Agentic }Provider for ${CAPITAL_PROVIDER_NAME} in Composio SDK"
36
+authors = ["Your Name <you@example.com>"]
37
+readme = "README.md"
38
+packages = [{include = "$PACKAGE_NAME"}]
39
+
40
+[tool.poetry.dependencies]
41
+python = ">=3.10,<4"
42
+composio = "*"
43
+
44
+[tool.poetry.group.dev.dependencies]
45
+pytest = "^8.3.2"
46
+ruff = "^0.5.7"
47
+mypy = "^1.11.1"
48
+
49
+[build-system]
50
+requires = ["poetry-core"]
51
+build-backend = "poetry.core.masonry.api"
52
+EOL
53
+
54
+# Create setup.py for backwards compatibility
55
+cat > "$PROVIDER_PATH/setup.py" << EOL
56
+from setuptools import setup, find_packages
57
+
58
+setup(
59
+ name="$PACKAGE_NAME",
60
+ version="0.1.0",
61
+ packages=find_packages(),
62
+ install_requires=[
63
+ "composio>=0.1.0",
64
+ ],
65
+ python_requires=">=3.10,<4",
66
+ author="Your Name",
67
+ author_email="you@example.com",
68
+ description="${IS_AGENTIC:+Agentic }Provider for ${CAPITAL_PROVIDER_NAME} in Composio SDK",
69
+ long_description=open("README.md").read(),
70
+ long_description_content_type="text/markdown",
71
+ url="https://github.com/composio/composio",
72
+ classifiers=[
73
+ "Development Status :: 3 - Alpha",
74
+ "Intended Audience :: Developers",
75
+ "License :: OSI Approved :: MIT License",
76
+ "Programming Language :: Python :: 3",
77
+ "Programming Language :: Python :: 3.10",
78
+ "Programming Language :: Python :: 3.11",
79
+ "Programming Language :: Python :: 3.12",
80
+ ],
81
+)
82
+EOL
83
+
84
+# Create __init__.py
85
+cat > "$PROVIDER_PATH/$PACKAGE_NAME/__init__.py" << EOL
86
+"""
87
+${CAPITAL_PROVIDER_NAME} Provider for composio SDK.
88
+"""
89
+
90
+from .$PACKAGE_NAME.provider import ${CAPITAL_PROVIDER_NAME}Provider
91
+
92
+__all__ = ["${CAPITAL_PROVIDER_NAME}Provider"]
93
+EOL
94
+
95
+# Create provider.py
96
+if [ "$IS_AGENTIC" = true ]; then
97
+cat > "$PROVIDER_PATH/$PACKAGE_NAME/provider.py" << EOL
98
+"""
99
+${CAPITAL_PROVIDER_NAME} Provider implementation.
100
+"""
101
+
102
+from typing import List, Sequence, Dict, Any, Callable
103
+from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
104
+from composio.types import Tool
105
+
106
+
107
+# Define your tool format
108
+class ${CAPITAL_PROVIDER_NAME}Tool:
109
+ """${CAPITAL_PROVIDER_NAME} tool format"""
110
+ def __init__(self, name: str, description: str, execute: Callable, schema: dict):
111
+ self.name = name
112
+ self.description = description
113
+ self.execute = execute
114
+ self.schema = schema
115
+
116
+
117
+# Define your tool collection format
118
+class ${CAPITAL_PROVIDER_NAME}Toolkit:
119
+ """${CAPITAL_PROVIDER_NAME} toolkit format"""
120
+ def __init__(self, tools: List[${CAPITAL_PROVIDER_NAME}Tool]):
121
+ self.tools = tools
122
+
123
+ def create_agent(self, config: dict) -> Any:
124
+ """Create an agent using the tools"""
125
+ # TODO: Implement agent creation logic
126
+ raise NotImplementedError("Agent creation not implemented yet")
127
+
128
+
129
+class ${CAPITAL_PROVIDER_NAME}Provider(
130
+ AgenticProvider[${CAPITAL_PROVIDER_NAME}Tool, ${CAPITAL_PROVIDER_NAME}Toolkit],
131
+ name="${PROVIDER_NAME}"
132
+):
133
+ """
134
+ Composio toolset for ${CAPITAL_PROVIDER_NAME} framework.
135
+ """
136
+
137
+ def wrap_tool(
138
+ self,
139
+ tool: Tool,
140
+ execute_tool: AgenticProviderExecuteFn
141
+ ) -> ${CAPITAL_PROVIDER_NAME}Tool:
142
+ """Wrap a tool in the ${PROVIDER_NAME} format."""
143
+ def execute_wrapper(**kwargs) -> Dict:
144
+ result = execute_tool(tool.slug, kwargs)
145
+ if not result.get("successful", False):
146
+ raise Exception(result.get("error", "Tool execution failed"))
147
+ return result.get("data", {})
148
+
149
+ return ${CAPITAL_PROVIDER_NAME}Tool(
150
+ name=tool.slug,
151
+ description=tool.description or "",
152
+ execute=execute_wrapper,
153
+ schema=tool.input_parameters
154
+ )
155
+
156
+ def wrap_tools(
157
+ self,
158
+ tools: Sequence[Tool],
159
+ execute_tool: AgenticProviderExecuteFn
160
+ ) -> ${CAPITAL_PROVIDER_NAME}Toolkit:
161
+ """
162
+ Get composio tools wrapped as ${CAPITAL_PROVIDER_NAME} toolkit.
163
+ """
164
+ wrapped_tools = [self.wrap_tool(tool, execute_tool) for tool in tools]
165
+ return ${CAPITAL_PROVIDER_NAME}Toolkit(tools=wrapped_tools)
166
+EOL
167
+else
168
+cat > "$PROVIDER_PATH/$PACKAGE_NAME/provider.py" << EOL
169
+"""
170
+${CAPITAL_PROVIDER_NAME} Provider implementation.
171
+"""
172
+
173
+from typing import List, Optional, Sequence, TypeAlias
174
+from composio.core.provider import NonAgenticProvider
175
+from composio.types import Tool, Modifiers, ToolExecutionResponse
176
+
177
+
178
+# Define your tool format
179
+class ${CAPITAL_PROVIDER_NAME}Tool:
180
+ """${CAPITAL_PROVIDER_NAME} tool format"""
181
+ def __init__(self, name: str, description: str, parameters: dict):
182
+ self.name = name
183
+ self.description = description
184
+ self.parameters = parameters
185
+
186
+
187
+# Define your tool collection format
188
+${CAPITAL_PROVIDER_NAME}ToolCollection: TypeAlias = List[${CAPITAL_PROVIDER_NAME}Tool]
189
+
190
+
191
+class ${CAPITAL_PROVIDER_NAME}Provider(
192
+ NonAgenticProvider[${CAPITAL_PROVIDER_NAME}Tool, ${CAPITAL_PROVIDER_NAME}ToolCollection],
193
+ name="${PROVIDER_NAME}"
194
+):
195
+ """
196
+ Composio toolset for ${CAPITAL_PROVIDER_NAME} platform.
197
+ """
198
+
199
+ def wrap_tool(self, tool: Tool) -> ${CAPITAL_PROVIDER_NAME}Tool:
200
+ """Transform a single tool to platform format"""
201
+ return ${CAPITAL_PROVIDER_NAME}Tool(
202
+ name=tool.slug,
203
+ description=tool.description or "",
204
+ parameters={
205
+ "type": "object",
206
+ "properties": tool.input_parameters.get("properties", {}),
207
+ "required": tool.input_parameters.get("required", [])
208
+ }
209
+ )
210
+
211
+ def wrap_tools(self, tools: Sequence[Tool]) -> ${CAPITAL_PROVIDER_NAME}ToolCollection:
212
+ """Transform a collection of tools"""
213
+ return [self.wrap_tool(tool) for tool in tools]
214
+
215
+ def execute_tool_call(
216
+ self,
217
+ user_id: str,
218
+ tool_call: dict,
219
+ modifiers: Optional[Modifiers] = None
220
+ ) -> ToolExecutionResponse:
221
+ """
222
+ Execute a tool call.
223
+
224
+ :param user_id: User ID to use for executing function calls.
225
+ :param tool_call: Tool call metadata containing 'name' and 'arguments'.
226
+ :param modifiers: Modifiers to use for executing function calls.
227
+ :return: Object containing output data from the tool call.
228
+ """
229
+ return self.execute_tool(
230
+ slug=tool_call["name"],
231
+ arguments=tool_call["arguments"],
232
+ modifiers=modifiers,
233
+ user_id=user_id
234
+ )
235
+
236
+ def handle_tool_calls(
237
+ self,
238
+ user_id: str,
239
+ response: Any,
240
+ modifiers: Optional[Modifiers] = None
241
+ ) -> List[ToolExecutionResponse]:
242
+ """
243
+ Handle tool calls from ${CAPITAL_PROVIDER_NAME} response.
244
+
245
+ :param response: Response object from ${CAPITAL_PROVIDER_NAME}
246
+ :param user_id: User ID to use for executing function calls.
247
+ :param modifiers: Modifiers to use for executing function calls.
248
+ :return: A list of output objects from the tool calls.
249
+ """
250
+ # TODO: Implement based on ${CAPITAL_PROVIDER_NAME}'s response format
251
+ raise NotImplementedError("Tool call handling not implemented yet")
252
+EOL
253
+fi
254
+
255
+# Create py.typed marker for PEP 561
256
+touch "$PROVIDER_PATH/$PACKAGE_NAME/py.typed"
257
+
258
+# Create demo script
259
+if [ "$IS_AGENTIC" = true ]; then
260
+cat > "$PROVIDER_PATH/${PROVIDER_NAME}_demo.py" << EOL
261
+"""
262
+${CAPITAL_PROVIDER_NAME} demo.
263
+"""
264
+
265
+from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
266
+from composio import Composio
267
+
268
+# Initialize tools.
269
+composio = Composio(provider=${CAPITAL_PROVIDER_NAME}Provider())
270
+
271
+# Define task.
272
+task = "Star a repo composiohq/composio on GitHub"
273
+
274
+# Get GitHub tools that are pre-configured
275
+tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
276
+
277
+# TODO: Implement agent execution with ${CAPITAL_PROVIDER_NAME}
278
+print(f"Got {len(tools)} tools for the task: {task}")
279
+print("Implement your ${CAPITAL_PROVIDER_NAME} agent logic here!")
280
+EOL
281
+else
282
+cat > "$PROVIDER_PATH/${PROVIDER_NAME}_demo.py" << EOL
283
+"""
284
+${CAPITAL_PROVIDER_NAME} demo.
285
+"""
286
+
287
+from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
288
+from composio import Composio
289
+
290
+# Initialize tools.
291
+composio = Composio(provider=${CAPITAL_PROVIDER_NAME}Provider())
292
+
293
+# Define task.
294
+task = "Star a repo composiohq/composio on GitHub"
295
+
296
+# Get GitHub tools that are pre-configured
297
+tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
298
+
299
+# TODO: Create ${CAPITAL_PROVIDER_NAME} client and use the tools
300
+print(f"Got {len(tools)} tools for the task: {task}")
301
+
302
+# Example tool execution (implement based on ${CAPITAL_PROVIDER_NAME}'s API)
303
+# result = composio.provider.execute_tool_call(
304
+# user_id="default",
305
+# tool_call={"name": "GITHUB_STAR_REPO", "arguments": {...}}
306
+# )
307
+# print(result)
308
+EOL
309
+fi
310
+
311
+# Create README.md
312
+cat > "$PROVIDER_PATH/README.md" << EOL
313
+# $PACKAGE_NAME
314
+
315
+${IS_AGENTIC:+Agentic }Provider for ${CAPITAL_PROVIDER_NAME} in Composio SDK.
316
+
317
+## Features
318
+
319
+${IS_AGENTIC:+- **Full Tool Execution**: Execute tools with proper parameter handling
320
+- **Agent Support**: Create agents with wrapped tools
321
+- **Type Safety**: Full type annotations for better IDE support}${!IS_AGENTIC:+- **Tool Transformation**: Convert Composio tools to ${CAPITAL_PROVIDER_NAME} format
322
+- **Tool Execution**: Execute tools with proper parameter handling
323
+- **Type Safety**: Full type annotations for better IDE support}
324
+
325
+## Installation
326
+
327
+\`\`\`bash
328
+pip install $PACKAGE_NAME
329
+# or
330
+poetry add $PACKAGE_NAME
331
+# or
332
+uv add $PACKAGE_NAME
333
+\`\`\`
334
+
335
+## Quick Start
336
+
337
+\`\`\`python
338
+from composio import Composio
339
+from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
340
+
341
+# Initialize Composio with ${CAPITAL_PROVIDER_NAME} provider
342
+composio = Composio(
343
+ api_key="your-composio-api-key",
344
+ provider=${CAPITAL_PROVIDER_NAME}Provider()
345
+)
346
+
347
+# Get available tools
348
+tools = composio.tools.get(
349
+ user_id="default",
350
+ toolkits=["github", "gmail"]
351
+)
352
+
353
+# Use tools with ${CAPITAL_PROVIDER_NAME}
354
+# TODO: Add your usage example here
355
+\`\`\`
356
+
357
+## Usage Examples
358
+
359
+### Basic Example
360
+
361
+\`\`\`python
362
+from composio import Composio
363
+from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
364
+
365
+# Initialize provider
366
+provider = ${CAPITAL_PROVIDER_NAME}Provider()
367
+
368
+# Initialize Composio
369
+composio = Composio(
370
+ api_key="your-api-key",
371
+ provider=provider
372
+)
373
+
374
+# Get tools
375
+tools = composio.tools.get(
376
+ user_id="default",
377
+ toolkits=["github"]
378
+)
379
+
380
+${IS_AGENTIC:+# Create agent with tools
381
+agent = tools.create_agent({})
382
+
383
+# Run agent
384
+result = agent.run("Star the composiohq/composio repository")
385
+print(result)}${!IS_AGENTIC:+# Execute a tool
386
+result = provider.execute_tool_call(
387
+ user_id="default",
388
+ tool_call={
389
+ "name": "GITHUB_STAR_REPO",
390
+ "arguments": {
391
+ "owner": "composiohq",
392
+ "repo": "composio"
393
+ }
394
+ }
395
+)
396
+print(result)}
397
+\`\`\`
398
+
399
+## API Reference
400
+
401
+### ${CAPITAL_PROVIDER_NAME}Provider Class
402
+
403
+The \`${CAPITAL_PROVIDER_NAME}Provider\` class extends \`${IS_AGENTIC:+AgenticProvider}${!IS_AGENTIC:+NonAgenticProvider}\` and provides ${PROVIDER_NAME}-specific functionality.
404
+
405
+#### Methods
406
+
407
+##### \`wrap_tool(tool: Tool${IS_AGENTIC:+, execute_tool: AgenticProviderExecuteFn}) -> ${CAPITAL_PROVIDER_NAME}Tool\`
408
+
409
+Wraps a tool in the ${PROVIDER_NAME} format.
410
+
411
+\`\`\`python
412
+tool = provider.wrap_tool(composio_tool${IS_AGENTIC:+, execute_tool})
413
+\`\`\`
414
+
415
+##### \`wrap_tools(tools: Sequence[Tool]${IS_AGENTIC:+, execute_tool: AgenticProviderExecuteFn}) -> ${IS_AGENTIC:+${CAPITAL_PROVIDER_NAME}Toolkit}${!IS_AGENTIC:+${CAPITAL_PROVIDER_NAME}ToolCollection}\`
416
+
417
+Wraps multiple tools in the ${PROVIDER_NAME} format.
418
+
419
+\`\`\`python
420
+tools = provider.wrap_tools(composio_tools${IS_AGENTIC:+, execute_tool})
421
+\`\`\`
422
+
423
+${!IS_AGENTIC:+##### \`execute_tool_call(user_id: str, tool_call: dict, modifiers: Optional[Modifiers] = None) -> ToolExecutionResponse\`
424
+
425
+Executes a tool call.
426
+
427
+\`\`\`python
428
+result = provider.execute_tool_call(
429
+ user_id="default",
430
+ tool_call={"name": "TOOL_NAME", "arguments": {...}}
431
+)
432
+\`\`\`}
433
+
434
+## Development
435
+
436
+1. Clone the repository
437
+2. Install dependencies: \`uv sync\` or \`poetry install\`
438
+3. Make your changes
439
+4. Run tests: \`pytest\`
440
+5. Format code: \`ruff format\`
441
+6. Lint code: \`ruff check\`
442
+
443
+## Contributing
444
+
445
+We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
446
+
447
+## License
448
+
449
+ISC License
450
+
451
+## Support
452
+
453
+For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
454
+EOL
455
+
456
+# Make the script executable
457
+chmod +x "$PROVIDER_PATH/${PROVIDER_NAME}_demo.py"
458
+
459
+echo "✨ Created new ${IS_AGENTIC:+agentic }provider at $PROVIDER_PATH"
460
+echo "✨ Provider structure:"
461
+echo " 📁 $PROVIDER_PATH/"
462
+echo " ├── 📄 README.md"
463
+echo " ├── 📄 pyproject.toml"
464
+echo " ├── 📄 setup.py"
465
+echo " ├── 📄 ${PROVIDER_NAME}_demo.py"
466
+echo " └── 📁 $PACKAGE_NAME/"
467
+echo " ├── 📄 __init__.py"
468
+echo " ├── 📄 provider.py"
469
+echo " └── 📄 py.typed"
470
+echo ""
471
+echo "🚀 Next steps:"
472
+echo " 1. cd $PROVIDER_PATH"
473
+echo " 2. Update provider.py with your implementation"
474
+echo " 3. Install in development mode: uv pip install -e ."
475
+echo " 4. Test your provider: python ${PROVIDER_NAME}_demo.py"
\ No newline at end of file