@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 93 lines 2.59 KB
Raw
1 /**
2 * OpenAI Chat Completions with Composio Tool Example
3 *
4 * This example demonstrates how to use the Composio OpenAIProvider with OpenAI chat completions API.
5 * It uses the HACKERNEWS_GET_USER tool to fetch information about a HackerNews user.
6 */
7 import { Composio } from '@composio/core';
8 import { OpenAI } from 'openai';
9 import dotenv from 'dotenv';
10
11 dotenv.config();
12
13 const openai = new OpenAI({
14 apiKey: process.env.OPENAI_API_KEY,
15 });
16
17 const composio = new Composio({
18 apiKey: process.env.COMPOSIO_API_KEY,
19 });
20
21 /**
22 * Main function to demonstrate OpenAI Chat Completions with Composio tool
23 */
24 async function main() {
25 try {
26 console.log('🔄 Setting up Composio and fetching tool...');
27
28 const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
29
30 const query = "Find information about the HackerNews user 'pg'";
31
32 console.log(`🔄 Sending query to OpenAI: "${query}"`);
33
34 const response = await openai.chat.completions.create({
35 model: 'gpt-4o',
36 messages: [
37 {
38 role: 'system',
39 content: 'You are a helpful assistant that can use tools to answer questions.',
40 },
41 { role: 'user', content: query },
42 ],
43 tools: tools,
44 tool_choice: 'auto',
45 });
46
47 if (
48 response.choices[0].message.tool_calls &&
49 response.choices[0].message.tool_calls[0].type === 'function'
50 ) {
51 console.log(
52 '🔧 Assistant is using tool:',
53 response.choices[0].message.tool_calls[0].function.name
54 );
55
56 const toolResult = await composio.provider.executeToolCall(
57 'default',
58 response.choices[0].message.tool_calls[0],
59 {
60 connectedAccountId: '', // Optional connected account ID
61 }
62 );
63
64 console.log('✅ Tool execution result:', JSON.parse(toolResult));
65
66 const finalResponse = await openai.chat.completions.create({
67 model: 'gpt-4o',
68 messages: [
69 {
70 role: 'system',
71 content: 'You are a helpful assistant that can use tools to answer questions.',
72 },
73 { role: 'user', content: query },
74 response.choices[0].message,
75 {
76 role: 'tool',
77 tool_call_id: response.choices[0].message.tool_calls[0].id,
78 content: toolResult,
79 },
80 ],
81 });
82
83 console.log('🤖 Final assistant response:', finalResponse.choices[0].message.content);
84 } else {
85 console.log('🤖 Assistant response:', response.choices[0].message.content);
86 }
87 } catch (error) {
88 console.error('❌ Error:', error);
89 process.exitCode = 1;
90 }
91 }
92
93 main();