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
Fix anthropic provider and examples
haxzie5d98d02571f2
diff --git a/examples/anthropic/.env.example b/examples/anthropic/.env.examplenew file mode 100644index 000000000..eeeaae119--- /dev/null+++ b/examples/anthropic/.env.example@@ -0,0 +1,2 @@+COMPOSIO_API_KEY=+ANTHROPIC_API_KEY=\ No newline at end of filediff --git a/examples/anthropic/package.json b/examples/anthropic/package.jsonindex e8d68e7c1..3f58263ed 100644--- a/examples/anthropic/package.json+++ b/examples/anthropic/package.json@@ -13,7 +13,7 @@"license": "ISC","packageManager": "[email protected]","dependencies": {- "@anthropic-ai/sdk": "^0.18.0",+ "@anthropic-ai/sdk": "^0.52.0","@composio/core": "workspace:*","@composio/anthropic": "workspace:*","dotenv": "^16.4.1"diff --git a/examples/anthropic/src/index.ts b/examples/anthropic/src/index.tsindex c9811891c..6f9289c1c 100644--- a/examples/anthropic/src/index.ts+++ b/examples/anthropic/src/index.ts@@ -1,6 +1,6 @@/*** Example for using Anthropic provider with Composio SDK- *+ ** Required environment variables:* - COMPOSIO_API_KEY: Your Composio API key (get one at https://app.composio.dev)* - ANTHROPIC_API_KEY: Your Anthropic API key (get one at https://console.anthropic.com)@@ -24,62 +24,59 @@ const composio = new Composio({async function main() {try {- console.log('Fetching tools from Composio...');+ console.log('π Fetching tools from Composio...');/*** Get the Hacker News user tool* This tool is automatically wrapped with the Anthropic provider format*/const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');- console.log(`Fetched ${tools.length} tools`);+ console.log(`β Fetched ${tools.length} tools`);- console.log('Creating message with Anthropic...');+ console.log('π Creating message with Anthropic...');/*** Create a message with Anthropic that may use tools*/const message = await anthropic.messages.create({- model: 'claude-3-sonnet-20240229',+ model: 'claude-3-7-sonnet-latest',max_tokens: 1024,- tools,+ tools: tools,messages: [{role: 'user',- content: "Fetch the details of the user 'pg' from Hacker News and summarize their profile",+ content:+ "Fetch the details of the user 'pg' from Hacker News and summarize their profile",},],});- console.log('Message created, processing tool calls if any...');-+ console.log('β Message created, processing tool calls if any...');+/*** Extract tool use blocks from the message content*/- const toolUseBlocks = message.content.filter(- (content) => content.type === 'tool_use'- );+ const toolUseBlocks = message.content.filter(content => content.type === 'tool_use');if (toolUseBlocks.length > 0) {- console.log(`Found ${toolUseBlocks.length} tool calls`);-+ console.log(`β Found ${toolUseBlocks.length} tool calls`);+/*** Execute the tool calls using Composio*/- const toolResults = await composio.provider.handleToolCalls(- 'default',- message- );-- console.log('Tool results:', toolResults);-+ const toolResults = await composio.provider.handleToolCalls('default', message);++ console.log('β Tool results:', toolResults);+/*** Send a follow-up message with the tool results*/const followUpMessage = await anthropic.messages.create({- model: 'claude-3-sonnet-20240229',+ model: 'claude-3-7-sonnet-latest',max_tokens: 1024,messages: [{role: 'user',- content: "Fetch the details of the user 'pg' from Hacker News and summarize their profile",+ content:+ "Fetch the details of the user 'pg' from Hacker News and summarize their profile",},{role: 'assistant',@@ -103,27 +100,28 @@ async function main() {},],});-+/*** Extract the text response from the follow-up message*/+ console.log('π Extracting the text response from the follow-up message...');const finalResponse = followUpMessage.content- .filter((content) => content.type === 'text')- .map((content) => content.text)+ .filter(content => content.type === 'text')+ .map(content => content.text).join('\n');-- console.log('Final response:');++ console.log('β Final response:');console.log(finalResponse);} else {/*** If no tool calls were made, just show the text response*/const response = message.content- .filter((content) => content.type === 'text')- .map((content) => content.text)+ .filter(content => content.type === 'text')+ .map(content => content.text).join('\n');-- console.log('Response (no tool calls):');++ console.log('β Response (no tool calls):');console.log(response);}} catch (error) {diff --git a/examples/anthropic/src/streaming.ts b/examples/anthropic/src/streaming.tsnew file mode 100644index 000000000..58fb2cd6a--- /dev/null+++ b/examples/anthropic/src/streaming.ts@@ -0,0 +1,116 @@+/**+ * Example for using Anthropic provider with Composio SDK+ *+ * Required environment variables:+ * - COMPOSIO_API_KEY: Your Composio API key (get one at https://app.composio.dev)+ * - ANTHROPIC_API_KEY: Your Anthropic API key (get one at https://console.anthropic.com)+ */+import { Composio } from '@composio/core';+import { AnthropicProvider } from '@composio/anthropic';+import Anthropic from '@anthropic-ai/sdk';+import 'dotenv/config';+import { stdout } from 'process';++const anthropic = new Anthropic({+ apiKey: process.env.ANTHROPIC_API_KEY,+});++/**+ * Initialize Composio with the Anthropic provider+ */+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: new AnthropicProvider(),+});++async function main() {+ console.log('π Fetching tools from Composio...');+ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');+ console.log(`β Fetched ${tools.length} tools`);++ console.log('π Creating message with Anthropic...');+ const stream = await anthropic.messages+ .stream({+ model: 'claude-3-5-sonnet-latest',+ max_tokens: 1024,+ messages: [+ {+ role: 'user',+ content: 'Tell me about the user "pg" from Hacker News',+ },+ ],+ tools: tools,+ })+ .on('text', text => {+ stdout.write(text);+ })+ .on('end', () => {+ stdout.write('\n');+ });++ const message = await stream.finalMessage();++ /**+ * Extract tool use blocks from the message content+ */+ const toolUseBlocks = message.content.filter(content => content.type === 'tool_use');++ if (toolUseBlocks.length > 0) {+ console.log(`β Found ${toolUseBlocks.length} tool calls`);++ /**+ * Execute the tool calls using Composio+ */+ const toolResults = await composio.provider.handleToolCalls('default', message);++ console.log('β Tool results:', toolResults);++ /**+ * Send a follow-up message with the tool results+ */+ const followUpStream = await anthropic.messages+ .stream({+ model: 'claude-3-7-sonnet-latest',+ max_tokens: 1024,+ messages: [+ {+ role: 'user',+ content:+ "Fetch the details of the user 'pg' from Hacker News and summarize their profile",+ },+ {+ role: 'assistant',+ content: [+ {+ type: 'text',+ text: "I'll fetch the details for the Hacker News user 'pg'.",+ },+ ...toolUseBlocks,+ ],+ },+ {+ role: 'user',+ content: [+ {+ type: 'tool_result',+ tool_use_id: toolUseBlocks[0].id,+ content: toolResults[0],+ },+ ],+ },+ ],+ })+ .on('text', text => {+ stdout.write(text);+ })+ .on('end', () => {+ stdout.write('\n');+ });++ const followUpMessage = await followUpStream.finalMessage();++ console.log(followUpMessage);+ }+}++main();diff --git a/examples/anthropic/tsconfig.json b/examples/anthropic/tsconfig.jsonnew file mode 100644index 000000000..158c157c8--- /dev/null+++ b/examples/anthropic/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "declarationDir": "./dist",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}diff --git a/packages/providers/anthropic/package.json b/packages/providers/anthropic/package.jsonindex 7f529676e..4d9a9d0b4 100644--- a/packages/providers/anthropic/package.json+++ b/packages/providers/anthropic/package.json@@ -32,11 +32,9 @@"author": "","license": "ISC","packageManager": "[email protected]",- "dependencies": {- "@anthropic-ai/sdk": "^0.18.0"- },"peerDependencies": {- "@composio/core": "^0.1.0"+ "@anthropic-ai/sdk": "^0.52.0",+ "@composio/core": "workspace:*"},"devDependencies": {"@composio/core": "workspace:*",diff --git a/packages/providers/anthropic/src/index.ts b/packages/providers/anthropic/src/index.tsindex 8b1b30e60..6a019d63e 100644--- a/packages/providers/anthropic/src/index.ts+++ b/packages/providers/anthropic/src/index.ts@@ -7,27 +7,15 @@* @packageDocumentation* @module providers/anthropic*/-import {- BaseNonAgenticProvider,- Tool,+import {+ BaseNonAgenticProvider,+ Tool as ComposioTool,ExecuteToolModifiers,ExecuteToolFnOptions,- ToolExecuteParams+ ToolExecuteParams,} from '@composio/core';import Anthropic from '@anthropic-ai/sdk';--/**- * Anthropic tool format based on their API docs- */-export interface AnthropicTool {- name: string;- description: string;- input_schema: {- type: string;- properties: Record<string, unknown>;- required: string[];- };-}+import { AnthropicTool } from './types';/*** Collection of Anthropic tools@@ -55,7 +43,10 @@ export type AnthropicContentBlock = {/*** Anthropic Provider implementation for Composio*/-export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {+export class AnthropicProvider extends BaseNonAgenticProvider<+ AnthropicToolCollection,+ AnthropicTool+> {readonly name = 'anthropic';/**@@ -63,17 +54,14 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolColle* @param tool - The tool to wrap.* @returns The wrapped tool in Anthropic format.*/- override wrapTool(tool: Tool): AnthropicTool {- const properties = tool.inputParameters?.properties || {};- const required = tool.inputParameters?.required || [];-+ override wrapTool(tool: ComposioTool): AnthropicTool {return {name: tool.slug,description: tool.description || '',input_schema: {type: 'object',- properties: properties as Record<string, unknown>,- required: required as string[],+ properties: (tool.inputParameters?.properties || {}) as Record<string, unknown>,+ required: (tool.inputParameters?.required || []) as string[],},};}@@ -83,7 +71,7 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolColle* @param tools - The tools to wrap.* @returns The wrapped tools in Anthropic format.*/- override wrapTools(tools: Tool[]): AnthropicToolCollection {+ override wrapTools(tools: ComposioTool[]): AnthropicToolCollection {return tools.map(tool => this.wrapTool(tool));}@@ -126,15 +114,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollemodifiers?: ExecuteToolModifiers): Promise<string[]> {const outputs: string[] = [];-+// Filter and map tool use blocks from message contentconst toolUseBlocks: AnthropicToolUseBlock[] = [];-+for (const content of message.content) {if (- typeof content === 'object' &&- content !== null &&- 'type' in content &&+ typeof content === 'object' &&+ content !== null &&+ 'type' in content &&typeof content.type === 'string' &&content.type.toString() === 'tool_use' &&'id' in content &&@@ -145,15 +133,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolColletype: 'tool_use',id: String(content.id),name: String(content.name),- input: content.input as Record<string, unknown>+ input: content.input as Record<string, unknown>,});}}-+for (const toolUse of toolUseBlocks) {outputs.push(await this.executeToolCall(userId, toolUse, options, modifiers));}-+return outputs;}}diff --git a/packages/providers/anthropic/src/types.ts b/packages/providers/anthropic/src/types.tsnew file mode 100644index 000000000..7590e68d0--- /dev/null+++ b/packages/providers/anthropic/src/types.ts@@ -0,0 +1,51 @@+export interface AnthropicTool {+ /**+ * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.+ *+ * This defines the shape of the `input` that your tool accepts and that the model+ * will produce.+ */+ input_schema: InputSchema;++ /**+ * Name of the tool.+ *+ * This is how the tool will be called by the model and in `tool_use` blocks.+ */+ name: string;++ /**+ * Create a cache control breakpoint at this content block.+ */+ cache_control?: CacheControlEphemeral | null;++ /**+ * Description of what this tool does.+ *+ * Tool descriptions should be as detailed as possible. The more information that+ * the model has about what the tool is and how to use it, the better it will+ * perform. You can use natural language descriptions to reinforce important+ * aspects of the tool input JSON schema.+ */+ description?: string;++ type?: 'custom' | null;+}++/**+ * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.+ *+ * This defines the shape of the `input` that your tool accepts and that the model+ * will produce.+ */+export interface InputSchema {+ type: 'object';++ properties?: unknown | null;++ [k: string]: unknown;+}++export interface CacheControlEphemeral {+ type: 'ephemeral';+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5bed0be35..3f8afee92 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -54,8 +54,8 @@ importers:examples/anthropic:dependencies:'@anthropic-ai/sdk':- specifier: ^0.18.0- version: 0.18.0([email protected])+ specifier: ^0.52.0+ version: 0.52.0'@composio/anthropic':specifier: workspace:*version: link:../../packages/providers/anthropic@@ -355,8 +355,8 @@ importers:packages/providers/anthropic:dependencies:'@anthropic-ai/sdk':- specifier: ^0.18.0- version: 0.18.0([email protected])+ specifier: ^0.52.0+ version: 0.52.0devDependencies:'@composio/core':specifier: workspace:*@@ -516,8 +516,9 @@ packages:peerDependencies:zod: ^3.23.8- '@anthropic-ai/[email protected]':- resolution: {integrity: sha512-3XsWEn/4nPGRd4AdSguugbSDFy6Z2AWTNOeI3iK+aV22+w23+vY9CEb3Hiy0kvKIQuxSmZz/+5WKC8nPWy8gVg==}+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==}+ hasBin: true'@apidevtools/[email protected]':resolution: {integrity: sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ==}@@ -2356,9 +2357,6 @@ packages:resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}- resolution: {integrity: sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==}-resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -2440,9 +2438,6 @@ packages:resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==}- resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==}-resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}engines: {node: '>= 16'}@@ -2537,9 +2532,6 @@ packages:resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}engines: {node: '>= 8'}- resolution: {integrity: sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==}-resolution: {integrity: sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==}@@ -2585,9 +2577,6 @@ packages:resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}- resolution: {integrity: sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==}-resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}engines: {node: '>=8'}@@ -3116,9 +3105,6 @@ packages:resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}engines: {node: '>= 0.10'}- resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==}-resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}engines: {node: '>= 0.4'}@@ -3305,9 +3291,6 @@ packages:resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==}-resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}engines: {node: '>= 0.8'}@@ -4252,10 +4235,6 @@ packages:jsdom:optional: true- resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}- engines: {node: '>= 8'}-resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}engines: {node: '>= 14'}@@ -4392,19 +4371,7 @@ snapshots:zod: 3.24.4zod-to-json-schema: 3.24.5([email protected])- '@anthropic-ai/[email protected]([email protected])':- dependencies:- '@types/node': 18.19.100- '@types/node-fetch': 2.6.12- abort-controller: 3.0.0- agentkeepalive: 4.6.0- digest-fetch: 1.3.0- form-data-encoder: 1.7.2- formdata-node: 4.4.1- node-fetch: 2.7.0([email protected])- web-streams-polyfill: 3.3.3- transitivePeerDependencies:- - encoding+ '@anthropic-ai/[email protected]': {}'@apidevtools/[email protected]':dependencies:@@ -6869,8 +6836,6 @@ snapshots:- [email protected]: {}-@@ -6959,8 +6924,6 @@ snapshots:- [email protected]: {}-@@ -7057,8 +7020,6 @@ snapshots:shebang-command: 2.0.0which: 2.0.2- [email protected]: {}-@@ -7083,11 +7044,6 @@ snapshots:- dependencies:- base-64: 0.1.0- md5: 2.3.0-dependencies:path-type: 4.0.0@@ -7671,8 +7627,6 @@ snapshots:- [email protected]: {}-dependencies:hasown: 2.0.2@@ -7859,12 +7813,6 @@ snapshots:- dependencies:- charenc: 0.0.2- crypt: 0.0.2- is-buffer: 1.1.6-@@ -8775,8 +8723,6 @@ snapshots:- tsx- yaml- [email protected]: {}-