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

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 219 lines 6.58 KB
Raw
1 /**
2 * Langchain Provider
3 *
4 * Author: Musthaq Ahamad <musthaq@composio.dev>
5 * Reference: https://github.com/ComposioHQ/composio/blob/master/js/src/frameworks/langchain.ts
6 *
7 * This provider provides a set of tools for interacting with Langchain.
8 *
9 * @packageDocumentation
10 * @module providers/langchain
11 */
12 import {
13 BaseAgenticProvider,
14 dereferenceJsonSchema,
15 jsonSchemaToZodSchema,
16 Tool,
17 ExecuteToolFn,
18 McpUrlResponse,
19 McpServerGetResponse,
20 normalizeToolArguments,
21 } from '@composio/core';
22 import { DynamicStructuredTool } from '@langchain/core/tools';
23
24 export type LangChainToolCollection = Array<DynamicStructuredTool>;
25 export class LangchainProvider extends BaseAgenticProvider<
26 LangChainToolCollection,
27 DynamicStructuredTool,
28 McpServerGetResponse
29 > {
30 readonly name = 'langchain';
31
32 /**
33 * Creates a new instance of the LangchainProvider.
34 *
35 * This provider enables integration with the Langchain framework,
36 * allowing Composio tools to be used with Langchain agents and chains.
37 *
38 * @example
39 * ```typescript
40 * // Initialize the Langchain provider
41 * const provider = new LangchainProvider();
42 *
43 * // Use with Composio
44 * const composio = new Composio({
45 * apiKey: 'your-api-key',
46 * provider: new LangchainProvider()
47 * });
48 *
49 * // Use the provider to wrap tools for Langchain
50 * const langchainTools = provider.wrapTools(composioTools, composio.tools.execute);
51 * ```
52 */
53 constructor() {
54 super();
55 }
56
57 /**
58 * Transform MCP URL response into Anthropic-specific format.
59 * By default, Anthropic uses the standard format (same as default),
60 * but this method is here to show providers can customize if needed.
61 *
62 * @param data - The MCP URL response data
63 * @returns Standard MCP server response format
64 */
65 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
66 // Anthropic uses the standard format
67 return data.map(item => ({
68 url: new URL(item.url),
69 name: item.name,
70 })) as McpServerGetResponse;
71 }
72
73 /**
74 * Wraps a Composio tool in the Langchain DynamicStructuredTool format.
75 *
76 * This method transforms a Composio tool definition into a Langchain
77 * DynamicStructuredTool that can be used with Langchain agents and chains.
78 *
79 * @param tool - The Composio tool to wrap
80 * @param executeTool - Function to execute the tool
81 * @returns The wrapped tool as a Langchain DynamicStructuredTool
82 *
83 * @example
84 * ```typescript
85 * // Wrap a single tool for use with Langchain
86 * const composioTool = {
87 * slug: 'SEARCH_TOOL',
88 * description: 'Search for information',
89 * toolkit: { name: 'search_toolkit' },
90 * inputParameters: {
91 * type: 'object',
92 * properties: {
93 * query: { type: 'string' }
94 * },
95 * required: ['query']
96 * }
97 * };
98 *
99 * // Create a Langchain tool using the provider
100 * const langchainTool = provider.wrapTool(
101 * composioTool,
102 * composio.tools.execute
103 * );
104 *
105 * // Use with Langchain
106 * import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
107 * import { ChatOpenAI } from '@langchain/openai';
108 *
109 * const model = new ChatOpenAI({ temperature: 0 });
110 * const agent = await createOpenAIFunctionsAgent({
111 * llm: model,
112 * tools: [langchainTool]
113 * });
114 *
115 * const executor = new AgentExecutor({
116 * agent,
117 * tools: [langchainTool]
118 * });
119 *
120 * const result = await executor.invoke({
121 * input: "Search for information about Composio"
122 * });
123 * ```
124 */
125 wrapTool(tool: Tool, executeTool: ExecuteToolFn): DynamicStructuredTool {
126 const toolName = tool.slug;
127 const description = tool.description;
128 const appName = tool.toolkit?.name?.toLowerCase();
129 if (!appName) {
130 throw new Error('App name is not defined');
131 }
132 const func = async (...args: unknown[]): Promise<unknown> => {
133 // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
134 const result = await executeTool(toolName, normalizeToolArguments(args[0], toolName));
135 return JSON.stringify(result);
136 };
137 if (!tool.inputParameters) {
138 throw new Error('Tool input parameters are not defined');
139 }
140 const parameters = jsonSchemaToZodSchema(
141 dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' })
142 );
143
144 // See https://github.com/langchain-ai/langchainjs/issues/8468 and pnpm-workspace.yaml.
145 // @ts-expect-error: error TS2589: Type instantiation is excessively deep and possibly infinite.
146 return new DynamicStructuredTool({
147 name: toolName,
148 description: description || '',
149 schema: parameters,
150 func: func,
151 });
152 }
153
154 /**
155 * Wraps a list of Composio tools in the Langchain DynamicStructuredTool format.
156 *
157 * This method transforms multiple Composio tool definitions into Langchain
158 * DynamicStructuredTools that can be used with Langchain agents and chains.
159 *
160 * @param tools - Array of Composio tools to wrap
161 * @param executeTool - Function to execute the tools
162 * @returns Array of wrapped tools as Langchain DynamicStructuredTools
163 *
164 * @example
165 * ```typescript
166 * // Wrap multiple tools for use with Langchain
167 * const composioTools = [
168 * {
169 * slug: 'SEARCH_TOOL',
170 * description: 'Search for information',
171 * toolkit: { name: 'search_toolkit' },
172 * inputParameters: {
173 * type: 'object',
174 * properties: {
175 * query: { type: 'string' }
176 * },
177 * required: ['query']
178 * }
179 * },
180 * {
181 * slug: 'WEATHER_TOOL',
182 * description: 'Get weather information',
183 * toolkit: { name: 'weather_toolkit' },
184 * inputParameters: {
185 * type: 'object',
186 * properties: {
187 * location: { type: 'string' }
188 * },
189 * required: ['location']
190 * }
191 * }
192 * ];
193 *
194 * // Create Langchain tools using the provider
195 * const langchainTools = provider.wrapTools(
196 * composioTools,
197 * composio.tools.execute
198 * );
199 *
200 * // Use with Langchain
201 * import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
202 * import { ChatOpenAI } from '@langchain/openai';
203 *
204 * const model = new ChatOpenAI({ temperature: 0 });
205 * const agent = await createOpenAIFunctionsAgent({
206 * llm: model,
207 * tools: langchainTools
208 * });
209 *
210 * const executor = new AgentExecutor({
211 * agent,
212 * tools: langchainTools
213 * });
214 * ```
215 */
216 wrapTools(tools: Tool[], executeTool: ExecuteToolFn): LangChainToolCollection {
217 return tools.map(tool => this.wrapTool(tool, executeTool));
218 }
219 }