Skip to content

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

Add sdk docs

haxzie49064c38f65f
diff --git a/docs/advanced/custom-providers.md b/docs/advanced/custom-providers.md
index afa2d240b..6f8f7ca15 100644
--- a/docs/advanced/custom-providers.md
+++ b/docs/advanced/custom-providers.md
@@ -33,7 +33,7 @@ BaseProvider (Abstract)
Non-agentic providers implement the `BaseNonAgenticProvider` abstract class:
```typescript
-import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
+import { BaseNonAgenticProvider, Tool } from '@composio/core';
// Define your tool format
interface MyAITool {
@@ -53,7 +53,7 @@ type MyAIToolCollection = MyAITool[];
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 {
@@ -66,12 +66,12 @@ export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyA
},
};
}
-
+
// 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,
@@ -81,14 +81,11 @@ export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyA
}
): Promise<string> {
// Use the built-in executeTool method
- const result = await this.executeTool(
- toolCall.name,
- {
- userId,
- arguments: toolCall.arguments,
- }
- );
-
+ const result = await this.executeTool(toolCall.name, {
+ userId,
+ arguments: toolCall.arguments,
+ });
+
return JSON.stringify(result.data);
}
}
@@ -99,7 +96,7 @@ export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyA
Agentic providers implement the `BaseAgenticProvider` abstract class:
```typescript
-import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/core';
// Define your tool format
interface AgentTool {
@@ -119,7 +116,7 @@ interface AgentToolkit {
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 {
@@ -132,29 +129,29 @@ export class MyAgentProvider extends BaseAgenticProvider<AgentToolkit, AgentTool
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) => {
+ 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({});
@@ -168,7 +165,7 @@ export class MyAgentProvider extends BaseAgenticProvider<AgentToolkit, AgentTool
After creating your provider, use it with the Composio SDK:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
import { MyAIProvider } from './my-ai-provider';
// Create your provider instance
@@ -196,20 +193,20 @@ 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
@@ -217,22 +214,22 @@ export class StatefulProvider extends BaseNonAgenticProvider<ToolCollection, Too
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);
}
@@ -244,7 +241,7 @@ export class StatefulProvider extends BaseNonAgenticProvider<ToolCollection, Too
You can compose functionality by extending existing providers:
```typescript
-import { OpenAIProvider } from '@composio/sdk';
+import { OpenAIProvider } from '@composio/openai';
// Extend the OpenAI provider with custom functionality
export class EnhancedOpenAIProvider extends OpenAIProvider {
@@ -253,11 +250,11 @@ export class EnhancedOpenAIProvider extends OpenAIProvider {
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);
@@ -267,16 +264,16 @@ export class EnhancedOpenAIProvider extends OpenAIProvider {
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);
@@ -286,7 +283,7 @@ export class EnhancedOpenAIProvider extends OpenAIProvider {
await new Promise(resolve => setTimeout(resolve, 1000 * attempts));
}
}
-
+
throw lastError;
}
}
@@ -297,7 +294,7 @@ export class EnhancedOpenAIProvider extends OpenAIProvider {
Here's a more complete example for Anthropic's Claude:
```typescript
-import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
+import { BaseNonAgenticProvider, Tool } from '@composio/core';
import Anthropic from '@anthropic-ai/sdk';
interface ClaudeTool {
@@ -315,14 +312,14 @@ 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,
@@ -334,41 +331,36 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
},
};
}
-
+
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 }
- ],
+ 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
- )) {
+ 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,
- }
- );
-
+ const result = await this.executeTool(content.name, {
+ userId,
+ arguments: content.input,
+ });
+
return {
type: 'tool_result',
tool_use_id: content.id,
@@ -376,7 +368,7 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
};
})
);
-
+
// Continue the conversation with tool results
const followupResponse = await this.client.messages.create({
model: 'claude-3-opus-20240229',
@@ -385,14 +377,14 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
messages: [
{ role: 'user', content: prompt },
{ role: 'assistant', content: response.content },
- { role: 'user', content: toolResponses }
+ { role: 'user', content: toolResponses },
],
tools,
});
-
+
return followupResponse;
}
-
+
return response;
}
}
@@ -403,7 +395,7 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
Here's an example for LangChain:
```typescript
-import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/core';
import { DynamicTool } from 'langchain/tools';
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { initializeAgentExecutorWithOptions } from 'langchain/agents';
@@ -421,7 +413,7 @@ interface LangChainToolkit {
export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, LangChainTool> {
readonly name = 'langchain';
-
+
override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {
return new DynamicTool({
name: tool.slug,
@@ -430,26 +422,26 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, Lan
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 }) => {
@@ -457,25 +449,17 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, Lan
modelName: model || 'gpt-4',
temperature: 0,
});
-
- return await initializeAgentExecutorWithOptions(
- langchainTools,
- llm,
- {
- agentType: 'chat-zero-shot-react-description',
- verbose: true,
- }
- );
- }
+
+ 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> {
+ 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;
@@ -491,4 +475,4 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, Lan
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 file
+7. **Use telemetry**: Set a meaningful provider name for telemetry insights
diff --git a/docs/advanced/telemetry.md b/docs/advanced/telemetry.md
index 5ec2bd875..d0a7a5979 100644
--- a/docs/advanced/telemetry.md
+++ b/docs/advanced/telemetry.md
@@ -20,6 +20,7 @@ The telemetry system collects the following types of data:
- **Environment Information**: SDK version, provider used, runtime context
No personal or sensitive information such as:
+
- API keys
- Tool arguments
- Tool responses
@@ -31,7 +32,7 @@ No personal or sensitive information such as:
You can disable telemetry when initializing the SDK:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: 'your-api-key',
@@ -51,18 +52,18 @@ COMPOSIO_DISABLE_TELEMETRY=true
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';
+import { Composio, BaseTelemetryTransport, TelemetryEvent } from '@composio/core';
// 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();
@@ -81,35 +82,35 @@ const composio = new Composio({
To implement a custom telemetry transport, extend the `BaseTelemetryTransport` class:
```typescript
-import { BaseTelemetryTransport, TelemetryEvent } from '@composio/sdk';
+import { BaseTelemetryTransport, TelemetryEvent } from '@composio/core';
export class CustomTelemetryTransport extends BaseTelemetryTransport {
// Optional constructor for configuration
- constructor(private config: { endpoint: string, batchSize: number }) {
+ 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, {
@@ -122,7 +123,7 @@ export class CustomTelemetryTransport extends BaseTelemetryTransport {
timestamp: new Date().toISOString(),
}),
});
-
+
// Clear the batch
this.events = [];
} catch (error) {
@@ -211,14 +212,14 @@ 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)
+ 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)
}
```
@@ -235,4 +236,4 @@ The SDK automatically detects whether it's running in a browser or Node.js envir
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 file
+5. If you **implement a custom provider**, set a meaningful name to improve telemetry insights
diff --git a/docs/api/composio.md b/docs/api/composio.md
index beb9d2e13..00e8c8dfe 100644
--- a/docs/api/composio.md
+++ b/docs/api/composio.md
@@ -5,7 +5,7 @@ The `Composio` class is the main entry point to the Composio SDK. It initializes
## Initialization
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: 'your-api-key',
@@ -21,27 +21,27 @@ const composio = new Composio({
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 |
+| 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 |
+| 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
@@ -62,7 +62,7 @@ const client = composio.getClient();
### Basic Initialization
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
@@ -72,7 +72,8 @@ const composio = new Composio({
### Custom Provider
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
const openaiProvider = new OpenAIProvider();
const composio = new Composio({
@@ -84,10 +85,10 @@ const composio = new Composio({
### Disable Tracking
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
allowTracking: false,
});
-```
\ No newline at end of file
+```
diff --git a/docs/api/providers.md b/docs/api/providers.md
index cc3bd6175..a2e662b67 100644
--- a/docs/api/providers.md
+++ b/docs/api/providers.md
@@ -26,7 +26,7 @@ abstract class BaseNonAgenticProvider<TToolCollection, TTool> extends BaseProvid
// 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;
}
@@ -42,7 +42,7 @@ abstract class BaseAgenticProvider<TToolCollection, TTool> extends BaseProvider
// 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;
}
@@ -53,7 +53,8 @@ abstract class BaseAgenticProvider<TToolCollection, TTool> extends BaseProvider
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';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
const composio = new Composio({
apiKey: 'your-api-key',
@@ -72,6 +73,7 @@ const openaiTool = openaiProvider.wrapTool(composioTool);
```
**Parameters:**
+
- `tool` (Tool): The Composio tool to transform
**Returns:** OpenAI.ChatCompletionTool - The tool in OpenAI format
@@ -85,6 +87,7 @@ const openaiTools = openaiProvider.wrapTools(composioTools);
```
**Parameters:**
+
- `tools` (Tool[]): The list of Composio tools to transform
**Returns:** Array<OpenAI.ChatCompletionTool> - The tools in OpenAI format
@@ -98,14 +101,15 @@ const result = await openaiProvider.executeToolCall(
'user123',
toolCall,
{ connectedAccountId: 'conn_abc123' },
- {
+ {
beforeToolExecute: (toolSlug, toolkitSlug, params) => params,
- afterToolExecute: (toolSlug, toolkitSlug, result) => result
+ 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
@@ -118,13 +122,11 @@ const result = await openaiProvider.executeToolCall(
Handles tool calls from an OpenAI chat completion.
```typescript
-const outputs = await openaiProvider.handleToolCall(
- 'user123',
- chatCompletion
-);
+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
@@ -137,13 +139,11 @@ const outputs = await openaiProvider.handleToolCall(
Handles tool calls from an OpenAI assistant run.
```typescript
-const toolOutputs = await openaiProvider.handleAssistantMessage(
- 'user123',
- run
-);
+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
@@ -167,6 +167,7 @@ for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(
```
**Parameters:**
+
- `userId` (string): The user ID
- `client` (OpenAI): The OpenAI client
- `runStream` (Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>): The run stream
@@ -190,6 +191,7 @@ const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(
```
**Parameters:**
+
- `userId` (string): The user ID
- `client` (OpenAI): The OpenAI client
- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls
@@ -204,7 +206,7 @@ const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(
You can create custom providers by extending either `BaseNonAgenticProvider` or `BaseAgenticProvider`:
```typescript
-import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
+import { BaseNonAgenticProvider, Tool } from '@composio/core';
type AnthropicTool = {
name: string;
@@ -214,7 +216,10 @@ type AnthropicTool = {
type AnthropicToolCollection = AnthropicTool[];
-export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {
+export class AnthropicProvider extends BaseNonAgenticProvider<
+ AnthropicToolCollection,
+ AnthropicTool
+> {
readonly name = 'anthropic';
override wrapTool(tool: Tool): AnthropicTool {
@@ -265,11 +270,7 @@ interface ExecuteToolModifiers {
### TransformToolSchemaModifier
```typescript
-type TransformToolSchemaModifier = (
- toolSlug: string,
- toolkitSlug: string,
- tool: Tool
-) => Tool;
+type TransformToolSchemaModifier = (toolSlug: string, toolkitSlug: string, tool: Tool) => Tool;
```
### BeforeToolExecuteModifier
@@ -290,4 +291,4 @@ type AfterToolExecuteModifier = (
toolkitSlug: string,
result: ToolExecuteResponse
) => ToolExecuteResponse;
-```
\ No newline at end of file
+```
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 716dc142f..446b4be9e 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -8,13 +8,13 @@ Install the Composio SDK using npm, yarn, or pnpm:
```bash
# Using npm
-npm install @composio/sdk
+npm install @composio/core
# Using yarn
-yarn add @composio/sdk
+yarn add @composio/core
# Using pnpm
-pnpm add @composio/sdk
+pnpm add @composio/core
```
## Initialization
@@ -22,7 +22,7 @@ pnpm add @composio/sdk
To use the SDK, you need to initialize it with your API key:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
// Initialize the SDK
const composio = new Composio({
@@ -33,7 +33,8 @@ const composio = new Composio({
You can also customize the initialization with additional options:
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
// Initialize with custom provider and options
const composio = new Composio({
@@ -57,7 +58,7 @@ console.log(allToolkits.items);
// Get toolkits by category
const devToolkits = await composio.toolkits.get({
- category: 'developer-tools'
+ category: 'developer-tools',
});
```
@@ -139,7 +140,7 @@ const result = await composio.tools.execute('GITHUB_GET_REPOS', {
Composio integrates seamlessly with OpenAI. Here's an example of using Composio tools with OpenAI:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
import OpenAI from 'openai';
// Initialize Composio and OpenAI
@@ -161,7 +162,7 @@ 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' }
+ { role: 'user', content: 'List the repositories in the Composio organization' },
],
tools, // Pass the tools to OpenAI
});
@@ -172,13 +173,13 @@ if (completion.choices[0].message.tool_calls) {
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);
}
@@ -202,15 +203,15 @@ const customTool = await composio.tools.createCustomTool({
properties: {
location: {
type: 'string',
- description: 'The location to get the forecast for'
+ description: 'The location to get the forecast for',
},
days: {
type: 'integer',
description: 'Number of days for the forecast',
- default: 3
- }
+ default: 3,
+ },
},
- required: ['location']
+ required: ['location'],
},
outputParameters: {
type: 'object',
@@ -222,32 +223,32 @@ const customTool = await composio.tools.createCustomTool({
properties: {
date: { type: 'string' },
temperature: { type: 'number' },
- conditions: { type: 'string' }
- }
- }
- }
- }
+ 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
+ error: null,
};
} catch (error) {
return {
data: {},
successful: false,
- error: error.message
+ error: error.message,
};
}
- }
+ },
});
// Now you can use your custom tool
@@ -255,8 +256,8 @@ const result = await composio.tools.execute('WEATHER_FORECAST', {
userId: 'default',
arguments: {
location: 'San Francisco, CA',
- days: 5
- }
+ days: 5,
+ },
});
console.log(result.data.forecast);
@@ -269,4 +270,4 @@ 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 file
+- Implement [middleware and modifiers](./advanced/middleware.md) to customize tool execution
diff --git a/docs/overview.md b/docs/index.md
similarity index 98%
rename from docs/overview.md
rename to docs/index.md
index 3cb870614..6748cd7e8 100644
--- a/docs/overview.md
+++ b/docs/index.md
@@ -49,7 +49,7 @@ Check out the [Core Concepts](./core-concepts.md) documentation for more detaile
Here's a quick example of how to use the Composio SDK:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
// Initialize the SDK
const composio = new Composio({
diff --git a/docs/providers/custom.md b/docs/providers/custom.md
index 99711e7be..e3a8befc5 100644
--- a/docs/providers/custom.md
+++ b/docs/providers/custom.md
@@ -14,7 +14,7 @@ Composio supports two types of providers:
Non-agentic providers extend the `BaseNonAgenticProvider` class:
```typescript
-import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
+import { BaseNonAgenticProvider, Tool } from '@composio/core';
// Define the tool type for your provider
type AnthropicTool = {
@@ -27,7 +27,10 @@ type AnthropicTool = {
type AnthropicToolCollection = AnthropicTool[];
// Create the provider class
-export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {
+export class AnthropicProvider extends BaseNonAgenticProvider<
+ AnthropicToolCollection,
+ AnthropicTool
+> {
// Define the provider name (used for telemetry)
readonly name = 'anthropic';
@@ -51,7 +54,7 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolColle
userId,
arguments: params,
});
-
+
return JSON.stringify(result);
}
}
@@ -62,7 +65,7 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolColle
Agentic providers extend the `BaseAgenticProvider` class:
```typescript
-import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/core';
// Define the tool type for your provider
type LangchainTool = {
@@ -90,19 +93,19 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan
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);
- }
+ },
};
}
@@ -114,7 +117,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan
run: async (prompt: string) => {
// Run the agent with the prompt
// The agent would use the tools.executor to execute tools
- }
+ },
};
}
}
@@ -125,7 +128,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan
Once you've created a custom provider, you can use it with the Composio SDK:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
import { AnthropicProvider } from './providers/anthropic-provider';
// Create an instance of your custom provider
@@ -169,11 +172,16 @@ Example:
```typescript
class MyProvider extends BaseNonAgenticProvider<MyToolCollection, MyTool> {
// Other methods...
-
- async executeWithContext(userId: string, toolSlug: string, args: Record<string, unknown>, context: string) {
+
+ 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,
@@ -228,7 +236,7 @@ wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): TToolCollection;
### Claude Provider Example
```typescript
-import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
+import { BaseNonAgenticProvider, Tool } from '@composio/core';
type ClaudeTool = {
name: string;
@@ -252,7 +260,7 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
properties: tool.inputParameters?.properties || {},
required: tool.inputParameters?.required || [],
};
-
+
return {
name: tool.slug,
description: tool.description || '',
@@ -270,7 +278,7 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
userId,
arguments: input,
});
-
+
return result.data;
}
}
@@ -279,7 +287,7 @@ export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection,
### LangChain Provider Example
```typescript
-import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
+import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/core';
// These types would match the actual LangChain API
type LangChainTool = {
@@ -305,7 +313,7 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, Lan
throw new Error(result.error || 'Tool execution failed');
}
return result.data;
- }
+ },
};
}
@@ -328,39 +336,39 @@ 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}`
+ 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 file
+```
diff --git a/docs/providers/openai.md b/docs/providers/openai.md
index 22cd08182..06d251589 100644
--- a/docs/providers/openai.md
+++ b/docs/providers/openai.md
@@ -16,7 +16,7 @@ The OpenAI Provider allows you to:
The OpenAI Provider is used by default when you initialize the Composio SDK:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
// OpenAI Provider is used by default
const composio = new Composio({
@@ -27,7 +27,8 @@ const composio = new Composio({
You can also explicitly specify the OpenAI Provider:
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
// Explicitly specify the OpenAI Provider
const composio = new Composio({
@@ -41,7 +42,7 @@ const composio = new Composio({
The OpenAI Provider transforms Composio tools into OpenAI function tools:
```typescript
-import { Composio } from '@composio/sdk';
+import { Composio } from '@composio/core';
import OpenAI from 'openai';
const composio = new Composio({
@@ -65,7 +66,7 @@ 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' }
+ { role: 'user', content: 'Find information about the Composio SDK repository' },
],
tools, // Pass the tools to OpenAI
});
@@ -76,7 +77,8 @@ const completion = await openai.chat.completions.create({
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 { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
import OpenAI from 'openai';
const composio = new Composio({
@@ -100,7 +102,7 @@ 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' }
+ { role: 'user', content: 'Find information about the Composio SDK repository' },
],
tools,
});
@@ -113,7 +115,7 @@ if (completion.choices[0].message.tool_calls) {
completion,
{ connectedAccountId: 'connected_account_123' } // Optional
);
-
+
// Continue the conversation with the tool outputs
const followupCompletion = await openai.chat.completions.create({
model: 'gpt-4',
@@ -121,11 +123,15 @@ if (completion.choices[0].message.tool_calls) {
{ 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 }
+ {
+ role: 'tool',
+ content: toolOutputs[0],
+ tool_call_id: completion.choices[0].message.tool_calls[0].id,
+ },
],
tools,
});
-
+
console.log(followupCompletion.choices[0].message.content);
}
```
@@ -135,7 +141,8 @@ if (completion.choices[0].message.tool_calls) {
The OpenAI Provider includes helper methods for working with OpenAI Assistants:
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
import OpenAI from 'openai';
const composio = new Composio({
@@ -195,7 +202,8 @@ console.log(messages.data[0].content);
The OpenAI Provider can also handle streaming responses with tool calls:
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
import OpenAI from 'openai';
const composio = new Composio({
@@ -262,46 +270,51 @@ for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(
You can use modifiers with the OpenAI Provider to transform tools and tool execution:
```typescript
-import { Composio, OpenAIProvider } from '@composio/sdk';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
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;
+const tools = await composio.tools.get(
+ 'default',
+ {
+ toolkits: ['github'],
},
-
- // 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;
+ {
+ // 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
@@ -318,31 +331,31 @@ 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,
@@ -351,7 +364,7 @@ class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAi
options?: ExecuteToolFnOptions,
modifiers?: ExecuteToolModifiers
): AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>;
-
+
waitAndHandleAssistantToolCalls(
userId: string,
client: OpenAI,
@@ -361,4 +374,4 @@ class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAi
modifiers?: ExecuteToolModifiers
): Promise<OpenAI.Beta.Threads.Run>;
}
-```
\ No newline at end of file
+```