Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add docs
haxzie5cd699a42a5a
diff --git a/.gitignore b/.gitignoreindex 658e00171..94114f116 100644--- a/.gitignore+++ b/.gitignore@@ -37,4 +37,7 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json.turbo# lerna-lerna-debug.log*\ No newline at end of file+lerna-debug.log*++# temp files+tempdiff --git a/docs/advanced/custom-providers.md b/docs/advanced/custom-providers.mdnew file mode 100644index 000000000..afa2d240b--- /dev/null+++ b/docs/advanced/custom-providers.md@@ -0,0 +1,494 @@+# Creating Custom Providers++This guide provides a comprehensive walkthrough of creating custom providers for the Composio SDK, enabling integration with different AI frameworks and platforms.++## Provider Architecture++The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:++1. **Tool Format Transformation**: Converting Composio tools into formats compatible with specific AI platforms+2. **Tool Execution**: Managing the flow of tool execution and results+3. **Platform-Specific Integration**: Providing helper methods for seamless integration++## Types of Providers++There are two types of providers:++1. **Non-Agentic Providers**: Transform tools for platforms that don't have their own agency (e.g., OpenAI)+2. **Agentic Providers**: Transform tools for platforms that have their own agency (e.g., LangChain, AutoGPT)++## Provider Class Hierarchy++```+BaseProvider (Abstract)+├── BaseNonAgenticProvider (Abstract)+│ └── OpenAIProvider (Concrete)+│ └── [Your Custom Non-Agentic Provider] (Concrete)+└── BaseAgenticProvider (Abstract)+ └── [Your Custom Agentic Provider] (Concrete)+```++## Creating a Non-Agentic Provider++Non-agentic providers implement the `BaseNonAgenticProvider` abstract class:++```typescript+import { BaseNonAgenticProvider, Tool } from '@composio/sdk';++// Define your tool format+interface MyAITool {+ name: string;+ description: string;+ parameters: {+ type: string;+ properties: Record<string, unknown>;+ required?: string[];+ };+}++// Define your tool collection format+type MyAIToolCollection = MyAITool[];++// Create your provider+export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyAITool> {+ // Required: Unique provider name for telemetry+ readonly name = 'my-ai-platform';++ // Required: Method to transform a single tool+ override wrapTool(tool: Tool): MyAITool {+ return {+ name: tool.slug,+ description: tool.description || '',+ parameters: {+ type: 'object',+ properties: tool.inputParameters?.properties || {},+ required: tool.inputParameters?.required || [],+ },+ };+ }++ // Required: Method to transform a collection of tools+ override wrapTools(tools: Tool[]): MyAIToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Optional: Custom helper methods for your AI platform+ async executeMyAIToolCall(+ userId: string,+ toolCall: {+ name: string;+ arguments: Record<string, unknown>;+ }+ ): Promise<string> {+ // Use the built-in executeTool method+ const result = await this.executeTool(+ toolCall.name,+ {+ userId,+ arguments: toolCall.arguments,+ }+ );++ return JSON.stringify(result.data);+ }+}+```++## Creating an Agentic Provider++Agentic providers implement the `BaseAgenticProvider` abstract class:++```typescript+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';++// Define your tool format+interface AgentTool {+ name: string;+ description: string;+ execute: (args: Record<string, unknown>) => Promise<unknown>;+ schema: Record<string, unknown>;+}++// Define your tool collection format+interface AgentToolkit {+ tools: AgentTool[];+ createAgent: (config: Record<string, unknown>) => unknown;+}++// Create your provider+export class MyAgentProvider extends BaseAgenticProvider<AgentToolkit, AgentTool> {+ // Required: Unique provider name for telemetry+ readonly name = 'my-agent-platform';++ // Required: Method to transform a single tool with execute function+ override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): AgentTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ schema: tool.inputParameters || {},+ execute: async (args: Record<string, unknown>) => {+ const result = await executeToolFn(tool.slug, args);+ if (!result.successful) {+ throw new Error(result.error || 'Tool execution failed');+ }+ return result.data;+ }+ };+ }++ // Required: Method to transform a collection of tools with execute function+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): AgentToolkit {+ const agentTools = tools.map(tool => this.wrapTool(tool, executeToolFn));++ return {+ tools: agentTools,+ createAgent: (config) => {+ // Create an agent using the tools+ return {+ run: async (prompt: string) => {+ // Implementation depends on your agent framework+ console.log(`Running agent with prompt: ${prompt}`);+ // The agent would use the tools.execute method to run tools+ }+ };+ }+ };+ }++ // Optional: Custom helper methods for your agent platform+ async runAgent(agentToolkit: AgentToolkit, prompt: string): Promise<unknown> {+ const agent = agentToolkit.createAgent({});+ return await agent.run(prompt);+ }+}+```++## Using Your Custom Provider++After creating your provider, use it with the Composio SDK:++```typescript+import { Composio } from '@composio/sdk';+import { MyAIProvider } from './my-ai-provider';++// Create your provider instance+const myProvider = new MyAIProvider();++// Initialize Composio with your provider+const composio = new Composio({+ apiKey: 'your-composio-api-key',+ provider: myProvider,+});++// Get tools - they will be transformed by your provider+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Use the tools with your AI platform+console.log(tools); // These will be in your custom format+```++## Provider State and Context++Your provider can maintain state and context:++```typescript+export class StatefulProvider extends BaseNonAgenticProvider<ToolCollection, Tool> {+ readonly name = 'stateful-provider';++ // Provider state+ private requestCount = 0;+ private toolCache = new Map<string, any>();+ private config: ProviderConfig;++ constructor(config: ProviderConfig) {+ super();+ this.config = config;+ }++ override wrapTool(tool: Tool): ProviderTool {+ this.requestCount++;++ // Use the provider state/config+ const enhancedTool = {+ // Transform the tool+ name: this.config.useUpperCase ? tool.slug.toUpperCase() : tool.slug,+ description: tool.description,+ schema: tool.inputParameters,+ };++ // Cache the transformed tool+ this.toolCache.set(tool.slug, enhancedTool);++ return enhancedTool;+ }++ override wrapTools(tools: Tool[]): ProviderToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Custom methods that use provider state+ getRequestCount(): number {+ return this.requestCount;+ }++ getCachedTool(slug: string): ProviderTool | undefined {+ return this.toolCache.get(slug);+ }+}+```++## Advanced: Provider Composition++You can compose functionality by extending existing providers:++```typescript+import { OpenAIProvider } from '@composio/sdk';++// Extend the OpenAI provider with custom functionality+export class EnhancedOpenAIProvider extends OpenAIProvider {+ // Add properties+ private analytics = {+ toolCalls: 0,+ errors: 0,+ };++ // Override methods to add functionality+ override async executeToolCall(userId, tool, options, modifiers) {+ this.analytics.toolCalls++;++ try {+ // Call the parent implementation+ const result = await super.executeToolCall(userId, tool, options, modifiers);+ return result;+ } catch (error) {+ this.analytics.errors++;+ throw error;+ }+ }++ // Add new methods+ getAnalytics() {+ return this.analytics;+ }++ async executeWithRetry(userId, tool, options, modifiers, maxRetries = 3) {+ let attempts = 0;+ let lastError;++ while (attempts < maxRetries) {+ try {+ return await this.executeToolCall(userId, tool, options, modifiers);+ } catch (error) {+ lastError = error;+ attempts++;+ await new Promise(resolve => setTimeout(resolve, 1000 * attempts));+ }+ }++ throw lastError;+ }+}+```++## Example: Anthropic Claude Provider++Here's a more complete example for Anthropic's Claude:++```typescript+import { BaseNonAgenticProvider, Tool } from '@composio/sdk';+import Anthropic from '@anthropic-ai/sdk';++interface ClaudeTool {+ name: string;+ description: string;+ input_schema: {+ type: string;+ properties: Record<string, unknown>;+ required?: string[];+ };+}++type ClaudeToolCollection = ClaudeTool[];++export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection, ClaudeTool> {+ readonly name = 'claude';+ private client: Anthropic;++ constructor(apiKey: string) {+ super();+ this.client = new Anthropic({+ apiKey,+ });+ }++ override wrapTool(tool: Tool): ClaudeTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ input_schema: {+ type: 'object',+ properties: tool.inputParameters?.properties || {},+ required: tool.inputParameters?.required || [],+ },+ };+ }++ override wrapTools(tools: Tool[]): ClaudeToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Helper method to create a Claude message with tools+ async createMessage(prompt: string, tools: ClaudeToolCollection, userId: string) {+ const response = await this.client.messages.create({+ model: 'claude-3-opus-20240229',+ max_tokens: 1024,+ system: 'You are a helpful assistant with access to tools.',+ messages: [+ { role: 'user', content: prompt }+ ],+ tools,+ });++ // Process tool calls if any+ if (response.content.some(content =>+ content.type === 'tool_use' &&+ 'name' in content &&+ 'input' in content+ )) {+ const toolResponses = await Promise.all(+ response.content+ .filter(content => content.type === 'tool_use')+ .map(async (content: any) => {+ const result = await this.executeTool(+ content.name,+ {+ userId,+ arguments: content.input,+ }+ );++ return {+ type: 'tool_result',+ tool_use_id: content.id,+ content: JSON.stringify(result.data),+ };+ })+ );++ // Continue the conversation with tool results+ const followupResponse = await this.client.messages.create({+ model: 'claude-3-opus-20240229',+ max_tokens: 1024,+ system: 'You are a helpful assistant with access to tools.',+ messages: [+ { role: 'user', content: prompt },+ { role: 'assistant', content: response.content },+ { role: 'user', content: toolResponses }+ ],+ tools,+ });++ return followupResponse;+ }++ return response;+ }+}+```++## Example: LangChain Provider++Here's an example for LangChain:++```typescript+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';+import { DynamicTool } from 'langchain/tools';+import { ChatOpenAI } from 'langchain/chat_models/openai';+import { initializeAgentExecutorWithOptions } from 'langchain/agents';++interface LangChainTool extends DynamicTool {+ name: string;+ description: string;+ func: (input: Record<string, unknown>) => Promise<string>;+}++interface LangChainToolkit {+ tools: LangChainTool[];+ createExecutor: (options: { model: string }) => Promise<any>;+}++export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, LangChainTool> {+ readonly name = 'langchain';++ override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {+ return new DynamicTool({+ name: tool.slug,+ description: tool.description || '',+ func: async (input: string) => {+ try {+ // Parse input from string to object+ const args = typeof input === 'string' ? JSON.parse(input) : input;++ // Execute the tool+ const result = await executeToolFn(tool.slug, args);++ if (!result.successful) {+ throw new Error(result.error || 'Tool execution failed');+ }++ // Return the result+ return JSON.stringify(result.data);+ } catch (error) {+ return `Error: ${error.message}`;+ }+ }+ }) as LangChainTool;+ }++ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolkit {+ const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));++ return {+ tools: langchainTools,+ createExecutor: async ({ model }) => {+ const llm = new ChatOpenAI({+ modelName: model || 'gpt-4',+ temperature: 0,+ });++ return await initializeAgentExecutorWithOptions(+ langchainTools,+ llm,+ {+ agentType: 'chat-zero-shot-react-description',+ verbose: true,+ }+ );+ }+ };+ }++ // Helper method to run the agent+ async runAgent(+ toolkit: LangChainToolkit,+ prompt: string,+ model = 'gpt-4'+ ): Promise<string> {+ const executor = await toolkit.createExecutor({ model });+ const result = await executor.call({ input: prompt });+ return result.output;+ }+}+```++## Best Practices++1. **Keep providers focused**: Each provider should integrate with one specific platform+2. **Handle errors gracefully**: Catch and transform errors from tool execution+3. **Follow platform conventions**: Adopt naming and structural conventions of the target platform+4. **Optimize for performance**: Cache transformed tools when possible+5. **Add helper methods**: Provide convenient methods for common platform-specific operations+6. **Provide clear documentation**: Document your provider's unique features and usage+7. **Use telemetry**: Set a meaningful provider name for telemetry insights\ No newline at end of filediff --git a/docs/advanced/error-handling.md b/docs/advanced/error-handling.mdnew file mode 100644index 000000000..2401dce5d--- /dev/null+++ b/docs/advanced/error-handling.md@@ -0,0 +1,242 @@+# Error Handling in Composio SDK++Proper error handling is essential for building robust applications with the Composio SDK. This guide explains the error classes provided by the SDK and how to handle errors effectively.++## Error Hierarchy++Composio SDK provides a structured error hierarchy:++- `ComposioError`: The base error class for all Composio errors+ - `AuthConfigErrors`: Errors related to authentication configurations+ - `ConnectedAccountsError`: Errors related to connected accounts+ - `ConnectionRequestError`: Errors related to connection requests+ - `ToolErrors`: Errors related to tools and tool execution+ - `ToolkitErrors`: Errors related to toolkits+ - `ValidationError`: Errors related to input validation++## Common Error Types++### Validation Errors++Validation errors occur when the input to a method doesn't match the expected schema:++```typescript+try {+ await composio.tools.get('default', {+ invalidParam: 'value', // This will cause a validation error+ });+} catch (error) {+ if (error instanceof ValidationError) {+ console.error('Validation error:', error.message);+ console.error('Validation details:', error.validationError);+ }+}+```++### Tool Execution Errors++Errors that occur during tool execution:++```typescript+try {+ const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ // Missing 'repo' parameter will cause an error+ },+ });+} catch (error) {+ if (error instanceof ComposioToolExecutionError) {+ console.error('Tool execution error:', error.message);+ console.error('Tool:', error.context.toolSlug);+ console.error('Execution params:', error.context.body);+ }+}+```++### Not Found Errors++Errors that occur when a resource is not found:++```typescript+try {+ await composio.tools.get('default', 'NON_EXISTENT_TOOL');+} catch (error) {+ if (error instanceof ComposioToolNotFoundError) {+ console.error('Tool not found:', error.message);+ }+}+```++## Handling Errors in Tool Execution++When executing tools, you should handle both SDK errors and execution result errors:++```typescript+try {+ const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ });++ // Check if the execution was successful+ if (result.successful) {+ console.log('Repository details:', result.data);+ } else {+ // Handle unsuccessful execution+ console.error('Execution failed:', result.error);+ }+} catch (error) {+ // Handle SDK errors+ console.error('SDK error:', error.message);+}+```++## Error Handling with Connected Accounts++Handle errors during the connection flow:++```typescript+try {+ // Step 1: Authorize the toolkit+ const connectionRequest = await composio.toolkits.authorize('user123', 'github');++ // Step 2: Wait for the connection to be established+ try {+ const connectedAccount = await composio.connectedAccounts.waitForConnection(+ connectionRequest.id,+ 60000 // 60 second timeout+ );+ console.log('Connected account:', connectedAccount);+ } catch (timeoutError) {+ if (timeoutError instanceof ConnectionRequestTimeoutError) {+ console.error('Connection timed out. Please try again.');+ } else if (timeoutError instanceof ConnectionRequestFailedError) {+ console.error('Connection failed:', timeoutError.message);+ }+ }+} catch (error) {+ if (error instanceof ComposioAuthConfigNotFoundError) {+ console.error('Auth config not found:', error.message);+ } else {+ console.error('Error initiating connection:', error.message);+ }+}+```++## Global Error Handler++For larger applications, consider implementing a global error handler:++```typescript+// Define a global error handler function+function handleComposioError(error: unknown): void {+ if (error instanceof ValidationError) {+ console.error('Validation error:', error.message);+ } else if (error instanceof ComposioToolNotFoundError) {+ console.error('Tool not found:', error.message);+ } else if (error instanceof ComposioToolExecutionError) {+ console.error('Tool execution error:', error.message);+ } else if (error instanceof ComposioAuthConfigNotFoundError) {+ console.error('Auth config not found:', error.message);+ } else if (error instanceof ConnectionRequestFailedError) {+ console.error('Connection failed:', error.message);+ } else if (error instanceof ConnectionRequestTimeoutError) {+ console.error('Connection timed out:', error.message);+ } else if (error instanceof ComposioError) {+ console.error('Composio error:', error.message);+ } else {+ console.error('Unexpected error:', error);+ }+}++// Use the global error handler+try {+ const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ });++ if (!result.successful) {+ console.error('Execution failed:', result.error);+ }+} catch (error) {+ handleComposioError(error);+}+```++## Error Handling in Custom Tools++When creating custom tools, implement proper error handling in your handler function:++```typescript+const customTool = await composio.tools.createCustomTool({+ name: 'My Custom Tool',+ description: 'A custom tool with error handling',+ slug: 'MY_CUSTOM_TOOL',+ inputParameters: {+ type: 'object',+ properties: {+ param1: { type: 'string' }+ },+ required: ['param1']+ },+ outputParameters: {+ type: 'object',+ properties: {+ result: { type: 'string' }+ }+ },+ handler: async (params, context) => {+ try {+ // Validate input+ const { param1 } = params.arguments;+ if (!param1 || param1.trim() === '') {+ return {+ data: {},+ successful: false,+ error: 'param1 cannot be empty'+ };+ }++ // Process the request+ // This could throw various errors+ const result = await someExternalService(param1);++ return {+ data: { result },+ successful: true,+ error: null+ };+ } catch (error) {+ // Log the error for debugging+ console.error('Error in custom tool:', error);++ // Return a user-friendly error message+ return {+ data: {},+ successful: false,+ error: error.message || 'An unexpected error occurred'+ };+ }+ }+});+```++## Best Practices++1. **Always use try/catch blocks** when calling SDK methods+2. **Check result.successful** after tool execution+3. **Provide specific error handling** for different error types+4. **Log detailed error information** for debugging+5. **Present user-friendly error messages** in your application+6. **Set appropriate timeouts** for operations like waitForConnection+7. **Validate inputs** before calling SDK methods+8. **Implement retry logic** for transient errors\ No newline at end of filediff --git a/docs/advanced/middleware.md b/docs/advanced/middleware.mdnew file mode 100644index 000000000..ec4a7ea58--- /dev/null+++ b/docs/advanced/middleware.md@@ -0,0 +1,402 @@+# Middleware and Modifiers++Composio SDK provides powerful middleware capabilities through modifiers that allow you to customize and extend the behavior of tools. This guide explains how to use modifiers to transform tool schemas, modify inputs before execution, and transform outputs after execution.++## What are Modifiers?++Modifiers are functions that intercept and modify the normal flow of tool operations. Composio supports three types of modifiers:++1. **Schema Modifiers**: Transform a tool's schema before it's wrapped for the provider+2. **Before Execution Modifiers**: Modify inputs before a tool is executed+3. **After Execution Modifiers**: Transform outputs after a tool has executed++### Schema Modifiers++Schema modifiers allow you to transform a tool's schema before it's wrapped for the provider. This is useful for customizing tool descriptions, parameter definitions, or adding metadata.++```typescript+// Modify tool schema when getting tools+const tools = await composio.tools.get(+ 'default',+ {+ toolkits: ['github'],+ },+ {+ modifyToolSchema: (toolSlug, toolkitSlug, tool) => {+ // Add a prefix to all tool descriptions+ if (tool.description) {+ tool.description = `[Enhanced] ${tool.description}`;+ }++ // Modify parameters for a specific tool+ if (toolSlug === 'GITHUB_GET_REPO') {+ if (tool.inputParameters?.properties?.owner) {+ // Add more detailed description+ tool.inputParameters.properties.owner.description =+ 'GitHub organization or user name (e.g., "composio")';+ }+ }++ return tool;+ },+ }+);+```++### Before Execution Modifiers++Before execution modifiers allow you to modify the input parameters before a tool is executed. This is useful for parameter validation, transformation, or adding default values.++```typescript+// Modify parameters before execution+const result = await composio.tools.execute(+ 'GITHUB_GET_REPO',+ {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ },+ {+ beforeToolExecute: (toolSlug, toolkitSlug, params) => {+ // Convert owner names to lowercase+ if (params.arguments.owner) {+ params.arguments.owner = params.arguments.owner.toLowerCase();+ }++ // Add a default branch parameter+ if (toolSlug === 'GITHUB_GET_REPO' && !params.arguments.branch) {+ params.arguments.branch = 'main';+ }++ // Add tracing for debugging+ console.log(`Executing ${toolSlug} from ${toolkitSlug} toolkit`);++ return params;+ },+ }+);+```++### After Execution Modifiers++After execution modifiers allow you to transform the output after a tool has executed. This is useful for data formatting, filtering, or enrichment.++```typescript+// Modify results after execution+const result = await composio.tools.execute(+ 'GITHUB_GET_REPO',+ {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ },+ {+ afterToolExecute: (toolSlug, toolkitSlug, result) => {+ // Only when execution was successful+ if (result.successful) {+ // Filter out sensitive data+ if (result.data.token) {+ delete result.data.token;+ }++ // Add a timestamp+ result.data.fetchedAt = new Date().toISOString();++ // Transform data formats+ if (result.data.created_at) {+ result.data.createdAt = new Date(result.data.created_at).toLocaleString();+ delete result.data.created_at;+ }+ }++ return result;+ },+ }+);+```++### Using Multiple Modifiers++You can use all three types of modifiers together:++```typescript+const tools = await composio.tools.get(+ 'default',+ {+ toolkits: ['github'],+ },+ {+ // Schema modifier+ modifyToolSchema: (toolSlug, toolkitSlug, tool) => {+ // Enhance tool schema+ return tool;+ },++ // Before execution modifier+ beforeToolExecute: (toolSlug, toolkitSlug, params) => {+ // Modify execution parameters+ return params;+ },++ // After execution modifier+ afterToolExecute: (toolSlug, toolkitSlug, result) => {+ // Transform execution results+ return result;+ },+ }+);+```++## Creating Reusable Modifiers++For better code organization, you can create reusable modifier functions:++```typescript+// Define reusable modifiers+const addTimestamps = (toolSlug, toolkitSlug, result) => {+ if (result.successful) {+ result.data.executedAt = new Date().toISOString();+ }+ return result;+};++const logExecutions = (toolSlug, toolkitSlug, params) => {+ console.log(`Executing ${toolSlug} from ${toolkitSlug} at ${new Date().toISOString()}`);+ return params;+};++const sanitizeInputs = (toolSlug, toolkitSlug, params) => {+ // Sanitize input parameters to prevent injection attacks+ if (params.arguments) {+ Object.keys(params.arguments).forEach(key => {+ if (typeof params.arguments[key] === 'string') {+ params.arguments[key] = sanitizeString(params.arguments[key]);+ }+ });+ }+ return params;+};++// Use the reusable modifiers+const result = await composio.tools.execute(+ 'GITHUB_GET_REPO',+ {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ },+ {+ beforeToolExecute: sanitizeInputs,+ afterToolExecute: addTimestamps,+ }+);+```++## Practical Use Cases++### Caching Tool Results++```typescript+// Simple in-memory cache+const cache = new Map();++const cacheModifier = (toolSlug, toolkitSlug, params) => {+ // Create a cache key based on tool slug and arguments+ const cacheKey = `${toolSlug}-${JSON.stringify(params.arguments)}`;++ // Add cache key to params for the after modifier to use+ params.__cacheKey = cacheKey;++ // Check if we have a cached result+ if (cache.has(cacheKey)) {+ const cachedResult = cache.get(cacheKey);+ if (Date.now() - cachedResult.timestamp < 60000) {+ // 1 minute cache+ // Throw a special error to short-circuit execution+ throw { __cached: true, result: cachedResult.result };+ }+ }++ return params;+};++const cacheAfterModifier = (toolSlug, toolkitSlug, result) => {+ if (result.successful && result.__cacheKey) {+ // Store in cache+ cache.set(result.__cacheKey, {+ result,+ timestamp: Date.now(),+ });++ // Remove the cache key from the result+ delete result.__cacheKey;+ }++ return result;+};++// Use with try/catch to handle the cache hit+try {+ const result = await composio.tools.execute(+ 'GITHUB_GET_REPO',+ {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ },+ {+ beforeToolExecute: cacheModifier,+ afterToolExecute: cacheAfterModifier,+ }+ );++ console.log('Fresh result:', result);+} catch (error) {+ if (error.__cached) {+ console.log('Cached result:', error.result);+ } else {+ throw error; // Re-throw if it's a real error+ }+}+```++### Adding Authentication Headers++```typescript+const authModifier = (toolSlug, toolkitSlug, params) => {+ // Add authentication parameters for specific toolkits+ if (toolkitSlug === 'custom-api') {+ if (!params.customAuthParams) {+ params.customAuthParams = {};+ }++ if (!params.customAuthParams.parameters) {+ params.customAuthParams.parameters = [];+ }++ // Add an API key to the headers+ params.customAuthParams.parameters.push({+ in: 'header',+ name: 'X-API-Key',+ value: process.env.CUSTOM_API_KEY,+ });+ }++ return params;+};++// Apply the auth modifier to all tools from a specific toolkit+const tools = await composio.tools.get(+ 'default',+ {+ toolkits: ['custom-api'],+ },+ {+ beforeToolExecute: authModifier,+ }+);+```++### Data Transformation Pipeline++```typescript+// Create a pipeline of modifiers+const pipeModifiers = (...modifiers) => {+ return (toolSlug, toolkitSlug, result) => {+ return modifiers.reduce((modifiedResult, modifier) => {+ return modifier(toolSlug, toolkitSlug, modifiedResult);+ }, result);+ };+};++// Individual transformation steps+const addMetadata = (toolSlug, toolkitSlug, result) => {+ if (result.successful) {+ result.data.metadata = { source: toolkitSlug, tool: toolSlug };+ }+ return result;+};++const formatDates = (toolSlug, toolkitSlug, result) => {+ if (result.successful) {+ // Convert all dates to a consistent format+ Object.keys(result.data).forEach(key => {+ if (key.includes('date') || key.includes('time') || key.endsWith('At')) {+ if (result.data[key]) {+ result.data[key] = new Date(result.data[key]).toLocaleString();+ }+ }+ });+ }+ return result;+};++const removeNulls = (toolSlug, toolkitSlug, result) => {+ if (result.successful) {+ // Remove null and undefined values+ Object.keys(result.data).forEach(key => {+ if (result.data[key] === null || result.data[key] === undefined) {+ delete result.data[key];+ }+ });+ }+ return result;+};++// Apply the pipeline+const result = await composio.tools.execute(+ 'GITHUB_GET_REPO',+ {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+ },+ {+ afterToolExecute: pipeModifiers(addMetadata, formatDates, removeNulls),+ }+);+```++## Type Definitions++```typescript+// Schema Modifier+type TransformToolSchemaModifier = (toolSlug: string, toolkitSlug: string, tool: Tool) => Tool;++// Before Execution Modifier+type BeforeToolExecuteModifier = (+ toolSlug: string,+ toolkitSlug: string,+ params: ToolExecuteParams+) => ToolExecuteParams;++// After Execution Modifier+type AfterToolExecuteModifier = (+ toolSlug: string,+ toolkitSlug: string,+ result: ToolExecuteResponse+) => ToolExecuteResponse;++// Modifiers Object+interface ExecuteToolModifiers {+ beforeToolExecute?: BeforeToolExecuteModifier;+ afterToolExecute?: AfterToolExecuteModifier;+}++// Provider Options (includes schema modifier)+interface ProviderOptions<TProvider> {+ modifyToolSchema?: TransformToolSchemaModifier;+ beforeToolExecute?: BeforeToolExecuteModifier;+ afterToolExecute?: AfterToolExecuteModifier;+}+```diff --git a/docs/advanced/telemetry.md b/docs/advanced/telemetry.mdnew file mode 100644index 000000000..5ec2bd875--- /dev/null+++ b/docs/advanced/telemetry.md@@ -0,0 +1,238 @@+# Telemetry in Composio SDK++Composio SDK includes a telemetry system to help improve the SDK and provide insights into usage patterns. This guide explains how telemetry works, what data is collected, how to customize it, and how to disable it if needed.++## Overview++The telemetry system in Composio SDK is:++- **Opt-out**: Enabled by default but can be disabled+- **Privacy-focused**: Does not collect personal or sensitive information+- **Transparent**: Clear about what data is collected+- **Configurable**: Custom transports can be provided++## Telemetry Data++The telemetry system collects the following types of data:++- **SDK Usage**: API calls, method invocations, error counts+- **Performance Metrics**: Response times, success/failure rates+- **Environment Information**: SDK version, provider used, runtime context++No personal or sensitive information such as:+- API keys+- Tool arguments+- Tool responses+- User IDs+- Connected account details++## Disabling Telemetry++You can disable telemetry when initializing the SDK:++```typescript+import { Composio } from '@composio/sdk';++const composio = new Composio({+ apiKey: 'your-api-key',+ allowTracking: false, // Disable telemetry+});+```++Or by setting an environment variable:++```bash+# In your .env file or environment+COMPOSIO_DISABLE_TELEMETRY=true+```++## Custom Telemetry Transport++For advanced use cases, you can provide a custom telemetry transport to process the telemetry data according to your needs:++```typescript+import { Composio, BaseTelemetryTransport, TelemetryEvent } from '@composio/sdk';++// Create a custom telemetry transport+class CustomTelemetryTransport extends BaseTelemetryTransport {+ async send(event: TelemetryEvent): Promise<void> {+ // Process the telemetry event+ console.log(`Telemetry event: ${event.name}`, event.properties);++ // You can send it to your own analytics system+ await yourAnalyticsSystem.track(event.name, event.properties);+ }++ async flush(): Promise<void> {+ // Clean up any pending events+ await yourAnalyticsSystem.flush();+ }+}++// Use the custom transport+const composio = new Composio({+ apiKey: 'your-api-key',+ telemetryTransport: new CustomTelemetryTransport(),+});+```++## Implementing a Custom Transport++To implement a custom telemetry transport, extend the `BaseTelemetryTransport` class:++```typescript+import { BaseTelemetryTransport, TelemetryEvent } from '@composio/sdk';++export class CustomTelemetryTransport extends BaseTelemetryTransport {+ // Optional constructor for configuration+ constructor(private config: { endpoint: string, batchSize: number }) {+ super();+ this.events = [];+ }++ // Local state for batching events+ private events: TelemetryEvent[];++ // Required: Implement the send method+ async send(event: TelemetryEvent): Promise<void> {+ // Add the event to the batch+ this.events.push(event);++ // If batch is full, flush it+ if (this.events.length >= this.config.batchSize) {+ await this.flush();+ }+ }++ // Required: Implement the flush method+ async flush(): Promise<void> {+ if (this.events.length === 0) {+ return;+ }++ try {+ // Send the batch to your endpoint+ await fetch(this.config.endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ events: this.events,+ timestamp: new Date().toISOString(),+ }),+ });++ // Clear the batch+ this.events = [];+ } catch (error) {+ console.error('Failed to send telemetry:', error);+ }+ }+}+```++## Telemetry Events++The telemetry system instruments various parts of the SDK and emits events for different operations:++### SDK Initialization++```+event: "sdk_initialized"+properties:+ framework: string // The provider name+ isAgentic: boolean // Whether the provider is agentic+ source: string // The runtime environment ("node" or "browser")+ version: string // The SDK version+ isBrowser: boolean // Whether the SDK is running in a browser+```++### Tool Operations++```+event: "tools_get"+properties:+ toolkit_slugs: string[] // The toolkit slugs used in the filter+ tool_count: number // The number of tools returned+ provider: string // The provider name++event: "tool_execute"+properties:+ tool_slug: string // The slug of the executed tool+ toolkit_slug: string // The toolkit slug of the executed tool+ success: boolean // Whether the execution was successful+ duration_ms: number // The execution duration in milliseconds+ provider: string // The provider name+```++### Connected Account Operations++```+event: "connected_account_initiate"+properties:+ toolkit_slug: string // The toolkit slug+ auth_config_id: string // The auth config ID++event: "connected_account_get"+properties:+ success: boolean // Whether the operation was successful++event: "connected_account_list"+properties:+ count: number // The number of connected accounts returned+ success: boolean // Whether the operation was successful+```++### Toolkit Operations++```+event: "toolkit_get"+properties:+ success: boolean // Whether the operation was successful+ toolkit_slug: string // The toolkit slug (if getting a specific toolkit)+ toolkits_count: number // The number of toolkits returned (if getting multiple)+```++## Telemetry Processor++The SDK includes a batch processor for telemetry events that:++1. Buffers events to reduce API calls+2. Sends events in batches+3. Handles retries and failures+4. Automatically flushes at regular intervals++This ensures that telemetry doesn't impact application performance.++## Environment Context++The telemetry system automatically includes environment context with each event:++```typescript+interface TelemetryMetadata {+ apiKey: string; // The Composio API key (first 8 chars only, for identification)+ baseUrl: string; // The Composio API base URL+ framework: string; // The provider name+ isAgentic: boolean; // Whether the provider is agentic+ source: string; // The runtime environment+ version: string; // The SDK version+ isBrowser: boolean; // Whether the SDK is running in a browser+ sessionId: string; // A random session ID (changes each init)+}+```++## Browser vs Node.js++The SDK automatically detects whether it's running in a browser or Node.js environment and uses the appropriate transport mechanism:++- In Node.js: Uses ProcessTransport with HTTP requests+- In Browser: Uses BrowserTransport with more browser-friendly approaches++## Best Practices++1. **Leave telemetry enabled** if possible to help improve the SDK+2. If you need to **disable telemetry** for compliance reasons, use the `allowTracking: false` option+3. If you want to **process telemetry locally**, implement a custom transport+4. **Never log sensitive data** in your custom transports+5. If you **implement a custom provider**, set a meaningful name to improve telemetry insights\ No newline at end of filediff --git a/docs/api/auth-configs.md b/docs/api/auth-configs.mdnew file mode 100644index 000000000..0c5bfacea--- /dev/null+++ b/docs/api/auth-configs.md@@ -0,0 +1,200 @@+# Auth Configs API++The `AuthConfigs` class provides methods to manage authentication configurations for toolkits. Auth configs define how authentication works for a particular toolkit, specifying the auth scheme (OAuth2, API Key, etc.) and other authentication-related details.++## Methods++### list(query?)++Lists all auth configs based on provided filter criteria.++```typescript+// List all auth configs+const allAuthConfigs = await composio.authConfigs.list();++// List auth configs for a specific toolkit+const githubAuthConfigs = await composio.authConfigs.list({+ toolkitSlug: 'github'+});+```++**Parameters:**++- `query` (AuthConfigListParams): Optional query parameters for filtering auth configs++**Returns:** Promise<AuthConfigListResponse> - A paginated list of auth configs++**Throws:** ValidationError if the query fails validation against the expected schema++### get(id)++Retrieves a specific auth config by its ID.++```typescript+// Get an auth config by ID+const authConfig = await composio.authConfigs.get('auth_config_123');+console.log(authConfig.name); // Name of the auth config+```++**Parameters:**++- `id` (string): The unique identifier of the auth config++**Returns:** Promise<AuthConfigRetrieveResponse> - The auth config details++**Throws:** ComposioAuthConfigNotFoundError if the auth config cannot be found++### create(toolkitSlug, data)++Creates a new auth config for a toolkit.++```typescript+// Create an auth config for GitHub+const authConfig = await composio.authConfigs.create('github', {+ type: 'use_composio_managed_auth',+ name: 'GitHub Auth Config',+});+```++**Parameters:**++- `toolkitSlug` (string): The slug of the toolkit to create an auth config for+- `data` (AuthConfigCreateParams): The parameters for creating the auth config++**Returns:** Promise<AuthConfigCreateResponse> - The created auth config++**Throws:**+- ValidationError if the parameters fail validation+- ComposioToolNotFoundError if the toolkit cannot be found++### update(id, data)++Updates an existing auth config.++```typescript+// Update an auth config+const updatedAuthConfig = await composio.authConfigs.update('auth_config_123', {+ name: 'Updated GitHub Auth Config',+ fields: {+ client_id: 'new_client_id',+ client_secret: 'new_client_secret',+ },+});+```++**Parameters:**++- `id` (string): The unique identifier of the auth config to update+- `data` (AuthConfigUpdateParams): The parameters for updating the auth config++**Returns:** Promise<AuthConfigUpdateResponse> - The updated auth config++**Throws:** ComposioAuthConfigNotFoundError if the auth config cannot be found++### delete(id)++Deletes an auth config.++```typescript+// Delete an auth config+await composio.authConfigs.delete('auth_config_123');+```++**Parameters:**++- `id` (string): The unique identifier of the auth config to delete++**Returns:** Promise<AuthConfigDeleteResponse> - The deletion response++**Throws:** Error if the auth config doesn't exist or cannot be deleted++## Types++### AuthConfigListParams++```typescript+interface AuthConfigListParams {+ cursor?: string; // Pagination cursor+ limit?: number; // Limit the number of results+ orderBy?: string; // Order by field+ toolkitSlug?: string; // Filter by toolkit slug+}+```++### AuthConfigListResponse++```typescript+interface AuthConfigListResponse {+ items: AuthConfigRetrieveResponse[]; // List of auth configs+ nextCursor: string | null; // Pagination cursor+ totalPages: number; // Total number of pages+}+```++### AuthConfigRetrieveResponse++```typescript+interface AuthConfigRetrieveResponse {+ id: string; // Auth config ID+ name: string; // Name of the auth config+ type: AuthConfigType; // Type of auth config+ toolkit: { // Associated toolkit+ id: string; // Toolkit ID+ slug: string; // Toolkit slug+ name: string; // Toolkit name+ };+ authScheme: AuthSchemeType; // Auth scheme (e.g., 'oauth2', 'api_key')+ isDisabled: boolean; // Whether the auth config is disabled+ fields: Record<string, unknown>; // Configuration fields+ meta: Record<string, unknown>; // Additional metadata+ createdAt: string; // Creation timestamp+ updatedAt: string; // Last update timestamp+}+```++### AuthConfigCreateParams++```typescript+interface AuthConfigCreateParams {+ type: AuthConfigType; // Type of auth config+ name: string; // Name of the auth config+ fields?: Record<string, unknown>; // Configuration fields+}+```++### AuthConfigUpdateParams++```typescript+interface AuthConfigUpdateParams {+ name?: string; // Name of the auth config+ fields?: Record<string, unknown>; // Configuration fields+}+```++### AuthConfigType++Auth config types are defined as an enum:++```typescript+enum AuthConfigTypes {+ USE_COMPOSIO_MANAGED_AUTH = 'use_composio_managed_auth',+ SERVICE_CONNECTION = 'service_connection',+ USER_CREDENTIALS = 'user_credentials',+ CUSTOM_AUTH = 'custom_auth',+ NO_AUTH = 'no_auth',+}+```++### AuthSchemeType++Auth scheme types are defined as an enum:++```typescript+enum AuthSchemeTypes {+ OAUTH2 = 'oauth2',+ API_KEY = 'api_key',+ BASIC_AUTH = 'basic_auth',+ CUSTOM = 'custom',+ NO_AUTH = 'no_auth',+}+```\ No newline at end of filediff --git a/docs/api/composio.md b/docs/api/composio.mdnew file mode 100644index 000000000..beb9d2e13--- /dev/null+++ b/docs/api/composio.md@@ -0,0 +1,93 @@+# Composio Class++The `Composio` class is the main entry point to the Composio SDK. It initializes the SDK and provides access to all the core functionality.++## Initialization++```typescript+import { Composio } from '@composio/sdk';++const composio = new Composio({+ apiKey: 'your-api-key',+ baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint+ allowTracking: true, // Optional: Enable/disable telemetry+ allowTracing: true, // Optional: Enable/disable tracing+ provider: new OpenAIProvider(), // Optional: Custom provider+ telemetryTransport: customTransport, // Optional: Custom telemetry transport+});+```++## Configuration Options++The `Composio` constructor accepts a configuration object with the following properties:++| Property | Type | Required | Default | Description |+|----------|------|----------|---------|-------------|+| `apiKey` | string | Yes | - | Your Composio API key |+| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |+| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |+| `allowTracing` | boolean | No | `true` | Whether to allow tracing |+| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |+| `telemetryTransport` | `BaseTelemetryTransport` | No | - | Custom transport for telemetry data |++## Properties++The `Composio` class provides access to the following core models:++| Property | Type | Description |+|----------|------|-------------|+| `tools` | `Tools` | Access to tools functionality |+| `toolkits` | `Toolkits` | Access to toolkits functionality |+| `triggers` | `Triggers` | Access to triggers functionality |+| `authConfigs` | `AuthConfigs` | Access to auth configs functionality |+| `connectedAccounts` | `ConnectedAccounts` | Access to connected accounts functionality |+| `provider` | `BaseComposioProvider` | The provider being used |++## Methods++### getClient()++Returns the internal Composio API client.++```typescript+const client = composio.getClient();+```++**Returns:** `ComposioClient`++**Throws:** Error if the client is not initialized++## Examples++### Basic Initialization++```typescript+import { Composio } from '@composio/sdk';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});+```++### Custom Provider++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';++const openaiProvider = new OpenAIProvider();+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: openaiProvider,+});+```++### Disable Tracking++```typescript+import { Composio } from '@composio/sdk';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ allowTracking: false,+});+```\ No newline at end of filediff --git a/docs/api/connected-accounts.md b/docs/api/connected-accounts.mdnew file mode 100644index 000000000..5011f2309--- /dev/null+++ b/docs/api/connected-accounts.md@@ -0,0 +1,258 @@+# Connected Accounts API++The `ConnectedAccounts` class provides methods to manage user connections to external services (toolkits). Connected accounts store authentication tokens and other information needed to access these services.++## Methods++### list(query?)++Lists all connected accounts based on provided filter criteria.++```typescript+// List all connected accounts+const allAccounts = await composio.connectedAccounts.list();++// List accounts for a specific user+const userAccounts = await composio.connectedAccounts.list({+ userIds: ['user123'],+});++// List accounts for a specific toolkit+const githubAccounts = await composio.connectedAccounts.list({+ toolkitSlugs: ['github'],+});+```++**Parameters:**++- `query` (ConnectedAccountListParams): Optional query parameters for filtering connected accounts++**Returns:** Promise<ConnectedAccountListResponse> - A paginated list of connected accounts++**Throws:** ValidationError if the query fails validation against the expected schema++### initiate(userId, authConfigId, options?)++Creates a new connected account and returns a connection request. Users can then wait for the connection to be established using the `waitForConnection` method.++```typescript+const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {+ data: {+ name: 'My GitHub Account',+ },+ callbackUrl: 'https://myapp.com/auth/callback',+});++// The redirectUrl is where the user should be redirected to authenticate+console.log(connectionRequest.redirectUrl);++// wait for the user to connected the acocunt+const connectedAccount = await connectionRequest.waitForConnection();+```++**Parameters:**++- `userId` (string): User ID of the connected account+- `authConfigId` (string): Auth config ID of the connected account+- `options` (CreateConnectedAccountOptions): Data for creating a new connected account++**Returns:** Promise<ConnectionRequest> - Connection request object++### waitForConnection(connectedAccountId, timeout?)++Waits for a connection request to complete and become active.++```typescript+// Wait for a connection to complete with default timeout+const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');++// Wait with a custom timeout of 2 minutes+const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);+```++**Parameters:**++- `connectedAccountId` (string): The ID of the connected account to wait for+- `timeout` (number): Maximum time to wait in milliseconds (default: 60 seconds)++**Returns:** Promise<ConnectedAccountRetrieveResponse> - The finalized connected account data++**Throws:**++- `ComposioConnectedAccountNotFoundError`: If the connected account cannot be found+- `ConnectionRequestFailedError`: If the connection enters a failed, expired, or deleted state+- `ConnectionRequestTimeoutError`: If the connection does not complete within the timeout period++### get(nanoid)++Retrieves a specific connected account by its ID.++```typescript+// Get a connected account by ID+const account = await composio.connectedAccounts.get('conn_abc123');+console.log(account.status); // e.g., 'ACTIVE'+console.log(account.toolkit.slug); // e.g., 'github'+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account++**Returns:** Promise<ConnectedAccountRetrieveResponse> - The connected account details++**Throws:** Error if the connected account cannot be found or an API error occurs++### delete(nanoid)++Deletes a connected account.++```typescript+// Delete a connected account+await composio.connectedAccounts.delete('conn_abc123');+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account to delete++**Returns:** Promise<ConnectedAccountDeleteResponse> - The deletion response++**Throws:** Error if the account doesn't exist or cannot be deleted++### refresh(nanoid)++Refreshes a connected account's authentication credentials.++```typescript+// Refresh a connected account's credentials+const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account to refresh++**Returns:** Promise<ConnectedAccountRefreshResponse> - The response containing the refreshed account details++**Throws:** Error if the account doesn't exist or credentials cannot be refreshed++### updateStatus(nanoid, params)++Updates the status of a connected account.++```typescript+// Update the status of a connected account+const updatedAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {+ enabled: true,+});+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account+- `params` (ConnectedAccountUpdateStatusParams): The parameters for updating the status++**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details++### enable(nanoid)++Enables a connected account.++```typescript+// Enable a connected account+const enabledAccount = await composio.connectedAccounts.enable('conn_abc123');+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account++**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details++### disable(nanoid)++Disables a connected account.++```typescript+// Disable a connected account+const disabledAccount = await composio.connectedAccounts.disable('conn_abc123');+```++**Parameters:**++- `nanoid` (string): The unique identifier of the connected account++**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details++## Types++### ConnectedAccountListParams++```typescript+interface ConnectedAccountListParams {+ authConfigIds?: string[]; // Filter by auth config IDs+ cursor?: string; // Pagination cursor+ labels?: string[]; // Filter by labels+ limit?: number; // Limit the number of results+ orderBy?: string; // Order by field+ statuses?: string[]; // Filter by statuses+ toolkitSlugs?: string[]; // Filter by toolkit slugs+ userIds?: string[]; // Filter by user IDs+}+```++### ConnectedAccountListResponse++```typescript+interface ConnectedAccountListResponse {+ items: ConnectedAccountRetrieveResponse[]; // List of connected accounts+ nextCursor: string | null; // Pagination cursor+ totalPages: number; // Total number of pages+}+```++### ConnectedAccountRetrieveResponse++```typescript+interface ConnectedAccountRetrieveResponse {+ id: string; // Connected account ID+ status: string; // Status (e.g., 'ACTIVE', 'PENDING')+ statusReason: string | null; // Reason for the status+ userId: string; // User ID+ toolkit: {+ // Associated toolkit+ id: string; // Toolkit ID+ slug: string; // Toolkit slug+ name: string; // Toolkit name+ };+ authConfig: {+ // Associated auth config+ id: string; // Auth config ID+ authScheme: string; // Auth scheme (e.g., 'oauth2')+ isComposioManaged: boolean; // Whether it's managed by Composio+ isDisabled: boolean; // Whether it's disabled+ };+ isDisabled: boolean; // Whether the connected account is disabled+ meta: Record<string, unknown>; // Additional metadata+ createdAt: string; // Creation timestamp+ updatedAt: string; // Last update timestamp+ testRequestEndpoint: string | null; // Endpoint for testing the connection+}+```++### CreateConnectedAccountOptions++```typescript+interface CreateConnectedAccountOptions {+ data?: Record<string, unknown>; // Additional data for the connection+ callbackUrl?: string; // URL to redirect after authentication+}+```++### ConnectedAccountUpdateStatusParams++```typescript+interface ConnectedAccountUpdateStatusParams {+ enabled: boolean; // Whether the account should be enabled+}+```diff --git a/docs/api/custom-tools.md b/docs/api/custom-tools.mdnew file mode 100644index 000000000..1e37077c5--- /dev/null+++ b/docs/api/custom-tools.md@@ -0,0 +1,279 @@+# Custom Tools API++Custom Tools allow you to extend Composio's functionality by creating your own tools with custom logic. These tools can be used alongside the built-in tools provided by Composio.++## Creating Custom Tools++You can create custom tools using the `createCustomTool` method of the `Tools` class:++```typescript+const customTool = await composio.tools.createCustomTool({+ name: 'My Custom Tool',+ description: 'A custom tool that does something specific',+ slug: 'MY_CUSTOM_TOOL',+ inputParameters: {+ type: 'object',+ properties: {+ param1: {+ type: 'string',+ description: 'First parameter',+ },+ param2: {+ type: 'number',+ description: 'Second parameter',+ }+ },+ required: ['param1']+ },+ outputParameters: {+ type: 'object',+ properties: {+ result: {+ type: 'string',+ description: 'The result of the operation'+ }+ }+ },+ handler: async (params, context) => {+ // Custom logic here+ const { param1, param2 } = params.arguments;++ // Return a successful response+ return {+ data: {+ result: `Processed ${param1} with value ${param2}`+ },+ successful: true,+ error: null+ };+ }+});+```++## Custom Tool Options++When creating a custom tool, you need to specify the following options:++| Property | Type | Required | Description |+|----------|------|----------|-------------|+| `name` | string | Yes | The name of the custom tool |+| `description` | string | Yes | A description of what the tool does |+| `slug` | string | Yes | A unique identifier for the tool (usually uppercase with underscores) |+| `inputParameters` | JSONSchema | Yes | The JSON Schema defining the input parameters |+| `outputParameters` | JSONSchema | No | The JSON Schema defining the output parameters |+| `handler` | function | Yes | The function that implements the tool's logic |++## Handler Function++The handler function is where you implement the custom tool's logic. It receives the following parameters:++1. `params`: The parameters passed to the tool, including:+ - `arguments`: The input arguments as defined in `inputParameters`+ - `userId`: The ID of the user executing the tool+ - `connectedAccountId`: (optional) The ID of the connected account to use+ - Additional properties as defined in `ToolExecuteParams`++2. `context`: Execution metadata, including:+ - `userId`: The ID of the user executing the tool+ - `connectedAccountId`: (optional) The ID of the connected account being used++The handler must return a `ToolExecuteResponse` object with the following structure:++```typescript+{+ data: Record<string, unknown>, // The output data matching the outputParameters schema+ error: string | null, // Error message (if any)+ successful: boolean, // Whether the execution was successful+ logId?: string, // Optional log ID for debugging+ sessionInfo?: unknown // Optional session information+}+```++## JSON Schema for Parameters++Both `inputParameters` and `outputParameters` should be defined using JSON Schema:++```typescript+const inputParametersSchema = {+ type: 'object',+ properties: {+ query: {+ type: 'string',+ description: 'The search query'+ },+ limit: {+ type: 'integer',+ description: 'Maximum number of results',+ default: 10+ }+ },+ required: ['query']+};++const outputParametersSchema = {+ type: 'object',+ properties: {+ results: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ title: { type: 'string' },+ url: { type: 'string' }+ }+ },+ description: 'Search results'+ },+ totalCount: {+ type: 'integer',+ description: 'Total number of results found'+ }+ }+};+```++## Error Handling in Custom Tools++Your handler function should handle errors gracefully:++```typescript+handler: async (params, context) => {+ try {+ // Custom logic here+ const { query, limit = 10 } = params.arguments;++ // Simulate an API call+ const results = await searchApi(query, limit);++ return {+ data: {+ results,+ totalCount: results.length+ },+ successful: true,+ error: null+ };+ } catch (error) {+ // Handle errors+ return {+ data: {},+ successful: false,+ error: error.message || 'An error occurred during tool execution'+ };+ }+}+```++## Using Connected Accounts in Custom Tools++You can use connected accounts in your custom tools to access authenticated services:++```typescript+handler: async (params, context) => {+ const { userId, connectedAccountId } = context;++ if (!connectedAccountId) {+ return {+ data: {},+ successful: false,+ error: 'No connected account provided'+ };+ }++ try {+ // Get the connected account details+ const connectedAccount = await composio.connectedAccounts.get(connectedAccountId);++ // Use the authentication tokens+ const accessToken = connectedAccount.meta.access_token;++ // Make authenticated API calls+ const apiResult = await callExternalApi(accessToken, params.arguments);++ return {+ data: apiResult,+ successful: true,+ error: null+ };+ } catch (error) {+ return {+ data: {},+ successful: false,+ error: error.message+ };+ }+}+```++## Accessing Custom Tools++Once created, custom tools can be accessed just like built-in tools:++```typescript+// Get the custom tool+const tool = await composio.tools.get('default', 'MY_CUSTOM_TOOL');++// Execute the custom tool+const result = await composio.tools.execute('MY_CUSTOM_TOOL', {+ userId: 'default',+ arguments: {+ param1: 'value1',+ param2: 42+ }+});++console.log(result.data); // { result: "Processed value1 with value 42" }+```++## Types++### CustomToolOptions++```typescript+interface CustomToolOptions {+ name: string;+ description: string;+ slug: string;+ inputParameters: JSONSchema;+ outputParameters?: JSONSchema;+ handler: (+ params: ToolExecuteParams,+ context: ExecuteMetadata+ ) => Promise<ToolExecuteResponse>;+}+```++### ExecuteMetadata++```typescript+interface ExecuteMetadata {+ userId: string;+ connectedAccountId?: string;+}+```++### ToolExecuteParams++```typescript+interface ToolExecuteParams {+ allowTracing?: boolean;+ connectedAccountId?: string;+ customAuthParams?: CustomAuthParams;+ arguments: Record<string, unknown>;+ userId: string;+ version?: string;+ text?: string;+}+```++### ToolExecuteResponse++```typescript+interface ToolExecuteResponse {+ data: Record<string, unknown>;+ error: string | null;+ successful: boolean;+ logId?: string;+ sessionInfo?: unknown;+}+```\ No newline at end of filediff --git a/docs/api/providers.md b/docs/api/providers.mdnew file mode 100644index 000000000..cc3bd6175--- /dev/null+++ b/docs/api/providers.md@@ -0,0 +1,293 @@+# Providers API++Providers are adapters that allow Composio tools to be used with different AI platforms. The SDK comes with a default OpenAI provider and supports creating custom providers.++## Base Provider Classes++Composio provides abstract base classes for creating providers:++### BaseComposioProvider++The base type for all providers:++```typescript+type BaseComposioProvider<TToolCollection, TTool> =+ | BaseNonAgenticProvider<TToolCollection, TTool>+ | BaseAgenticProvider<TToolCollection, TTool>;+```++### BaseNonAgenticProvider++Base class for non-agentic providers (those that don't have their own agency/autonomy):++```typescript+abstract class BaseNonAgenticProvider<TToolCollection, TTool> extends BaseProvider {+ readonly _isAgentic = false;++ // Wrap a tool in the provider specific format+ abstract wrapTool(tool: Tool): TTool;++ // Wrap a list of tools in the provider specific format+ abstract wrapTools(tools: Tool[]): TToolCollection;+}+```++### BaseAgenticProvider++Base class for agentic providers (those with their own agency/autonomy):++```typescript+abstract class BaseAgenticProvider<TToolCollection, TTool> extends BaseProvider {+ readonly _isAgentic = true;++ // Wrap a tool in the provider specific format+ abstract wrapTool(tool: Tool, executeTool: ExecuteToolFn): TTool;++ // Wrap a list of tools in the provider specific format+ abstract wrapTools(tools: Tool[], executeTool: ExecuteToolFn): TToolCollection;+}+```++## OpenAI Provider++The default provider for Composio SDK is the OpenAI Provider, which formats tools for use with OpenAI's API.++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';++const composio = new Composio({+ apiKey: 'your-api-key',+ provider: new OpenAIProvider(),+});+```++### Methods++#### wrapTool(tool)++Transforms a Composio tool into an OpenAI function tool format.++```typescript+const openaiTool = openaiProvider.wrapTool(composioTool);+```++**Parameters:**+- `tool` (Tool): The Composio tool to transform++**Returns:** OpenAI.ChatCompletionTool - The tool in OpenAI format++#### wrapTools(tools)++Transforms a list of Composio tools into an array of OpenAI function tools.++```typescript+const openaiTools = openaiProvider.wrapTools(composioTools);+```++**Parameters:**+- `tools` (Tool[]): The list of Composio tools to transform++**Returns:** Array<OpenAI.ChatCompletionTool> - The tools in OpenAI format++#### executeToolCall(userId, tool, options?, modifiers?)++Executes a tool call from an OpenAI assistant.++```typescript+const result = await openaiProvider.executeToolCall(+ 'user123',+ toolCall,+ { connectedAccountId: 'conn_abc123' },+ {+ beforeToolExecute: (toolSlug, toolkitSlug, params) => params,+ afterToolExecute: (toolSlug, toolkitSlug, result) => result+ }+);+```++**Parameters:**+- `userId` (string): The user ID+- `tool` (OpenAI.ChatCompletionMessageToolCall): The tool call from OpenAI+- `options` (ExecuteToolFnOptions): Optional parameters for tool execution+- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation++**Returns:** Promise<string> - The result of the tool call as JSON string++#### handleToolCall(userId, chatCompletion, options?, modifiers?)++Handles tool calls from an OpenAI chat completion.++```typescript+const outputs = await openaiProvider.handleToolCall(+ 'user123',+ chatCompletion+);+```++**Parameters:**+- `userId` (string): The user ID+- `chatCompletion` (OpenAI.ChatCompletion): The chat completion containing tool calls+- `options` (ExecuteToolFnOptions): Optional parameters for tool execution+- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation++**Returns:** Promise<string[]> - The results of the tool calls++#### handleAssistantMessage(userId, run, options?, modifiers?)++Handles tool calls from an OpenAI assistant run.++```typescript+const toolOutputs = await openaiProvider.handleAssistantMessage(+ 'user123',+ run+);+```++**Parameters:**+- `userId` (string): The user ID+- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls+- `options` (ExecuteToolFnOptions): Optional parameters for tool execution+- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation++**Returns:** Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]> - The tool outputs++#### waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, options?, modifiers?)++Waits for and handles tool calls from an OpenAI assistant stream.++```typescript+for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(+ 'user123',+ openaiClient,+ runStream,+ thread+)) {+ console.log(event);+}+```++**Parameters:**+- `userId` (string): The user ID+- `client` (OpenAI): The OpenAI client+- `runStream` (Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>): The run stream+- `thread` (OpenAI.Beta.Threads.Thread): The thread object+- `options` (ExecuteToolFnOptions): Optional parameters for tool execution+- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation++**Returns:** AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown> - Generator of stream events++#### waitAndHandleAssistantToolCalls(userId, client, run, thread, options?, modifiers?)++Waits for and handles tool calls from an OpenAI assistant.++```typescript+const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(+ 'user123',+ openaiClient,+ run,+ thread+);+```++**Parameters:**+- `userId` (string): The user ID+- `client` (OpenAI): The OpenAI client+- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls+- `thread` (OpenAI.Beta.Threads.Thread): The thread object+- `options` (ExecuteToolFnOptions): Optional parameters for tool execution+- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation++**Returns:** Promise<OpenAI.Beta.Threads.Run> - The final run object++## Creating Custom Providers++You can create custom providers by extending either `BaseNonAgenticProvider` or `BaseAgenticProvider`:++```typescript+import { BaseNonAgenticProvider, Tool } from '@composio/sdk';++type AnthropicTool = {+ name: string;+ description: string;+ parameters: Record<string, unknown>;+};++type AnthropicToolCollection = AnthropicTool[];++export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {+ readonly name = 'anthropic';++ override wrapTool(tool: Tool): AnthropicTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ parameters: tool.inputParameters || {},+ };+ }++ override wrapTools(tools: Tool[]): AnthropicToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Additional methods for handling Anthropic-specific functionality+}+```++## Types++### ExecuteToolFn++```typescript+type ExecuteToolFn = (+ toolSlug: string,+ input: Record<string, unknown>+) => Promise<ToolExecuteResponse>;+```++### ExecuteToolFnOptions++```typescript+interface ExecuteToolFnOptions {+ connectedAccountId?: string;+ customAuthParams?: CustomAuthParams;+}+```++### ExecuteToolModifiers++```typescript+interface ExecuteToolModifiers {+ beforeToolExecute?: BeforeToolExecuteModifier;+ afterToolExecute?: AfterToolExecuteModifier;+}+```++### TransformToolSchemaModifier++```typescript+type TransformToolSchemaModifier = (+ toolSlug: string,+ toolkitSlug: string,+ tool: Tool+) => Tool;+```++### BeforeToolExecuteModifier++```typescript+type BeforeToolExecuteModifier = (+ toolSlug: string,+ toolkitSlug: string,+ params: ToolExecuteParams+) => ToolExecuteParams;+```++### AfterToolExecuteModifier++```typescript+type AfterToolExecuteModifier = (+ toolSlug: string,+ toolkitSlug: string,+ result: ToolExecuteResponse+) => ToolExecuteResponse;+```\ No newline at end of filediff --git a/docs/api/toolkits.md b/docs/api/toolkits.mdnew file mode 100644index 000000000..b721e738e--- /dev/null+++ b/docs/api/toolkits.md@@ -0,0 +1,169 @@+# Toolkits API++The `Toolkits` class provides methods to list, retrieve, and manage toolkits. Toolkits are collections of related tools provided by a single service (like GitHub, Gmail, etc.).++## Methods++### get(slug)++Retrieves a specific toolkit by its slug identifier.++```typescript+// Get a specific toolkit+const githubToolkit = await composio.toolkits.get('github');+console.log(githubToolkit.name); // GitHub+console.log(githubToolkit.authConfigDetails); // Authentication configuration details+```++**Parameters:**++- `slug` (string): The unique slug identifier of the toolkit to retrieve++**Returns:** Promise<ToolkitRetrieveResponse> - The toolkit object with detailed information++**Throws:** ComposioToolNotFoundError if no toolkit with the given slug exists++### get(query)++Retrieves a list of toolkits based on the provided query parameters.++```typescript+// Get all toolkits+const allToolkits = await composio.toolkits.get({});++// Get toolkits by category+const devToolkits = await composio.toolkits.get({+ category: 'developer-tools'+});++// Get local toolkits+const localToolkits = await composio.toolkits.get({+ isLocal: true+});+```++**Parameters:**++- `query` (ToolkitListParams): The query parameters to filter toolkits++**Returns:** Promise<ToolKitListResponse> - A paginated list of toolkits matching the query criteria++### listCategories()++Retrieves all toolkit categories available in the Composio SDK.++```typescript+// Get all toolkit categories+const categories = await composio.toolkits.listCategories();+console.log(categories.items); // Array of category objects+```++**Returns:** Promise<ToolkitRetrieveCategoriesResponse> - The list of toolkit categories++### authorize(userId, toolkitSlug)++Authorizes a user to use a toolkit. This method will create an auth config if one doesn't exist and initiate a connection request.++```typescript+// Authorize a user to use GitHub+const connectionRequest = await composio.toolkits.authorize('user123', 'github');++// Use the connection request to complete the authorization process+console.log(connectionRequest.redirectUrl); // URL to redirect the user for authorization+```++**Parameters:**++- `userId` (string): The user ID of the user to authorize+- `toolkitSlug` (string): The slug of the toolkit to authorize++**Returns:** Promise<ConnectionRequest> - The connection request object++## Types++### ToolkitListParams++```typescript+interface ToolkitListParams {+ category?: string; // Filter by category+ isLocal?: boolean; // Filter for local toolkits+ managedBy?: string; // Filter by manager+ sortBy?: string; // Sort results by this field+}+```++### ToolKitListResponse++```typescript+interface ToolKitListResponse {+ items: ToolKitItem[]; // List of toolkits+ nextCursor?: string | null; // Pagination cursor+ totalPages: number; // Total number of pages+}+```++### ToolKitItem++```typescript+interface ToolKitItem {+ name: string; // Name of the toolkit+ slug: string; // Unique slug identifier+ meta: { // Metadata about the toolkit+ createdAt: string; // When the toolkit was created+ updatedAt: string; // When the toolkit was last updated+ toolsCount: number; // Number of tools in the toolkit+ triggersCount: number; // Number of triggers in the toolkit+ };+ isLocalToolkit: boolean; // Whether this is a local toolkit+ authSchemes: string[]; // Available authentication schemes+ composioManagedAuthSchemes: string[]; // Managed auth schemes+ noAuth: boolean; // Whether authentication is required+}+```++### ToolkitRetrieveResponse++```typescript+interface ToolkitRetrieveResponse {+ name: string; // Name of the toolkit+ slug: string; // Unique slug identifier+ meta: { // Metadata about the toolkit+ createdAt: string; // When the toolkit was created+ updatedAt: string; // When the toolkit was last updated+ toolsCount: number; // Number of tools in the toolkit+ triggersCount: number; // Number of triggers in the toolkit+ };+ isLocalToolkit: boolean; // Whether this is a local toolkit+ composioManagedAuthSchemes: string[]; // Managed auth schemes+ authConfigDetails: { // Authentication configuration details+ name: string; // Name of the auth configuration+ mode: string; // Auth mode (e.g., "OAUTH2")+ fields: { // Required fields+ authConfigCreation: Record<string, unknown>; // Fields for creating auth config+ connectedAccountInitiation: Record<string, unknown>; // Fields for initiating connection+ };+ proxy?: { // Proxy configuration (if any)+ baseUrl: string; // Base URL for proxied requests+ };+ }[];+}+```++### ToolkitRetrieveCategoriesResponse++```typescript+interface ToolkitRetrieveCategoriesResponse {+ items: ToolkitCategory[]; // List of categories+ nextCursor?: string | null; // Pagination cursor+ totalPages: number; // Total number of pages+}+```++### ToolkitCategory++```typescript+interface ToolkitCategory {+ id: string; // Category ID+ name: string; // Category name+}+```\ No newline at end of filediff --git a/docs/api/tools.md b/docs/api/tools.mdnew file mode 100644index 000000000..1946f419c--- /dev/null+++ b/docs/api/tools.md@@ -0,0 +1,218 @@+# Tools API++The `Tools` class provides methods to list, retrieve, and execute tools from various toolkits. It is one of the core components of the Composio SDK.++## Methods++### get(userId, filters, options?)++Retrieves tools based on the provided filters.++```typescript+// Get tools from a specific toolkit+const githubTools = await composio.tools.get('default', {+ toolkits: ['github'],+ limit: 10+});++// Get tools with search+const searchTools = await composio.tools.get('default', {+ search: 'user',+ important: true+});++// Get a specific tool by slug+const tool = await composio.tools.get('default', 'GITHUB_GET_REPO');++// Get a tool with schema modifications+const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {+ modifyToolSchema: (toolSlug, toolkitSlug, schema) => {+ // Customize the tool schema+ return {...schema, description: 'Custom description'};+ }+});+```++**Parameters:**++- `userId` (string): The user ID to get the tools for+- `filters` (ToolListParams | string): Either a slug string or filters object+- `options` (ProviderOptions): Optional provider options including modifiers++**Returns:** The wrapped tools collection, formatted according to the provider++### execute(slug, body, modifiers?)++Executes a given tool with the provided parameters.++```typescript+// Execute a Composio API tool+const result = await composio.tools.execute('HACKERNEWS_GET_USER', {+ userId: 'default',+ arguments: { userId: 'pg' }+});++// Execute with modifiers+const result = await composio.tools.execute('GITHUB_GET_ISSUES', {+ userId: 'default',+ arguments: { owner: 'composio', repo: 'sdk' }+}, {+ beforeToolExecute: (toolSlug, toolkitSlug, params) => {+ // Modify params before execution+ return params;+ },+ afterToolExecute: (toolSlug, toolkitSlug, result) => {+ // Transform result after execution+ return result;+ }+});+```++**Parameters:**++- `slug` (string): The slug/ID of the tool to be executed+- `body` (ToolExecuteParams): The parameters to be passed to the tool+- `modifiers` (ExecuteToolModifiers): Optional modifiers to transform the request or response++**Returns:** Promise<ToolExecuteResponse> - The response from the tool execution++**Throws:**+- `ComposioCustomToolsNotInitializedError`: If the CustomTools instance is not initialized+- `ComposioToolNotFoundError`: If the tool with the given slug is not found+- `ComposioToolExecutionError`: If there is an error during tool execution++### createCustomTool(body)++Creates a custom tool that can be used within the Composio SDK.++```typescript+const customTool = await composio.tools.createCustomTool({+ name: 'My Custom Tool',+ description: 'A custom tool that does something specific',+ slug: 'MY_CUSTOM_TOOL',+ inputParameters: {+ param1: {+ type: 'string',+ description: 'First parameter',+ required: true+ }+ },+ outputParameters: {+ result: {+ type: 'string',+ description: 'The result of the operation'+ }+ },+ handler: async (params, context) => {+ // Custom logic here+ return { data: { result: 'Success!' } };+ }+});+```++**Parameters:**++- `body` (CustomToolOptions): The configuration for the custom tool++**Returns:** Promise<Tool> - The created custom tool++### getRawComposioTools(userId, query?, modifier?)++Lists all tools available in the Composio SDK including custom tools.++```typescript+// Get all tools+const tools = await composio.tools.getRawComposioTools('default');++// Get tools with filters+const githubTools = await composio.tools.getRawComposioTools('default', {+ toolkits: ['github'],+ important: true+});++// Get tools with schema transformation+const tools = await composio.tools.getRawComposioTools('default', {},+ (toolSlug, toolkitSlug, tool) => {+ // Add custom properties to tool schema+ return {...tool, customProperty: 'value'};+ }+);+```++**Parameters:**++- `userId` (string): The user ID for whom to fetch the tools+- `query` (ToolListParams): Optional query parameters to filter the tools+- `modifier` (TransformToolSchemaModifier): Optional function to transform tool schemas++**Returns:** Promise<ToolList> - List of tools matching the query criteria++### getRawComposioToolBySlug(userId, slug, modifier?)++Retrieves a tool by its Slug.++```typescript+const tool = await composio.tools.getRawComposioToolBySlug('default', 'github');+```++**Parameters:**++- `userId` (string): The user ID for whom to fetch the tool+- `slug` (string): The ID of the tool to be retrieved+- `modifier` (TransformToolSchemaModifier): Optional function to transform tool schema++**Returns:** Promise<Tool> - The tool++## Types++### ToolListParams++```typescript+interface ToolListParams {+ tools?: string[]; // List of tool slugs to filter by+ cursor?: string; // Pagination cursor+ important?: string; // Filter for important tools+ limit?: string; // Limit the number of results+ search?: string; // Search term+ toolkits?: string[]; // List of toolkit slugs to filter by+}+```++### ToolExecuteParams++```typescript+interface ToolExecuteParams {+ allowTracing?: boolean; // Enable/disable tracing+ connectedAccountId?: string; // Connected account ID+ customAuthParams?: CustomAuthParams; // Custom auth parameters+ arguments?: Record<string, unknown>; // Tool arguments+ userId: string; // User ID+ version?: string; // Tool version+ text?: string; // Text input+}+```++### ToolExecuteResponse++```typescript+interface ToolExecuteResponse {+ data: Record<string, unknown>; // Tool execution data+ error: string | null; // Error message (if any)+ successful: boolean; // Whether the execution was successful+ logId?: string; // Log ID for debugging+ sessionInfo?: unknown; // Session information+}+```++### CustomToolOptions++```typescript+interface CustomToolOptions {+ name: string; // Name of the custom tool+ description: string; // Description of the custom tool+ slug: string; // Unique slug for the custom tool+ inputParameters: Record<string, unknown>; // Input parameters schema+ outputParameters?: Record<string, unknown>; // Output parameters schema+ handler: (params: ToolExecuteParams, context: ExecuteMetadata) => Promise<ToolExecuteResponse>; // Handler function+}+```\ No newline at end of filediff --git a/docs/core-concepts.md b/docs/core-concepts.mdnew file mode 100644index 000000000..fa3147ee7--- /dev/null+++ b/docs/core-concepts.md@@ -0,0 +1,122 @@+# Core Concepts++Composio SDK is built around a set of key concepts that work together to provide a seamless integration experience for third-party services and tools.++## Tools++Tools are the fundamental units of functionality in Composio. Each tool represents a specific action that can be performed, such as "Get GitHub Repository" or "Send Email". Tools have:++- **Slug**: A unique identifier (e.g., `GITHUB_GET_REPO`)+- **Name**: A human-readable name (e.g., "Get GitHub Repository")+- **Description**: A description of what the tool does+- **Input Parameters**: The arguments required to execute the tool+- **Output Parameters**: The data returned by the tool++Tools are organized into toolkits and can be executed through the Composio SDK.++```typescript+// Example: Execute a GitHub tool+const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+});+```++## Toolkits++Toolkits are collections of related tools grouped by service or functionality. For example, the "GitHub" toolkit includes tools for interacting with repositories, issues, pull requests, and more.++Toolkits typically require authentication to be accessed, which is managed through connected accounts.++```typescript+// Example: Get all tools from the GitHub toolkit+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});+```++## Connected Accounts++Connected Accounts represent a user's connection to an external service (toolkit). They store authentication tokens and other information needed to access the service.++The SDK provides methods to create, manage, and use connected accounts:++```typescript+// Example: Initiate a connection to GitHub+const connectionRequest = await composio.toolkits.authorize('user123', 'github');++// Example: Wait for the connection to be established+const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);+```++## Auth Configs++Auth Configs define how authentication works for a particular toolkit. They specify the auth scheme (OAuth2, API Key, etc.) and other authentication-related details.++Auth Configs are usually created automatically when authorizing a toolkit but can also be created manually.++```typescript+// Example: Create an auth config for GitHub+const authConfig = await composio.authConfigs.create('github', {+ type: 'use_composio_managed_auth',+ name: 'GitHub Auth Config',+});+```++## Providers++Providers are adapters that allow tools to be used with different AI platforms or frameworks. The default provider is OpenAIProvider, which formats tools for use with OpenAI's API.++Providers handle the transformation of tools into the format required by the AI platform and manage the execution flow.++```typescript+// Example: Initialize Composio with OpenAI provider+const composio = new Composio({+ apiKey: 'your-api-key',+ provider: new OpenAIProvider(),+});+```++## Custom Tools++Custom Tools allow you to extend Composio's functionality by creating your own tools. You define the input and output parameters and provide a handler function that implements the tool's behavior.++```typescript+// Example: Create a custom tool+const customTool = await composio.tools.createCustomTool({+ name: 'My Custom Tool',+ description: 'A custom tool that does something specific',+ slug: 'MY_CUSTOM_TOOL',+ inputParameters: {+ param1: {+ type: 'string',+ description: 'First parameter',+ required: true+ }+ },+ outputParameters: {+ result: {+ type: 'string',+ description: 'The result of the operation'+ }+ },+ handler: async (params, context) => {+ // Custom logic here+ return { data: { result: 'Success!' } };+ }+});+```++## Triggers++Triggers allow your application to respond to events from external services. They define when and how your application should take action based on external events.++```typescript+// Example: Get available triggers+const triggers = await composio.triggers.get({+ toolkits: ['github'],+});+```\ No newline at end of filediff --git a/docs/getting-started.md b/docs/getting-started.mdnew file mode 100644index 000000000..716dc142f--- /dev/null+++ b/docs/getting-started.md@@ -0,0 +1,272 @@+# Getting Started with Composio SDK++This guide will help you get started with the Composio SDK. You'll learn how to install it, initialize it, and use it to execute tools, manage connected accounts, and integrate with AI providers.++## Installation++Install the Composio SDK using npm, yarn, or pnpm:++```bash+# Using npm+npm install @composio/sdk++# Using yarn+yarn add @composio/sdk++# Using pnpm+pnpm add @composio/sdk+```++## Initialization++To use the SDK, you need to initialize it with your API key:++```typescript+import { Composio } from '@composio/sdk';++// Initialize the SDK+const composio = new Composio({+ apiKey: 'your-api-key',+});+```++You can also customize the initialization with additional options:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';++// Initialize with custom provider and options+const composio = new Composio({+ apiKey: 'your-api-key',+ baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint+ allowTracking: true, // Optional: Enable/disable telemetry+ provider: new OpenAIProvider(), // Optional: Custom provider+});+```++## Basic Usage++### Listing Available Toolkits++Toolkits are collections of related tools (like GitHub, Gmail, etc.). You can list all available toolkits:++```typescript+// Get all toolkits+const allToolkits = await composio.toolkits.get({});+console.log(allToolkits.items);++// Get toolkits by category+const devToolkits = await composio.toolkits.get({+ category: 'developer-tools'+});+```++### Getting Tools from a Toolkit++You can get tools from a specific toolkit:++```typescript+// Get all tools from the GitHub toolkit+const githubTools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Get a specific tool by slug+const getRepoTool = await composio.tools.get('default', 'GITHUB_GET_REPO');+```++### Executing a Tool++To execute a tool, you need to provide the tool's slug and the parameters:++```typescript+// Execute a GitHub tool+const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+});++// Check if the execution was successful+if (result.successful) {+ console.log('Repository details:', result.data);+} else {+ console.error('Error:', result.error);+}+```++## Working with Connected Accounts++Many tools require authentication with external services. Composio manages this through connected accounts.++### Setting Up a Connection++To create a connected account, you need to:++1. Authorize the toolkit+2. Wait for the user to complete the authentication flow++```typescript+// Step 1: Authorize the toolkit+const connectionRequest = await composio.toolkits.authorize('user123', 'github');++// This gives you a redirect URL+console.log('Redirect the user to:', connectionRequest.redirectUrl);++// Step 2: Wait for the connection to be established+// This should be called after the user completes the auth flow+const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);+console.log('Connected account:', connectedAccount);+```++### Using a Connected Account with Tools++Once you have a connected account, you can use it when executing tools:++```typescript+// Execute a tool with a connected account+const result = await composio.tools.execute('GITHUB_GET_REPOS', {+ userId: 'user123',+ connectedAccountId: connectedAccount.id,+ arguments: {},+});+```++## Integration with OpenAI++Composio integrates seamlessly with OpenAI. Here's an example of using Composio tools with OpenAI:++```typescript+import { Composio } from '@composio/sdk';+import OpenAI from 'openai';++// Initialize Composio and OpenAI+const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++const openai = new OpenAI({+ apiKey: 'your-openai-api-key',+});++// Get tools from the GitHub toolkit+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Create a chat completion with OpenAI using the tools+const completion = await openai.chat.completions.create({+ model: 'gpt-4-turbo',+ messages: [+ { role: 'system', content: 'You are a helpful assistant with access to GitHub tools.' },+ { role: 'user', content: 'List the repositories in the Composio organization' }+ ],+ tools, // Pass the tools to OpenAI+});++// If the assistant wants to use a tool+if (completion.choices[0].message.tool_calls) {+ // Execute each tool call+ for (const toolCall of completion.choices[0].message.tool_calls) {+ // Parse the arguments+ const args = JSON.parse(toolCall.function.arguments);++ // Execute the tool+ const result = await composio.tools.execute(toolCall.function.name, {+ userId: 'default',+ arguments: args,+ });++ // Use the result in your application+ console.log(`Tool ${toolCall.function.name} result:`, result.data);+ }+}+```++For a more complete integration, check out the [OpenAI Provider example](../examples/openai).++## Creating Custom Tools++You can extend Composio by creating your own custom tools:++```typescript+// Create a custom tool+const customTool = await composio.tools.createCustomTool({+ name: 'Weather Forecast',+ description: 'Get the weather forecast for a location',+ slug: 'WEATHER_FORECAST',+ inputParameters: {+ type: 'object',+ properties: {+ location: {+ type: 'string',+ description: 'The location to get the forecast for'+ },+ days: {+ type: 'integer',+ description: 'Number of days for the forecast',+ default: 3+ }+ },+ required: ['location']+ },+ outputParameters: {+ type: 'object',+ properties: {+ forecast: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ date: { type: 'string' },+ temperature: { type: 'number' },+ conditions: { type: 'string' }+ }+ }+ }+ }+ },+ handler: async (params, context) => {+ try {+ const { location, days = 3 } = params.arguments;++ // Here you would call your weather API+ const forecast = await getWeatherForecast(location, days);++ return {+ data: { forecast },+ successful: true,+ error: null+ };+ } catch (error) {+ return {+ data: {},+ successful: false,+ error: error.message+ };+ }+ }+});++// Now you can use your custom tool+const result = await composio.tools.execute('WEATHER_FORECAST', {+ userId: 'default',+ arguments: {+ location: 'San Francisco, CA',+ days: 5+ }+});++console.log(result.data.forecast);+```++## Next Steps++Now that you understand the basics, you can:++- Explore [more examples](../examples) to see how to use Composio in different scenarios+- Learn about [custom providers](./api/providers.md) to integrate with other AI frameworks+- Understand [error handling](./advanced/error-handling.md) to make your application more robust+- Implement [middleware and modifiers](./advanced/middleware.md) to customize tool execution\ No newline at end of filediff --git a/docs/overview.md b/docs/overview.mdnew file mode 100644index 000000000..3cb870614--- /dev/null+++ b/docs/overview.md@@ -0,0 +1,112 @@+# Composio SDK v3 Documentation++Composio SDK is a powerful toolkit that enables you to integrate third-party tools and services into your applications. This SDK helps you connect to various services (toolkits), execute tools, and manage user connections seamlessly.++## Table of Contents++- [Overview](#overview)+- [Installation](#installation)+- [Core Concepts](#core-concepts)+- [Getting Started](#getting-started)+- [API Reference](#api-reference)+- [Providers](#providers)+- [Examples](#examples)+- [Advanced Topics](#advanced-topics)++## Overview++Composio SDK allows you to:++- Execute tools from various services (like GitHub, Gmail, Slack, etc.)+- Manage user connections to external services+- Create custom tools+- Implement triggers and event handlers+- Integrate with AI providers like OpenAI++The SDK is designed to be flexible and extensible, allowing you to integrate it into various types of applications.++## Installation++```bash+npm install @composio/core+```++## Core Concepts++The Composio SDK is built around several key concepts:++- **Tools**: Individual actions that can be performed (e.g., "Get GitHub Repository", "Send Email")+- **Toolkits**: Collections of related tools (e.g., GitHub, Gmail)+- **Connected Accounts**: User connections to external services+- **Auth Configs**: Authentication configurations for external services+- **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)+- **Custom Tools**: Tools you can create and define yourself++Check out the [Core Concepts](./core-concepts.md) documentation for more detailed information.++## Getting Started++Here's a quick example of how to use the Composio SDK:++```typescript+import { Composio } from '@composio/sdk';++// Initialize the SDK+const composio = new Composio({+ apiKey: 'your-api-key',+});++// Get tools from a specific toolkit+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Execute a tool+const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: 'default',+ arguments: {+ owner: 'composio',+ repo: 'sdk',+ },+});++console.log(result.data);+```++For more detailed examples and tutorials, check out the [Getting Started](./getting-started.md) guide.++## API Reference++The complete API reference documentation is available here:++- [Composio Class](./api/composio.md)+- [Tools](./api/tools.md)+- [Toolkits](./api/toolkits.md)+- [Connected Accounts](./api/connected-accounts.md)+- [Auth Configs](./api/auth-configs.md)+- [Providers](./api/providers.md)+- [Custom Tools](./api/custom-tools.md)++## Providers++Composio SDK comes with built-in support for different providers:++- [OpenAI Provider](./providers/openai.md)+- [Custom Providers](./providers/custom.md)++## Examples++Check out our [examples directory](../examples) for complete code samples:++- [Connected Accounts](../examples/connected-accounts)+- [OpenAI Integration](../examples/openai)+- [LangChain Integration](../examples/langchain)+- [Toolkits](../examples/toolkits)+- [Modifiers](../examples/modifiers)++## Advanced Topics++- [Error Handling](./advanced/error-handling.md)+- [Telemetry](./advanced/telemetry.md)+- [Custom Providers](./advanced/custom-providers.md)+- [Middleware and Modifiers](./advanced/middleware.md)diff --git a/docs/providers/custom.md b/docs/providers/custom.mdnew file mode 100644index 000000000..99711e7be--- /dev/null+++ b/docs/providers/custom.md@@ -0,0 +1,366 @@+# Creating Custom Providers++Composio SDK allows you to create custom providers to integrate with different AI platforms and frameworks. This guide explains how to create custom providers for both agentic and non-agentic platforms.++## Provider Types++Composio supports two types of providers:++1. **Non-Agentic Providers**: For platforms where the provider simply formats tools but doesn't have its own agency (e.g., OpenAI).+2. **Agentic Providers**: For platforms where the provider has its own agency and can execute tools autonomously (e.g., an agent framework).++## Creating a Non-Agentic Provider++Non-agentic providers extend the `BaseNonAgenticProvider` class:++```typescript+import { BaseNonAgenticProvider, Tool } from '@composio/sdk';++// Define the tool type for your provider+type AnthropicTool = {+ name: string;+ description: string;+ parameters: Record<string, unknown>;+};++// Define the collection type for your provider+type AnthropicToolCollection = AnthropicTool[];++// Create the provider class+export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {+ // Define the provider name (used for telemetry)+ readonly name = 'anthropic';++ // Implement the wrapTool method+ override wrapTool(tool: Tool): AnthropicTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ parameters: tool.inputParameters || {},+ };+ }++ // Implement the wrapTools method+ override wrapTools(tools: Tool[]): AnthropicToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Add provider-specific methods+ async handleToolUsage(userId: string, toolName: string, params: Record<string, unknown>) {+ const result = await this.executeTool(toolName, {+ userId,+ arguments: params,+ });++ return JSON.stringify(result);+ }+}+```++## Creating an Agentic Provider++Agentic providers extend the `BaseAgenticProvider` class:++```typescript+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';++// Define the tool type for your provider+type LangchainTool = {+ name: string;+ description: string;+ func: Function;+};++// Define the collection type for your provider+type LangchainToolset = {+ tools: LangchainTool[];+ executor: (tool: LangchainTool, input: Record<string, unknown>) => Promise<unknown>;+};++// Create the provider class+export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, LangchainTool> {+ // Define the provider name (used for telemetry)+ readonly name = 'langchain';++ // Implement the wrapTool method (note the executeToolFn parameter)+ override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangchainTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ func: async (input: Record<string, unknown>) => {+ const result = await executeToolFn(tool.slug, input);+ return result.data;+ }+ };+ }++ // Implement the wrapTools method (note the executeToolFn parameter)+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolset {+ const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));++ return {+ tools: langchainTools,+ executor: async (tool, input) => {+ return await tool.func(input);+ }+ };+ }++ // Add provider-specific methods+ async createAgent(tools: LangchainToolset, model: any) {+ // Create a Langchain agent with the tools+ // This is just an example, the actual implementation would depend on the Langchain API+ return {+ run: async (prompt: string) => {+ // Run the agent with the prompt+ // The agent would use the tools.executor to execute tools+ }+ };+ }+}+```++## Using a Custom Provider++Once you've created a custom provider, you can use it with the Composio SDK:++```typescript+import { Composio } from '@composio/sdk';+import { AnthropicProvider } from './providers/anthropic-provider';++// Create an instance of your custom provider+const anthropicProvider = new AnthropicProvider();++// Initialize Composio with your custom provider+const composio = new Composio({+ apiKey: 'your-composio-api-key',+ provider: anthropicProvider,+});++// Get tools using your custom provider+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Now you can use these tools with Anthropic's API+// The tools will be formatted according to your provider's implementation+```++## Provider Methods++### Common Methods++Both types of providers have these methods available:++#### executeTool(toolSlug, body, modifiers?)++Executes a tool using the global execute function. This is useful for implementing provider-specific helper methods that need to execute tools.++```typescript+async executeTool(+ toolSlug: string,+ body: ToolExecuteParams,+ modifiers?: ExecuteToolModifiers+): Promise<ToolExecuteResponse>;+```++Example:++```typescript+class MyProvider extends BaseNonAgenticProvider<MyToolCollection, MyTool> {+ // Other methods...++ async executeWithContext(userId: string, toolSlug: string, args: Record<string, unknown>, context: string) {+ // Add context to the arguments+ const argsWithContext = { ...args, context };++ // Execute the tool+ return this.executeTool(toolSlug, {+ userId,+ arguments: argsWithContext,+ });+ }+}+```++### Non-Agentic Provider Methods++Non-agentic providers must implement these methods:++#### wrapTool(tool)++Transforms a Composio tool into the provider-specific format.++```typescript+wrapTool(tool: Tool): TTool;+```++#### wrapTools(tools)++Transforms a list of Composio tools into the provider-specific collection format.++```typescript+wrapTools(tools: Tool[]): TToolCollection;+```++### Agentic Provider Methods++Agentic providers must implement these methods:++#### wrapTool(tool, executeToolFn)++Transforms a Composio tool into the provider-specific format, with access to an execute function.++```typescript+wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): TTool;+```++#### wrapTools(tools, executeToolFn)++Transforms a list of Composio tools into the provider-specific collection format, with access to an execute function.++```typescript+wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): TToolCollection;+```++## Examples++### Claude Provider Example++```typescript+import { BaseNonAgenticProvider, Tool } from '@composio/sdk';++type ClaudeTool = {+ name: string;+ description: string;+ input_schema: {+ type: string;+ properties: Record<string, unknown>;+ required?: string[];+ };+};++type ClaudeToolCollection = ClaudeTool[];++export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection, ClaudeTool> {+ readonly name = 'claude';++ override wrapTool(tool: Tool): ClaudeTool {+ // Convert the input parameters to Claude's format+ const inputSchema = {+ type: 'object',+ properties: tool.inputParameters?.properties || {},+ required: tool.inputParameters?.required || [],+ };++ return {+ name: tool.slug,+ description: tool.description || '',+ input_schema: inputSchema,+ };+ }++ override wrapTools(tools: Tool[]): ClaudeToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Helper method for Claude tool execution+ async executeClaudeTool(userId: string, toolName: string, input: Record<string, unknown>) {+ const result = await this.executeTool(toolName, {+ userId,+ arguments: input,+ });++ return result.data;+ }+}+```++### LangChain Provider Example++```typescript+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';++// These types would match the actual LangChain API+type LangChainTool = {+ name: string;+ description: string;+ schema: any;+ call: (input: Record<string, unknown>) => Promise<any>;+};++type LangChainToolset = LangChainTool[];++export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, LangChainTool> {+ readonly name = 'langchain';++ override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {+ return {+ name: tool.slug,+ description: tool.description || '',+ schema: tool.inputParameters || {},+ call: async (input: Record<string, unknown>) => {+ const result = await executeToolFn(tool.slug, input);+ if (!result.successful) {+ throw new Error(result.error || 'Tool execution failed');+ }+ return result.data;+ }+ };+ }++ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolset {+ return tools.map(tool => this.wrapTool(tool, executeToolFn));+ }++ // LangChain-specific helper methods+ createAgent(tools: LangChainToolset, model: any) {+ // Implement LangChain agent creation+ // This is just a placeholder - the actual implementation would use the LangChain API+ }+}+```++## Advanced: Provider Context++You can store provider-specific context or state in your provider class:++```typescript+class ProviderWithContext extends BaseNonAgenticProvider<MyToolCollection, MyTool> {+ readonly name = 'provider-with-context';++ // Provider-specific context+ private cache = new Map<string, any>();+ private config: any;++ constructor(config: any) {+ super();+ this.config = config;+ }++ override wrapTool(tool: Tool): MyTool {+ // Use the config when wrapping tools+ const customizedTool = {+ name: tool.slug,+ description: this.config.addDescriptionPrefix+ ? `[${this.config.descriptionPrefix}] ${tool.description}`+ : tool.description,+ // Other properties...+ };++ // Cache the tool for later use+ this.cache.set(tool.slug, customizedTool);++ return customizedTool;+ }++ override wrapTools(tools: Tool[]): MyToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ // Custom method that uses the cache+ getTool(slug: string): MyTool | undefined {+ return this.cache.get(slug);+ }+}+```\ No newline at end of filediff --git a/docs/providers/openai.md b/docs/providers/openai.mdnew file mode 100644index 000000000..22cd08182--- /dev/null+++ b/docs/providers/openai.md@@ -0,0 +1,364 @@+# OpenAI Provider++The OpenAI Provider is the default provider for the Composio SDK. It transforms Composio tools into a format compatible with OpenAI's function calling capabilities.++## Overview++The OpenAI Provider allows you to:++1. Format Composio tools as OpenAI function tools+2. Handle tool calls from OpenAI chat completions+3. Handle tool calls from OpenAI assistants+4. Process streaming responses from OpenAI with tool calls++## Basic Usage++The OpenAI Provider is used by default when you initialize the Composio SDK:++```typescript+import { Composio } from '@composio/sdk';++// OpenAI Provider is used by default+const composio = new Composio({+ apiKey: 'your-composio-api-key',+});+```++You can also explicitly specify the OpenAI Provider:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';++// Explicitly specify the OpenAI Provider+const composio = new Composio({+ apiKey: 'your-composio-api-key',+ provider: new OpenAIProvider(),+});+```++## Getting Tools for OpenAI++The OpenAI Provider transforms Composio tools into OpenAI function tools:++```typescript+import { Composio } from '@composio/sdk';+import OpenAI from 'openai';++const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++const openai = new OpenAI({+ apiKey: 'your-openai-api-key',+});++// Get GitHub tools from Composio+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// The tools are already formatted for OpenAI+console.log(tools[0]); // { type: 'function', function: { name: 'GITHUB_GET_REPO', ... } }++// Use the tools with OpenAI+const completion = await openai.chat.completions.create({+ model: 'gpt-4',+ messages: [+ { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },+ { role: 'user', content: 'Find information about the Composio SDK repository' }+ ],+ tools, // Pass the tools to OpenAI+});+```++## Handling Tool Calls from OpenAI Chat Completions++When OpenAI's model decides to call a tool, you can use the OpenAI Provider to handle it:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';+import OpenAI from 'openai';++const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++const openai = new OpenAI({+ apiKey: 'your-openai-api-key',+});++// Get the OpenAI Provider+const openaiProvider = composio.provider as OpenAIProvider;++// Get GitHub tools+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Create a chat completion+const completion = await openai.chat.completions.create({+ model: 'gpt-4',+ messages: [+ { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },+ { role: 'user', content: 'Find information about the Composio SDK repository' }+ ],+ tools,+});++// Check if there are tool calls+if (completion.choices[0].message.tool_calls) {+ // Handle the tool calls+ const toolOutputs = await openaiProvider.handleToolCall(+ 'default', // userId+ completion,+ { connectedAccountId: 'connected_account_123' } // Optional+ );++ // Continue the conversation with the tool outputs+ const followupCompletion = await openai.chat.completions.create({+ model: 'gpt-4',+ messages: [+ { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },+ { role: 'user', content: 'Find information about the Composio SDK repository' },+ completion.choices[0].message,+ { role: 'tool', content: toolOutputs[0], tool_call_id: completion.choices[0].message.tool_calls[0].id }+ ],+ tools,+ });++ console.log(followupCompletion.choices[0].message.content);+}+```++## Working with OpenAI Assistants++The OpenAI Provider includes helper methods for working with OpenAI Assistants:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';+import OpenAI from 'openai';++const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++const openai = new OpenAI({+ apiKey: 'your-openai-api-key',+});++// Get the OpenAI Provider+const openaiProvider = composio.provider as OpenAIProvider;++// Get GitHub tools+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Create an assistant with Composio tools+const assistant = await openai.beta.assistants.create({+ name: 'GitHub Assistant',+ instructions: 'You are a helpful assistant with GitHub tools.',+ model: 'gpt-4',+ tools,+});++// Create a thread+const thread = await openai.beta.threads.create();++// Add a message to the thread+await openai.beta.threads.messages.create(thread.id, {+ role: 'user',+ content: 'Find information about the Composio SDK repository',+});++// Run the assistant+const run = await openai.beta.threads.runs.create(thread.id, {+ assistant_id: assistant.id,+});++// Wait for the run to complete and handle any tool calls+const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(+ 'default', // userId+ openai,+ run,+ thread,+ { connectedAccountId: 'connected_account_123' } // Optional+);++// Get the assistant's response+const messages = await openai.beta.threads.messages.list(thread.id);+console.log(messages.data[0].content);+```++## Handling Streaming Responses with Tool Calls++The OpenAI Provider can also handle streaming responses with tool calls:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';+import OpenAI from 'openai';++const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++const openai = new OpenAI({+ apiKey: 'your-openai-api-key',+});++// Get the OpenAI Provider+const openaiProvider = composio.provider as OpenAIProvider;++// Get GitHub tools+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+});++// Create an assistant with Composio tools+const assistant = await openai.beta.assistants.create({+ name: 'GitHub Assistant',+ instructions: 'You are a helpful assistant with GitHub tools.',+ model: 'gpt-4',+ tools,+});++// Create a thread+const thread = await openai.beta.threads.create();++// Add a message to the thread+await openai.beta.threads.messages.create(thread.id, {+ role: 'user',+ content: 'Find information about the Composio SDK repository',+});++// Run the assistant with streaming+const runStream = await openai.beta.threads.runs.createAndStream(thread.id, {+ assistant_id: assistant.id,+});++// Process the stream and handle tool calls+for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(+ 'default', // userId+ openai,+ runStream,+ thread,+ { connectedAccountId: 'connected_account_123' } // Optional+)) {+ // Process different event types+ if (event.event === 'thread.message.created') {+ console.log('New message created');+ } else if (event.event === 'thread.message.delta') {+ console.log('Message update:', event.data.delta.content);+ } else if (event.event === 'thread.run.requires_action') {+ console.log('Run requires action (tools being executed)');+ } else if (event.event === 'thread.run.completed') {+ console.log('Run completed');+ }+}+```++## Modifiers with OpenAI Provider++You can use modifiers with the OpenAI Provider to transform tools and tool execution:++```typescript+import { Composio, OpenAIProvider } from '@composio/sdk';++const composio = new Composio({+ apiKey: 'your-composio-api-key',+});++// Get GitHub tools with modifiers+const tools = await composio.tools.get('default', {+ toolkits: ['github'],+}, {+ // Modify tool schema+ modifyToolSchema: (toolSlug, toolkitSlug, tool) => {+ // Make tool descriptions more concise for OpenAI+ if (tool.description && tool.description.length > 100) {+ tool.description = tool.description.substring(0, 100) + '...';+ }+ return tool;+ },++ // Modify parameters before execution+ beforeToolExecute: (toolSlug, toolkitSlug, params) => {+ console.log(`Executing ${toolSlug} tool`);+ return params;+ },++ // Transform results after execution+ afterToolExecute: (toolSlug, toolkitSlug, result) => {+ // Format the result data for better presentation+ if (result.successful && toolSlug === 'GITHUB_GET_REPO') {+ result.data = {+ name: result.data.name,+ description: result.data.description,+ stars: result.data.stargazers_count,+ forks: result.data.forks_count,+ url: result.data.html_url,+ };+ }+ return result;+ }+});+```++## Type Definitions++The OpenAI Provider exports these types:++```typescript+// OpenAI tool type (matches OpenAI's API)+type OpenAiTool = OpenAI.ChatCompletionTool;++// Collection of OpenAI tools+type OpenAiToolCollection = Array<OpenAiTool>;++// The provider class+class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAiTool> {+ readonly name = 'openai';++ wrapTool(tool: Tool): OpenAiTool;+ wrapTools(tools: Tool[]): OpenAiToolCollection;++ executeToolCall(+ userId: string,+ tool: OpenAI.ChatCompletionMessageToolCall,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<string>;++ handleToolCall(+ userId: string,+ chatCompletion: OpenAI.ChatCompletion,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<string[]>;++ handleAssistantMessage(+ userId: string,+ run: OpenAI.Beta.Threads.Run,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>;++ waitAndHandleAssistantStreamToolCalls(+ userId: string,+ client: OpenAI,+ runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,+ thread: OpenAI.Beta.Threads.Thread,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>;++ waitAndHandleAssistantToolCalls(+ userId: string,+ client: OpenAI,+ run: OpenAI.Beta.Threads.Run,+ thread: OpenAI.Beta.Threads.Thread,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<OpenAI.Beta.Threads.Run>;+}+```\ No newline at end of filediff --git a/packages/core/.env.example b/packages/core/.env.examplenew file mode 100644index 000000000..2c275167a--- /dev/null+++ b/packages/core/.env.example@@ -0,0 +1,3 @@+COMPOSIO_LOG_LEVEL=+COMPOSIO_API_KEY=+COMPOSIO_API_BASE_URL=\ No newline at end of file