@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 108 lines 3.04 KB
Raw
1 import { Composio, normalizeToolArguments } from '@composio/core';
2 import { OpenAIProvider } from '@composio/openai';
3 import OpenAI from 'openai';
4
5 const MODEL = 'gpt-5-mini';
6 const USER_ID = 'example-user';
7 const MAX_STEPS = 10;
8
9 export interface ToolRouterHackerNewsAgentEnvironment {
10 COMPOSIO_API_KEY?: string;
11 OPENAI_API_KEY?: string;
12 }
13
14 function requireKey(
15 env: ToolRouterHackerNewsAgentEnvironment,
16 name: keyof ToolRouterHackerNewsAgentEnvironment
17 ): string {
18 const value = env[name];
19 if (!value) {
20 throw new Error(`${name} is required to run the HackerNews agent.`);
21 }
22
23 return value;
24 }
25
26 export async function runToolRouterHackerNewsAgent(
27 env: ToolRouterHackerNewsAgentEnvironment
28 ): Promise<string> {
29 const composioApiKey = requireKey(env, 'COMPOSIO_API_KEY');
30 const openaiApiKey = requireKey(env, 'OPENAI_API_KEY');
31 const openai = new OpenAI({
32 apiKey: openaiApiKey,
33 maxRetries: 1,
34 timeout: 60_000,
35 });
36 const composio = new Composio({
37 apiKey: composioApiKey,
38 provider: new OpenAIProvider(),
39 });
40 const session = await composio.sessions.create(USER_ID, {
41 toolkits: ['hackernews'],
42 });
43 const tools = await session.tools();
44 const messages: OpenAI.ChatCompletionMessageParam[] = [
45 {
46 role: 'system',
47 content:
48 'You are a helpful assistant. Use the available Composio tools to search for and read HackerNews data before answering.',
49 },
50 {
51 role: 'user',
52 content: 'What are the current top 3 HackerNews stories? Give me their titles.',
53 },
54 ];
55 let hasSuccessfulToolExecution = false;
56
57 for (let step = 0; step < MAX_STEPS; step += 1) {
58 let toolChoice: 'auto' | 'required' = 'auto';
59 if (!hasSuccessfulToolExecution) {
60 toolChoice = 'required';
61 }
62
63 const response = await openai.chat.completions.create({
64 model: MODEL,
65 messages,
66 tools,
67 tool_choice: toolChoice,
68 });
69 const message = response.choices[0]?.message;
70 if (!message) {
71 throw new Error('OpenAI returned no assistant message.');
72 }
73
74 messages.push(message);
75 if (!message.tool_calls?.length) {
76 if (!hasSuccessfulToolExecution) {
77 throw new Error('Agent returned without successfully executing a Composio tool.');
78 }
79
80 const text = message.content?.trim();
81 if (!text) {
82 throw new Error('Agent returned empty output — expected a non-empty response.');
83 }
84 return text;
85 }
86
87 for (const toolCall of message.tool_calls) {
88 if (toolCall.type !== 'function') {
89 throw new Error(`Unsupported OpenAI tool call type: ${toolCall.type}`);
90 }
91
92 const result = await session.execute(
93 toolCall.function.name,
94 normalizeToolArguments(toolCall.function.arguments, toolCall.function.name)
95 );
96 if (!result.error) {
97 hasSuccessfulToolExecution = true;
98 }
99 messages.push({
100 role: 'tool',
101 tool_call_id: toolCall.id,
102 content: JSON.stringify(result),
103 });
104 }
105 }
106
107 throw new Error(`Agent exceeded the ${MAX_STEPS}-step tool-call budget.`);
108 }