Elffuss BraidHub

kikocis/continue public

81ce8cce6ac5 · 4.9 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { OpenAI } from "openai/index";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParams,
7 ChatCompletionCreateParamsNonStreaming,
8 ChatCompletionCreateParamsStreaming,
9 Completion,
10 CompletionCreateParamsNonStreaming,
11 CompletionCreateParamsStreaming,
12 Model,
13} from "openai/resources/index";
14import { z } from "zod";
15import { OpenAIConfigSchema } from "../types.js";
16import { customFetch } from "../util.js";
17import {
18 BaseLlmApi,
19 CreateRerankResponse,
20 FimCreateParamsStreaming,
21 RerankCreateParams,
22} from "./base.js";
23
24export class OpenAIApi implements BaseLlmApi {
25 openai: OpenAI;
26 apiBase: string = "https://api.openai.com/v1/";
27
28 constructor(protected config: z.infer<typeof OpenAIConfigSchema>) {
29 this.apiBase = config.apiBase ?? this.apiBase;
30 this.openai = new OpenAI({
31 apiKey: config.apiKey,
32 baseURL: this.apiBase,
33 fetch: customFetch(config.requestOptions),
34 });
35 }
36 modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
37 // o-series models - only apply for official OpenAI API
38 const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
39 if (isOfficialOpenAIAPI) {
40 if (body.model.startsWith("o")) {
41 // a) use max_completion_tokens instead of max_tokens
42 body.max_completion_tokens = body.max_tokens;
43 body.max_tokens = undefined;
44
45 // b) use "developer" message role rather than "system"
46 body.messages = body.messages.map((message) => {
47 if (message.role === "system") {
48 return { ...message, role: "developer" } as any;
49 }
50 return message;
51 });
52 }
53 if (body.tools?.length && !body.model.startsWith("o3")) {
54 body.parallel_tool_calls = false;
55 }
56 }
57 return body;
58 }
59
60 async chatCompletionNonStream(
61 body: ChatCompletionCreateParamsNonStreaming,
62 signal: AbortSignal,
63 ): Promise<ChatCompletion> {
64 const response = await this.openai.chat.completions.create(
65 this.modifyChatBody(body),
66 {
67 signal,
68 },
69 );
70 return response;
71 }
72
73 async *chatCompletionStream(
74 body: ChatCompletionCreateParamsStreaming,
75 signal: AbortSignal,
76 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
77 const response = await this.openai.chat.completions.create(
78 this.modifyChatBody(body),
79 {
80 signal,
81 },
82 );
83 for await (const result of response) {
84 yield result;
85 }
86 }
87 async completionNonStream(
88 body: CompletionCreateParamsNonStreaming,
89 signal: AbortSignal,
90 ): Promise<Completion> {
91 const response = await this.openai.completions.create(body, { signal });
92 return response;
93 }
94 async *completionStream(
95 body: CompletionCreateParamsStreaming,
96 signal: AbortSignal,
97 ): AsyncGenerator<Completion, any, unknown> {
98 const response = await this.openai.completions.create(body, { signal });
99 for await (const result of response) {
100 yield result;
101 }
102 }
103 async *fimStream(
104 body: FimCreateParamsStreaming,
105 signal: AbortSignal,
106 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
107 const endpoint = new URL("fim/completions", this.apiBase);
108 const resp = await customFetch(this.config.requestOptions)(endpoint, {
109 method: "POST",
110 body: JSON.stringify({
111 model: body.model,
112 prompt: body.prompt,
113 suffix: body.suffix,
114 max_tokens: body.max_tokens,
115 max_completion_tokens: (body as any).max_completion_tokens,
116 temperature: body.temperature,
117 top_p: body.top_p,
118 frequency_penalty: body.frequency_penalty,
119 presence_penalty: body.presence_penalty,
120 stop: body.stop,
121 stream: true,
122 }),
123 headers: {
124 "Content-Type": "application/json",
125 Accept: "application/json",
126 "x-api-key": this.config.apiKey ?? "",
127 Authorization: `Bearer ${this.config.apiKey}`,
128 },
129 signal,
130 });
131 for await (const chunk of streamSse(resp as any)) {
132 if (chunk.choices && chunk.choices.length > 0) {
133 yield chunk;
134 }
135 }
136 }
137
138 async embed(
139 body: OpenAI.Embeddings.EmbeddingCreateParams,
140 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
141 const response = await this.openai.embeddings.create(body);
142 return response;
143 }
144
145 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
146 const endpoint = new URL("rerank", this.apiBase);
147 const response = await customFetch(this.config.requestOptions)(endpoint, {
148 method: "POST",
149 body: JSON.stringify(body),
150 headers: {
151 "Content-Type": "application/json",
152 Accept: "application/json",
153 "x-api-key": this.config.apiKey ?? "",
154 Authorization: `Bearer ${this.config.apiKey}`,
155 },
156 });
157 const data = await response.json();
158 return data as any;
159 }
160
161 async list(): Promise<Model[]> {
162 return (await this.openai.models.list()).data;
163 }
164}