@devries-cameron20 / composio Mirror · read-only / commits / 879aee1fe
Fork 0

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, 22:00 UTC

docs: update custom provider documentation and scripts for clarity and consistency

balyan.sid@gmail.com committed Jul 2, 2025 at 13:54 UTC 879aee1fed561f69abc4d943c0be17b53145483d
3 files changed +291 -366
fern/pages/src/providers/py-custom.mdx
+192 -293
@@ -12,8 +12,7 @@ This guide shows how to create custom providers for the Composio Python SDK. Cus
12 The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:
13
14 1. **Tool format transformation**: Converting Composio tools into formats compatible with specific AI platforms
15 -2. **Tool execution**: Managing the flow of tool execution and results
16 -3. **Platform-specific integration**: Providing helper methods for seamless integration
15 +2. **Platform-specific integration**: Providing helper methods for seamless integration
16
17 ## Types of providers
18
@@ -48,14 +47,14 @@ make create-provider name=myagent agentic=true
47 ```
48
49 This will create a new provider in `python/providers/<provider-name>/` with:
51 -- Complete package structure with `pyproject.toml` and `setup.py`
50 +- Complete package structure with `pyproject.toml`
51 - Provider implementation template
52 - Demo script
53 - README with usage examples
54 - Type annotations and proper inheritance
55
56 <Tip>
58 -The scaffolding script creates a fully functional provider template. You just need to implement the tool transformation logic specific to your platform.
57 +The scaffolding script creates a fully functional provider template. You just need to implement the tool transformation logic specific to your platform. You can maintain your provider implementation in your own repository.
58 </Tip>
59
60 ### Generated structure
@@ -65,7 +64,7 @@ The create-provider script generates the following structure:
64 ```
65 python/providers/<provider-name>/
66 ├── README.md # Documentation and usage examples
68 -├── pyproject.toml # Poetry configuration
67 +├── pyproject.toml # Project configuration
68 ├── setup.py # Setup script for pip compatibility
69 ├── <provider-name>_demo.py # Demo script showing usage
70 └── composio_<provider-name>/ # Package directory
@@ -126,7 +125,14 @@ class MyAIProvider(NonAgenticProvider[MyAITool, MyAIToolCollection], name="my-ai
125 tool_call: dict,
126 modifiers: Optional[Modifiers] = None
127 ) -> ToolExecutionResponse:
129 - """Execute a tool call in your platform's format"""
128 + """Execute a tool call in your platform's format
129 +
130 + Example usage:
131 + result = my_provider.execute_my_ai_tool_call(
132 + user_id="default",
133 + tool_call={"name": "GITHUB_STAR_REPO", "arguments": {"owner": "composiohq", "repo": "composio"}}
134 + )
135 + """
136 # Use the built-in execute_tool method
137 return self.execute_tool(
138 slug=tool_call["name"],
@@ -144,27 +150,21 @@ Agentic providers inherit from the `AgenticProvider` abstract class:
150 from typing import Callable, Dict, List, Sequence
151 from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
152 from composio.types import Tool
153 +from my_provider import AgentTool
154
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 +# Import the Tool/Function class represents a callable tool for your framework. Optionally define your tool format
156 +# class AgentTool:
157 +# def __init__(self, name: str, description: str, execute: Callable, schema: dict):
158 +# self.name = name
159 +# self.description = description
160 +# self.execute = execute
161 +# self.schema = schema
162
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
163 +# Define your tool collection format (typically a List)
164 +AgentToolCollection: TypeAlias = List[AgentTool]
165
166 # Create your provider
167 -class MyAgentProvider(AgenticProvider[AgentTool, AgentToolkit], name="my-agent-platform"):
167 +class MyAgentProvider(AgenticProvider[AgentTool, list[AgentTool]], name="my-agent-platform"):
168 """Custom provider for My Agent Platform"""
169
170 def wrap_tool(self, tool: Tool, execute_tool: AgenticProviderExecuteFn) -> AgentTool:
@@ -186,346 +186,245 @@ class MyAgentProvider(AgenticProvider[AgentTool, AgentToolkit], name="my-agent-p
186 self,
187 tools: Sequence[Tool],
188 execute_tool: AgenticProviderExecuteFn
189 - ) -> AgentToolkit:
189 + ) -> AgentToolCollection:
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)
191 + return [self.wrap_tool(tool, execute_tool) for tool in tools]
192 ```
193
194 ## Using your custom provider
195
196 After creating your provider, use it with the Composio SDK:
197
198 +### Non-agentic provider example
199 +
200 ```python
201 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
202 +from composio_myai import MyAIProvider
203 +from myai import MyAIClient # Your AI platform's client
204 +
205 +# Initialize tools
206 +myai_client = MyAIClient()
207 +composio = Composio(provider=MyAIProvider())
208 +
209 +# Define task
210 +task = "Star a repo composiohq/composio on GitHub"
211 +
212 +# Get GitHub tools that are pre-configured
213 +tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
214 +
215 +# Get response from your AI platform (example)
216 +response = myai_client.chat.completions.create(
217 + model="your-model",
218 + tools=tools, # These are in your platform's format
219 + messages=[
220 + {"role": "system", "content": "You are a helpful assistant."},
221 + {"role": "user", "content": task},
222 + ],
223 )
224 +print(response)
225
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 -)
226 +# Execute the function calls
227 +result = composio.provider.handle_tool_calls(response=response, user_id="default")
228 +print(result)
229 ```
230
234 -## Provider state and context
235 -
236 -Your provider can maintain state and context:
231 +### Agentic provider example
232
233 ```python
239 -from typing import Dict, Optional
240 -from composio.core.provider import NonAgenticProvider
234 +import asyncio
235 +from agents import Agent, Runner
236 +from composio_myagent import MyAgentProvider
237 +from composio import Composio
238
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 -```
239 +# Initialize Composio toolset
240 +composio = Composio(provider=MyAgentProvider())
241
281 -## Advanced: Provider composition
242 +# Get all the tools
243 +tools = composio.tools.get(
244 + user_id="default",
245 + tools=["GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER"],
246 +)
247
283 -You can compose functionality by extending existing providers:
248 +# Create an agent with the tools
249 +agent = Agent(
250 + name="GitHub Agent",
251 + instructions="You are a helpful assistant that helps users with GitHub tasks.",
252 + tools=tools,
253 +)
254
285 -```python
286 -import time
287 -from composio_openai import OpenAIProvider
288 -from typing import Optional
289 -from composio.types import Modifiers
290 -
291 -# Extend the OpenAI provider with custom functionality
292 -class EnhancedOpenAIProvider(OpenAIProvider):
293 - """OpenAI provider with analytics and retry logic"""
294 -
295 - def __init__(self):
296 - super().__init__()
297 - # Add properties
298 - self.analytics = {
299 - "tool_calls": 0,
300 - "errors": 0
301 - }
302 -
303 - def execute_tool_call(
304 - self,
305 - user_id: str,
306 - tool_call,
307 - modifiers: Optional[Modifiers] = None
308 - ):
309 - """Execute tool call with analytics"""
310 - self.analytics["tool_calls"] += 1
311 -
312 - try:
313 - # Call the parent implementation
314 - result = super().execute_tool_call(user_id, tool_call, modifiers)
315 - return result
316 - except Exception as error:
317 - self.analytics["errors"] += 1
318 - raise error
319 -
320 - # Add new methods
321 - def get_analytics(self) -> dict:
322 - """Get provider analytics"""
323 - return self.analytics.copy()
324 -
325 - def execute_with_retry(
326 - self,
327 - user_id: str,
328 - tool_call,
329 - modifiers: Optional[Modifiers] = None,
330 - max_retries: int = 3
331 - ):
332 - """Execute tool call with retry logic"""
333 - attempts = 0
334 - last_error = None
335 -
336 - while attempts < max_retries:
337 - try:
338 - return self.execute_tool_call(user_id, tool_call, modifiers)
339 - except Exception as error:
340 - last_error = error
341 - attempts += 1
342 - time.sleep(1.0 * attempts)
343 -
344 - raise last_error
255 +# Run the agent
256 +async def main():
257 + result = await Runner.run(
258 + starting_agent=agent,
259 + input=(
260 + "Star the repository composiohq/composio on GitHub. If done "
261 + "successfully, respond with 'Action executed successfully'"
262 + ),
263 + )
264 + print(result.final_output)
265 +
266 +asyncio.run(main())
267 ```
268
269 +
270 ## Example: Anthropic Claude provider
271
272 Here's a complete example for Anthropic's Claude:
273
274 ```python
275 import typing as t
353 -from anthropic import Anthropic
354 -from anthropic.types.message import Message
276 +
277 +from anthropic.types.beta.beta_tool_use_block import BetaToolUseBlock
278 +from anthropic.types.message import Message as ToolsBetaMessage
279 from anthropic.types.tool_param import ToolParam
280 from anthropic.types.tool_use_block import ToolUseBlock
281
282 from composio.core.provider import NonAgenticProvider
359 -from composio.types import Tool, Modifiers, ToolExecutionResponse
283 +from composio.types import Modifiers, Tool, ToolExecutionResponse
284 +
285 +
286 +class AnthropicProvider(
287 + NonAgenticProvider[ToolParam, list[ToolParam]],
288 + name="anthropic",
289 +):
290 + """Composio toolset for Anthropic Claude platform."""
291
361 -class ClaudeProvider(NonAgenticProvider[ToolParam, list[ToolParam]], name="claude"):
362 - """Provider for Anthropic Claude"""
363 -
364 - def __init__(self, api_key: str):
365 - self.client = Anthropic(api_key=api_key)
366 -
292 def wrap_tool(self, tool: Tool) -> ToolParam:
368 - """Convert Composio tool to Claude format"""
293 return ToolParam(
294 + input_schema=tool.input_parameters,
295 name=tool.slug,
296 description=tool.description,
372 - input_schema=tool.input_parameters
297 )
374 -
298 +
299 def wrap_tools(self, tools: t.Sequence[Tool]) -> list[ToolParam]:
376 - """Convert multiple tools"""
300 return [self.wrap_tool(tool) for tool in tools]
378 -
301 +
302 def execute_tool_call(
303 self,
304 user_id: str,
382 - tool_use: ToolUseBlock,
383 - modifiers: t.Optional[Modifiers] = None
305 + tool_call: ToolUseBlock,
306 + modifiers: t.Optional[Modifiers] = None,
307 ) -> ToolExecutionResponse:
385 - """Execute a Claude tool call"""
308 + """Execute a tool call.
309 +
310 + :param user_id: User ID to use for executing function calls.
311 + :param tool_call: Tool call metadata.
312 + :param modifiers: Modifiers to use for executing function calls.
313 + :return: Object containing output data from the tool call.
314 + """
315 return self.execute_tool(
387 - slug=tool_use.name,
388 - arguments=dict(tool_use.input),
316 + slug=tool_call.name,
317 + arguments=t.cast(t.Dict, tool_call.input),
318 modifiers=modifiers,
390 - user_id=user_id
319 + user_id=user_id,
320 )
392 -
393 - # Helper method to create a Claude message with tools
394 - async def create_message(
321 +
322 + def handle_tool_calls(
323 self,
396 - prompt: str,
397 - tools: list[ToolParam],
398 - user_id: str
399 - ) -> Message:
400 - """Create a message and handle tool calls"""
401 - response = self.client.messages.create(
402 - model="claude-3-opus-20240229",
403 - max_tokens=1024,
404 - messages=[{"role": "user", "content": prompt}],
405 - tools=tools
406 - )
324 + user_id: str,
325 + response: t.Union[dict, ToolsBetaMessage],
326 + modifiers: t.Optional[Modifiers] = None,
327 + ) -> t.List[ToolExecutionResponse]:
328 + """Handle tool calls from Anthropic Claude chat completion object.
329
408 - # Process tool calls if any
409 - tool_results = []
330 + :param response: Chat completion object from
331 + `anthropic.Anthropic.beta.tools.messages.create` function call.
332 + :param user_id: User ID to use for executing function calls.
333 + :param modifiers: Modifiers to use for executing function calls.
334 + :return: A list of output objects from the tool calls.
335 + """
336 + if isinstance(response, dict):
337 + response = ToolsBetaMessage(**response)
338 +
339 + outputs = []
340 for content in response.content:
411 - if content.type == "tool_use":
412 - result = self.execute_tool_call(
413 - user_id=user_id,
414 - tool_use=content,
341 + if isinstance(content, (ToolUseBlock, BetaToolUseBlock)):
342 + outputs.append(
343 + self.execute_tool_call(
344 + user_id=user_id,
345 + tool_call=content,
346 + modifiers=modifiers,
347 + )
348 )
416 - tool_results.append({
417 - "type": "tool_result",
418 - "tool_use_id": content.id,
419 - "content": str(result.data)
420 - })
421 -
422 - # Continue conversation with tool results if needed
423 - if tool_results:
424 - response = self.client.messages.create(
425 - model="claude-3-opus-20240229",
426 - max_tokens=1024,
427 - messages=[
428 - {"role": "user", "content": prompt},
429 - {"role": "assistant", "content": response.content},
430 - {"role": "user", "content": tool_results}
431 - ],
432 - tools=tools
433 - )
434 -
435 - return response
349 + return outputs
350 ```
351
438 -## Example: LangChain provider
352 +## Example: OpenAI Agents provider
353
440 -Here's an example for LangChain:
354 +Here's an example for OpenAI Agents framework:
355
356 ```python
443 -import types
444 -from typing import List, Sequence, Dict, Any
445 -from inspect import Signature
357 +import asyncio
358 +import json
359 +import typing as t
360 +
361 +import pydantic
362 +from agents import FunctionTool
363
447 -from langchain_core.tools import StructuredTool
364 from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
365 from composio.types import Tool
450 -from composio.utils.shared import (
451 - get_signature_format_from_schema_params,
452 - json_schema_to_model
453 -)
366 +from composio.utils.pydantic import parse_pydantic_error
367 +
368
455 -class LangChainProvider(
456 - AgenticProvider[StructuredTool, List[StructuredTool]],
457 - name="langchain"
369 +class OpenAIAgentsProvider(
370 + AgenticProvider[FunctionTool, list[FunctionTool]],
371 + name="openai_agents",
372 ):
459 - """Provider for LangChain framework"""
373 + """Provider for OpenAI Agents framework"""
374
461 - def _create_tool_function(
375 + def wrap_tool(
376 self,
463 - tool_slug: str,
464 - description: str,
465 - schema_params: Dict,
466 - execute_tool: AgenticProviderExecuteFn
467 - ):
468 - """Create a wrapped function for the tool"""
469 - def function(**kwargs: Any) -> Dict:
470 - """Wrapper function for composio action"""
471 - return execute_tool(tool_slug, kwargs)
377 + tool: Tool,
378 + execute_tool: AgenticProviderExecuteFn,
379 + ) -> FunctionTool:
380 + """Wrap a tool as a FunctionTool"""
381
473 - # Create a new function with proper metadata
474 - action_func = types.FunctionType(
475 - function.__code__,
476 - globals=globals(),
477 - name=tool_slug,
478 - closure=function.__closure__
479 - )
480 - action_func.__signature__ = Signature(
481 - parameters=get_signature_format_from_schema_params(
482 - schema_params=schema_params
483 - )
484 - )
485 - action_func.__doc__ = description
486 - return action_func
487 -
488 - def wrap_tool(
489 - self,
490 - tool: Tool,
491 - execute_tool: AgenticProviderExecuteFn
492 - ) -> StructuredTool:
493 - """Wrap tool as LangChain StructuredTool"""
494 - return StructuredTool.from_function(
382 + # Create an async wrapper for the tool execution
383 + async def execute_tool_wrapper(_ctx, payload):
384 + """Execute Composio action with the given arguments"""
385 + try:
386 + return json.dumps(
387 + obj=(
388 + await asyncio.to_thread( # Running in thread since execute_tool is not async
389 + execute_tool,
390 + slug=tool.slug,
391 + arguments=json.loads(payload) if payload else {},
392 + )
393 + )
394 + )
395 + except pydantic.ValidationError as e:
396 + return json.dumps({
397 + "successful": False,
398 + "error": parse_pydantic_error(e),
399 + "data": None,
400 + })
401 + except Exception as e:
402 + return json.dumps({
403 + "successful": False,
404 + "error": str(e),
405 + "data": None,
406 + })
407 +
408 + # Ensure the schema has additionalProperties set to false
409 + modified_schema = tool.input_parameters.copy()
410 + modified_schema["additionalProperties"] = False
411 +
412 + # Create a FunctionTool with the appropriate schema
413 + return FunctionTool(
414 name=tool.slug,
415 description=tool.description,
497 - args_schema=json_schema_to_model(
498 - json_schema=tool.input_parameters,
499 - skip_default=True
500 - ),
501 - func=self._create_tool_function(
502 - tool_slug=tool.slug,
503 - description=tool.description,
504 - schema_params=tool.input_parameters,
505 - execute_tool=execute_tool
506 - ),
507 - handle_tool_error=True
416 + params_json_schema=modified_schema,
417 + on_invoke_tool=execute_tool_wrapper,
418 + strict_json_schema=False, # Composio tools already have optimal schemas
419 )
420
421 def wrap_tools(
422 self,
512 - tools: Sequence[Tool],
513 - execute_tool: AgenticProviderExecuteFn
514 - ) -> List[StructuredTool]:
515 - """Wrap multiple tools for LangChain"""
423 + tools: t.Sequence[Tool],
424 + execute_tool: AgenticProviderExecuteFn,
425 + ) -> list[FunctionTool]:
426 + """Wrap multiple tools for OpenAI Agents"""
427 return [self.wrap_tool(tool, execute_tool) for tool in tools]
517 -
518 - # Helper method to create and run an agent
519 - def create_agent_executor(self, tools: List[StructuredTool], llm):
520 - """Create a LangChain agent with tools"""
521 - from langchain.agents import initialize_agent, AgentType
522 -
523 - return initialize_agent(
524 - tools=tools,
525 - llm=llm,
526 - agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
527 - verbose=True
528 - )
428 ```
429
430 ## Best practices
python/Makefile
+2 -2
@@ -19,9 +19,9 @@ create-provider:
19 exit 1;\
20 fi
21 @if [ "$(agentic)" = "true" ]; then\
22 - bash scripts/create-provider.sh $(name) --agentic;\
22 + python scripts/create_provider.py $(name) --agentic;\
23 else\
24 - bash scripts/create-provider.sh $(name);\
24 + python scripts/create_provider.py $(name);\
25 fi
26
27 env:
python/scripts/create-provider.sh
+97 -71
@@ -9,6 +9,7 @@ fi
9
10 PROVIDER_NAME=$1
11 PROVIDER_PATH="python/providers/$PROVIDER_NAME"
12 +# Convert to title case (e.g., myai -> Myai)
13 CAPITAL_PROVIDER_NAME="$(tr '[:lower:]' '[:upper:]' <<< ${PROVIDER_NAME:0:1})${PROVIDER_NAME:1}"
14 PACKAGE_NAME="composio_$PROVIDER_NAME"
15
@@ -29,26 +30,26 @@ mkdir -p "$PROVIDER_PATH/$PACKAGE_NAME"
30
31 # Create pyproject.toml
32 cat > "$PROVIDER_PATH/pyproject.toml" << EOL
32 -[tool.poetry]
33 +[project]
34 name = "$PACKAGE_NAME"
35 version = "0.1.0"
36 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"
38 +requires-python = ">=3.10,<4"
39 +authors = [
40 + { name = "Composio", email = "tech@composio.dev" }
41 +]
42 +classifiers = [
43 + "Programming Language :: Python :: 3",
44 + "License :: OSI Approved :: Apache Software License",
45 + "Operating System :: OS Independent",
46 +]
47 +dependencies = [
48 + "composio",
49 +]
50 +
51 +[project.urls]
52 +Homepage = "https://github.com/ComposioHQ/composio"
53 EOL
54
55 # Create setup.py for backwards compatibility
@@ -99,7 +100,7 @@ cat > "$PROVIDER_PATH/$PACKAGE_NAME/provider.py" << EOL
100 ${CAPITAL_PROVIDER_NAME} Provider implementation.
101 """
102
102 -from typing import List, Sequence, Dict, Any, Callable
103 +from typing import Any, Callable, Dict, List, Sequence
104 from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
105 from composio.types import Tool
106
@@ -114,20 +115,8 @@ class ${CAPITAL_PROVIDER_NAME}Tool:
115 self.schema = schema
116
117
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 -
118 class ${CAPITAL_PROVIDER_NAME}Provider(
130 - AgenticProvider[${CAPITAL_PROVIDER_NAME}Tool, ${CAPITAL_PROVIDER_NAME}Toolkit],
119 + AgenticProvider[${CAPITAL_PROVIDER_NAME}Tool, List[${CAPITAL_PROVIDER_NAME}Tool]],
120 name="${PROVIDER_NAME}"
121 ):
122 """
@@ -157,12 +146,11 @@ class ${CAPITAL_PROVIDER_NAME}Provider(
146 self,
147 tools: Sequence[Tool],
148 execute_tool: AgenticProviderExecuteFn
160 - ) -> ${CAPITAL_PROVIDER_NAME}Toolkit:
149 + ) -> List[${CAPITAL_PROVIDER_NAME}Tool]:
150 """
162 - Get composio tools wrapped as ${CAPITAL_PROVIDER_NAME} toolkit.
151 + Get composio tools wrapped as a list of ${CAPITAL_PROVIDER_NAME} tools.
152 """
164 - wrapped_tools = [self.wrap_tool(tool, execute_tool) for tool in tools]
165 - return ${CAPITAL_PROVIDER_NAME}Toolkit(tools=wrapped_tools)
153 + return [self.wrap_tool(tool, execute_tool) for tool in tools]
154 EOL
155 else
156 cat > "$PROVIDER_PATH/$PACKAGE_NAME/provider.py" << EOL
@@ -170,7 +158,7 @@ cat > "$PROVIDER_PATH/$PACKAGE_NAME/provider.py" << EOL
158 ${CAPITAL_PROVIDER_NAME} Provider implementation.
159 """
160
173 -from typing import List, Optional, Sequence, TypeAlias
161 +from typing import List, Optional, Sequence, TypeAlias, Dict
162 from composio.core.provider import NonAgenticProvider
163 from composio.types import Tool, Modifiers, ToolExecutionResponse
164
@@ -236,7 +224,7 @@ class ${CAPITAL_PROVIDER_NAME}Provider(
224 def handle_tool_calls(
225 self,
226 user_id: str,
239 - response: Any,
227 + response: Dict,
228 modifiers: Optional[Modifiers] = None
229 ) -> List[ToolExecutionResponse]:
230 """
@@ -262,21 +250,49 @@ cat > "$PROVIDER_PATH/${PROVIDER_NAME}_demo.py" << EOL
250 ${CAPITAL_PROVIDER_NAME} demo.
251 """
252
253 +import asyncio
254 +
255 +# from ${PROVIDER_NAME}_framework import Agent, Runner # Import your agent framework
256 from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
257 +
258 from composio import Composio
259
268 -# Initialize tools.
260 +# Initialize Composio toolset
261 composio = Composio(provider=${CAPITAL_PROVIDER_NAME}Provider())
262
271 -# Define task.
272 -task = "Star a repo composiohq/composio on GitHub"
263 +# Get all the tools
264 +tools = composio.tools.get(
265 + user_id="default",
266 + tools=["GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER"],
267 +)
268
274 -# Get GitHub tools that are pre-configured
275 -tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
269 +# TODO: Create an agent with the tools
270 +# agent = Agent(
271 +# name="GitHub Agent",
272 +# instructions="You are a helpful assistant that helps users with GitHub tasks.",
273 +# tools=tools,
274 +# )
275
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!")
276 +
277 +# Run the agent
278 +async def main():
279 + # TODO: Implement your agent execution logic
280 + # result = await Runner.run(
281 + # starting_agent=agent,
282 + # input=(
283 + # "Star the repository composiohq/composio on GitHub. If done "
284 + # "successfully, respond with 'Action executed successfully'"
285 + # ),
286 + # )
287 + # print(result.final_output)
288 +
289 + print("Implement your ${CAPITAL_PROVIDER_NAME} agent logic here!")
290 + print(f"Got {len(tools)} tools:")
291 + for tool in tools:
292 + print(f" - {tool.name}: {tool.description}")
293 +
294 +
295 +asyncio.run(main())
296 EOL
297 else
298 cat > "$PROVIDER_PATH/${PROVIDER_NAME}_demo.py" << EOL
@@ -285,9 +301,12 @@ ${CAPITAL_PROVIDER_NAME} demo.
301 """
302
303 from $PACKAGE_NAME import ${CAPITAL_PROVIDER_NAME}Provider
304 +# from ${PROVIDER_NAME} import ${CAPITAL_PROVIDER_NAME} # Import your AI client
305 +
306 from composio import Composio
307
308 # Initialize tools.
309 +# ${PROVIDER_NAME}_client = ${CAPITAL_PROVIDER_NAME}() # Initialize your AI client
310 composio = Composio(provider=${CAPITAL_PROVIDER_NAME}Provider())
311
312 # Define task.
@@ -296,15 +315,25 @@ task = "Star a repo composiohq/composio on GitHub"
315 # Get GitHub tools that are pre-configured
316 tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
317
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": {...}}
318 +# TODO: Get response from the LLM
319 +# response = ${PROVIDER_NAME}_client.chat.completions.create(
320 +# model="your-model",
321 +# tools=tools,
322 +# messages=[
323 +# {"role": "system", "content": "You are a helpful assistant."},
324 +# {"role": "user", "content": task},
325 +# ],
326 # )
327 +# print(response)
328 +
329 +# TODO: Execute the function calls.
330 +# result = composio.provider.handle_tool_calls(response=response, user_id="default")
331 # print(result)
332 +
333 +print(f"Got {len(tools)} tools for the task: {task}")
334 +for tool in tools:
335 + print(f" - {tool.name}: {tool.description}")
336 +print("\nImplement your ${CAPITAL_PROVIDER_NAME} integration here!")
337 EOL
338 fi
339
@@ -327,8 +356,6 @@ ${IS_AGENTIC:+- **Full Tool Execution**: Execute tools with proper parameter han
356 \`\`\`bash
357 pip install $PACKAGE_NAME
358 # or
330 -poetry add $PACKAGE_NAME
331 -# or
359 uv add $PACKAGE_NAME
360 \`\`\`
361
@@ -377,23 +404,22 @@ tools = composio.tools.get(
404 toolkits=["github"]
405 )
406
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)}
407 +${IS_AGENTIC:+# Use the tools with your agent framework
408 +# TODO: Implement your agent logic here
409 +for tool in tools:
410 + print(f"Tool: {tool.name} - {tool.description}")}${!IS_AGENTIC:+# TODO: Get response from your AI platform (example)
411 +# response = ${PROVIDER_NAME}_client.chat.completions.create(
412 +# model="your-model",
413 +# tools=tools,
414 +# messages=[
415 +# {"role": "system", "content": "You are a helpful assistant."},
416 +# {"role": "user", "content": "Star the composiohq/composio repository"},
417 +# ],
418 +# )
419 +#
420 +# # Execute the function calls
421 +# result = composio.provider.handle_tool_calls(response=response, user_id="default")
422 +# print(result)}
423 \`\`\`
424
425 ## API Reference
@@ -434,7 +460,7 @@ result = provider.execute_tool_call(
460 ## Development
461
462 1. Clone the repository
437 -2. Install dependencies: \`uv sync\` or \`poetry install\`
463 +2. Install dependencies: \`uv sync\`
464 3. Make your changes
465 4. Run tests: \`pytest\`
466 5. Format code: \`ruff format\`