|
| 1 | +import OpenAI from "openai"; |
| 2 | +import type { ToolInput, ToolMetadata } from "#/agent/tools/types.ts"; |
| 3 | +import type { LlmClient, LlmEvent, Message, MessagePart } from "#/agent/types.ts"; |
| 4 | +import type { LlmAdapter } from "./types.ts"; |
| 5 | + |
| 6 | +export const openaiAdapter: LlmAdapter = { |
| 7 | + matchesApiKey: (apiKey) => apiKey.startsWith("sk-") && !apiKey.startsWith("sk-ant-"), |
| 8 | + |
| 9 | + fromApiKey(apiKey, systemPrompt, model) { |
| 10 | + return new OpenAiLlmClient(new OpenAI({ apiKey }), model ?? "gpt-5-mini", systemPrompt); |
| 11 | + }, |
| 12 | + |
| 13 | + tryFromEnv(env, systemPrompt) { |
| 14 | + const apiKey = env.OPENAI_API_KEY; |
| 15 | + if (!apiKey) return null; |
| 16 | + |
| 17 | + // A custom base URL means a proxy or gateway, whose keys use their own format. |
| 18 | + if (!env.OPENAI_BASE_URL && !this.matchesApiKey(apiKey)) { |
| 19 | + return null; |
| 20 | + } |
| 21 | + |
| 22 | + return this.fromApiKey(apiKey, systemPrompt, env.MODEL); |
| 23 | + }, |
| 24 | +}; |
| 25 | + |
| 26 | +export class OpenAiLlmClient implements LlmClient { |
| 27 | + readonly provider = "openai"; |
| 28 | + |
| 29 | + constructor( |
| 30 | + private readonly sdk: OpenAI, |
| 31 | + readonly model: string, |
| 32 | + private readonly systemPrompt?: string, |
| 33 | + ) {} |
| 34 | + |
| 35 | + async *send( |
| 36 | + messages: Message[], |
| 37 | + tools?: ToolMetadata[], |
| 38 | + signal?: AbortSignal, |
| 39 | + ): AsyncGenerator<LlmEvent> { |
| 40 | + const stream = await this.sdk.responses.create( |
| 41 | + { |
| 42 | + model: this.model, |
| 43 | + stream: true, |
| 44 | + input: messages.flatMap(toSdkInputItems), |
| 45 | + ...(tools && tools.length > 0 ? { tools: tools.map(toSdkTool) } : {}), |
| 46 | + ...(this.systemPrompt ? { instructions: this.systemPrompt } : {}), |
| 47 | + }, |
| 48 | + { signal }, |
| 49 | + ); |
| 50 | + |
| 51 | + const toolCalls = new Map<number, { callId: string; name: string; args: string }>(); |
| 52 | + let response: MessagePart[] | undefined; |
| 53 | + |
| 54 | + for await (const event of stream) { |
| 55 | + switch (event.type) { |
| 56 | + case "response.output_text.delta": |
| 57 | + yield { |
| 58 | + type: "text_delta", |
| 59 | + text: event.delta, |
| 60 | + }; |
| 61 | + break; |
| 62 | + |
| 63 | + case "response.output_item.added": |
| 64 | + if (event.item.type === "function_call") { |
| 65 | + toolCalls.set(event.output_index, { |
| 66 | + callId: event.item.call_id, |
| 67 | + name: event.item.name, |
| 68 | + args: "", |
| 69 | + }); |
| 70 | + } |
| 71 | + break; |
| 72 | + |
| 73 | + case "response.function_call_arguments.delta": { |
| 74 | + const call = toolCalls.get(event.output_index); |
| 75 | + if (call) call.args += event.delta; |
| 76 | + break; |
| 77 | + } |
| 78 | + |
| 79 | + case "response.output_item.done": { |
| 80 | + const call = toolCalls.get(event.output_index); |
| 81 | + if (call) { |
| 82 | + const args = event.item.type === "function_call" ? event.item.arguments : call.args; |
| 83 | + yield { |
| 84 | + type: "tool_call", |
| 85 | + id: call.callId, |
| 86 | + name: call.name, |
| 87 | + input: args ? JSON.parse(args) : {}, |
| 88 | + }; |
| 89 | + toolCalls.delete(event.output_index); |
| 90 | + } |
| 91 | + break; |
| 92 | + } |
| 93 | + |
| 94 | + case "response.completed": |
| 95 | + response = fromSdkOutput(event.response.output); |
| 96 | + break; |
| 97 | + |
| 98 | + case "response.failed": |
| 99 | + throw new Error(event.response.error?.message ?? "OpenAI response failed"); |
| 100 | + |
| 101 | + case "response.incomplete": |
| 102 | + throw new Error( |
| 103 | + event.response.incomplete_details?.reason ?? "OpenAI response was incomplete", |
| 104 | + ); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + if (response) { |
| 109 | + yield { |
| 110 | + type: "complete", |
| 111 | + response, |
| 112 | + }; |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +function toSdkInputItems(message: Message): OpenAI.Responses.ResponseInputItem[] { |
| 118 | + return message.content.map((part): OpenAI.Responses.ResponseInputItem => { |
| 119 | + if (part.type === "text") { |
| 120 | + return { |
| 121 | + role: message.role, |
| 122 | + content: part.text, |
| 123 | + }; |
| 124 | + } |
| 125 | + if (part.type === "tool_call") { |
| 126 | + return { |
| 127 | + type: "function_call", |
| 128 | + call_id: part.id, |
| 129 | + name: part.name, |
| 130 | + arguments: JSON.stringify(part.input), |
| 131 | + }; |
| 132 | + } |
| 133 | + return { |
| 134 | + type: "function_call_output", |
| 135 | + call_id: part.toolCallId, |
| 136 | + output: part.content, |
| 137 | + }; |
| 138 | + }); |
| 139 | +} |
| 140 | + |
| 141 | +function toSdkTool(tool: ToolMetadata): OpenAI.Responses.FunctionTool { |
| 142 | + return { |
| 143 | + type: "function", |
| 144 | + name: tool.name, |
| 145 | + description: tool.description, |
| 146 | + parameters: tool.inputSchema, |
| 147 | + strict: false, |
| 148 | + }; |
| 149 | +} |
| 150 | + |
| 151 | +function fromSdkOutput(output: OpenAI.Responses.ResponseOutputItem[]): MessagePart[] { |
| 152 | + return output.flatMap((item): MessagePart[] => { |
| 153 | + if (item.type === "message") { |
| 154 | + return item.content.flatMap((part): MessagePart[] => |
| 155 | + part.type === "output_text" ? [{ type: "text", text: part.text }] : [], |
| 156 | + ); |
| 157 | + } |
| 158 | + if (item.type === "function_call") { |
| 159 | + return [ |
| 160 | + { |
| 161 | + type: "tool_call", |
| 162 | + id: item.call_id, |
| 163 | + name: item.name, |
| 164 | + input: (item.arguments ? JSON.parse(item.arguments) : {}) as ToolInput, |
| 165 | + }, |
| 166 | + ]; |
| 167 | + } |
| 168 | + return []; |
| 169 | + }); |
| 170 | +} |
0 commit comments