@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 65 lines 1.91 KB
Raw
1 /**
2 * OpenAI Chat Completions adapter.
3 */
4
5 import OpenAI from 'openai';
6 import { z } from 'zod';
7 import { SHELL_TOOL, type ModelAdapter, type ModelTurn } from './agent';
8
9 const ShellInput = z.object({ command: z.string() });
10
11 export const openaiAdapter = (options: {
12 baseURL: string;
13 apiKey: string;
14 model: string;
15 system: string;
16 prompt: string;
17 maxTokens: number;
18 }): ModelAdapter => {
19 const client = new OpenAI({
20 baseURL: `${options.baseURL}/v1`,
21 apiKey: options.apiKey,
22 maxRetries: 0,
23 });
24 const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
25 { role: 'system', content: options.system },
26 { role: 'user', content: options.prompt },
27 ];
28
29 return {
30 provider: 'openai',
31 model: options.model,
32 next: async (): Promise<ModelTurn> => {
33 const response = await client.chat.completions.create({
34 model: options.model,
35 max_completion_tokens: options.maxTokens,
36 tools: [{ type: 'function', function: SHELL_TOOL }],
37 messages,
38 });
39 const choice = response.choices[0];
40 if (!choice) return { text: '', calls: [], stopped: 'no-choice' };
41 messages.push(choice.message);
42
43 const calls = (choice.message.tool_calls ?? [])
44 .filter(call => call.type === 'function')
45 .map(call => ({
46 id: call.id,
47 command: ShellInput.parse(JSON.parse(call.function.arguments)).command,
48 }));
49 const continues = choice.finish_reason === 'tool_calls' || choice.finish_reason === 'stop';
50 return {
51 text: choice.message.content ?? '',
52 calls,
53 stopped: continues ? undefined : choice.finish_reason,
54 };
55 },
56 record: results => {
57 for (const { call, payload } of results) {
58 messages.push({ role: 'tool', tool_call_id: call.id, content: payload });
59 }
60 },
61 say: message => {
62 messages.push({ role: 'user', content: message });
63 },
64 };
65 };