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

next
ts 296 lines 9.05 KB
Raw
1 /**
2 * Google GenAI Provider
3 *
4 * This provider provides a set of tools for interacting with Google's GenAI API.
5 * It supports both the Gemini Developer API and Vertex AI implementations.
6 *
7 * @packageDocumentation
8 * @module providers/google
9 */
10 import {
11 BaseNonAgenticProvider,
12 Tool,
13 ToolExecuteParams,
14 ExecuteToolModifiers,
15 ExecuteToolFnOptions,
16 ToolCallExecutionTarget,
17 ToolCallSession,
18 McpUrlResponse,
19 McpServerGetResponse,
20 normalizeToolArguments,
21 deduplicateJsonSchemaRequiredArrays,
22 dereferenceJsonSchema,
23 ensureObjectTypeOnProperties,
24 } from '@composio/core';
25 import { FunctionDeclaration } from '@google/genai';
26
27 /**
28 * Interface for Google GenAI function declaration
29 * Based on the FunctionDeclaration type from @google/genai
30 */
31 export type GoogleTool = FunctionDeclaration;
32
33 /**
34 * Interface for Google GenAI function call
35 * Based on the FunctionCall type from @google/genai
36 */
37 export interface GoogleGenAIFunctionCall {
38 name: string;
39 args: Record<string, unknown>;
40 }
41
42 /**
43 * Type for a collection of Google GenAI function declarations
44 */
45 export type GoogleGenAIToolCollection = GoogleTool[];
46
47 /**
48 * Google GenAI Provider for Composio SDK
49 * Implements the BaseNonAgenticProvider to wrap Composio tools for use with Google's GenAI API
50 */
51 export class GoogleProvider extends BaseNonAgenticProvider<
52 GoogleGenAIToolCollection,
53 GoogleTool,
54 McpServerGetResponse
55 > {
56 readonly name = 'google';
57
58 /**
59 * Creates a new instance of the GoogleProvider.
60 *
61 * This provider enables integration with Google's GenAI API,
62 * supporting both the Gemini Developer API and Vertex AI implementations.
63 *
64 * @example
65 * ```typescript
66 * // Initialize the Google provider
67 * const provider = new GoogleProvider();
68 *
69 * // Use with Composio
70 * const composio = new Composio({
71 * apiKey: 'your-api-key',
72 * provider: new GoogleProvider()
73 * });
74 *
75 * // Use the provider to wrap tools for Google GenAI
76 * const googleTools = provider.wrapTools(composioTools);
77 * ```
78 */
79 constructor() {
80 super();
81 }
82
83 /**
84 * Transform MCP URL response into Anthropic-specific format.
85 * By default, Anthropic uses the standard format (same as default),
86 * but this method is here to show providers can customize if needed.
87 *
88 * @param data - The MCP URL response data
89 * @returns Standard MCP server response format
90 */
91 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
92 // Anthropic uses the standard format
93 return data.map(item => ({
94 url: new URL(item.url),
95 name: item.name,
96 })) as McpServerGetResponse;
97 }
98
99 /**
100 * Wraps a Composio tool in the Google GenAI function declaration format.
101 *
102 * This method transforms a Composio tool definition into the format
103 * expected by Google's GenAI API for function calling.
104 *
105 * @param tool - The Composio tool to wrap
106 * @returns The wrapped tool in Google GenAI format
107 *
108 * @example
109 * ```typescript
110 * // Wrap a single tool for use with Google GenAI
111 * const composioTool = {
112 * slug: 'SEARCH_TOOL',
113 * description: 'Search for information',
114 * inputParameters: {
115 * type: 'object',
116 * properties: {
117 * query: { type: 'string' }
118 * },
119 * required: ['query']
120 * }
121 * };
122 *
123 * const googleTool = provider.wrapTool(composioTool);
124 * // Use with Google GenAI SDK
125 * const genAI = new GoogleGenerativeAI('YOUR_API_KEY');
126 * const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
127 *
128 * const result = await model.generateContent({
129 * contents: [{ role: 'user', parts: [{ text: 'Search for Composio' }] }],
130 * tools: [googleTool]
131 * });
132 * ```
133 */
134 wrapTool(tool: Tool): GoogleTool {
135 const inputParameters = ensureObjectTypeOnProperties(
136 deduplicateJsonSchemaRequiredArrays(
137 dereferenceJsonSchema(tool.inputParameters ?? { type: 'object', properties: {} }, {
138 onUnresolved: 'sentinel',
139 })
140 )
141 );
142
143 return {
144 name: tool.slug,
145 description: tool.description || '',
146 // Composio schemas are JSON Schema and carry keywords such as `examples`
147 // and `const`. The OpenAPI-subset `parameters` field rejects those with a
148 // 400, so send them through `parametersJsonSchema` instead.
149 parametersJsonSchema: {
150 type: 'object',
151 description: tool.description || '',
152 properties: inputParameters?.properties || {},
153 required: inputParameters?.required || [],
154 },
155 };
156 }
157
158 /**
159 * Wraps a list of Composio tools in the Google GenAI function declaration format.
160 *
161 * This method transforms multiple Composio tool definitions into the format
162 * expected by Google's GenAI API for function calling.
163 *
164 * @param tools - Array of Composio tools to wrap
165 * @returns Array of wrapped tools in Google GenAI format
166 *
167 * @example
168 * ```typescript
169 * // Wrap multiple tools for use with Google GenAI
170 * const composioTools = [
171 * {
172 * slug: 'SEARCH_TOOL',
173 * description: 'Search for information',
174 * inputParameters: {
175 * type: 'object',
176 * properties: {
177 * query: { type: 'string' }
178 * },
179 * required: ['query']
180 * }
181 * },
182 * {
183 * slug: 'WEATHER_TOOL',
184 * description: 'Get weather information',
185 * inputParameters: {
186 * type: 'object',
187 * properties: {
188 * location: { type: 'string' }
189 * },
190 * required: ['location']
191 * }
192 * }
193 * ];
194 *
195 * const googleTools = provider.wrapTools(composioTools);
196 *
197 * // Use with Google GenAI SDK
198 * const genAI = new GoogleGenerativeAI('YOUR_API_KEY');
199 * const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
200 *
201 * const result = await model.generateContent({
202 * contents: [{ role: 'user', parts: [{ text: 'How is the weather in New York?' }] }],
203 * tools: googleTools
204 * });
205 * ```
206 */
207 wrapTools(tools: Tool[]): GoogleGenAIToolCollection {
208 return tools.map(tool => this.wrapTool(tool));
209 }
210
211 /**
212 * Executes a tool call from Google GenAI.
213 *
214 * This method processes a function call from Google's GenAI API,
215 * executes the corresponding Composio tool, and returns the result.
216 *
217 * @param executionTarget - A user ID for direct tools or the session that produced session tools
218 * @param tool - The Google GenAI function call to execute
219 * @param options - Optional execution options like connected account ID (user ID targets only)
220 * @param modifiers - Optional execution modifiers for tool behavior (user ID targets only)
221 * @returns The result of the tool execution as a JSON string
222 *
223 * @example
224 * ```typescript
225 * // Execute a tool call from Google GenAI
226 * const functionCall = {
227 * name: 'SEARCH_TOOL',
228 * args: {
229 * query: 'composio documentation'
230 * }
231 * };
232 *
233 * const result = await provider.executeToolCall(
234 * 'user123',
235 * functionCall,
236 * { connectedAccountId: 'conn_xyz456' }
237 * );
238 *
239 * // Parse the result and use it in your application
240 * const searchResults = JSON.parse(result);
241 * console.log(searchResults);
242 *
243 * // You can also use the result to continue the conversation
244 * const genAI = new GoogleGenerativeAI('YOUR_API_KEY');
245 * const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
246 *
247 * await model.generateContent({
248 * contents: [
249 * { role: 'user', parts: [{ text: 'Search for Composio' }] },
250 * { role: 'model', parts: [{ functionResponse: { name: 'SEARCH_TOOL', response: result } }] }
251 * ]
252 * });
253 *
254 * // For tools from session.tools(), pass the session instead of a user ID
255 * const sessionResult = await provider.executeToolCall(session, functionCall);
256 * ```
257 */
258 async executeToolCall(session: ToolCallSession, tool: GoogleGenAIFunctionCall): Promise<string>;
259 async executeToolCall(
260 userId: string,
261 tool: GoogleGenAIFunctionCall,
262 options?: ExecuteToolFnOptions,
263 modifiers?: ExecuteToolModifiers
264 ): Promise<string>;
265 async executeToolCall(
266 executionTarget: ToolCallExecutionTarget,
267 tool: GoogleGenAIFunctionCall,
268 options?: ExecuteToolFnOptions,
269 modifiers?: ExecuteToolModifiers
270 ): Promise<string> {
271 // Models occasionally emit tool args as a JSON string rather than an object (issue #2406).
272 const toolArguments = normalizeToolArguments(tool.args, tool.name);
273 if (typeof executionTarget !== 'string') {
274 const result = await this.executeToolForTarget(
275 executionTarget,
276 tool.name,
277 toolArguments,
278 options,
279 modifiers
280 );
281 return JSON.stringify(result);
282 }
283
284 // Keep direct execution on `executeTool`, which every supported @composio/core provides.
285 const payload: ToolExecuteParams = {
286 arguments: toolArguments,
287 connectedAccountId: options?.connectedAccountId,
288 customAuthParams: options?.customAuthParams,
289 customConnectionData: options?.customConnectionData,
290 userId: executionTarget,
291 };
292
293 const result = await this.executeTool(tool.name, payload, modifiers);
294 return JSON.stringify(result);
295 }
296 }