Elffuss BraidHub

kikocis/continue public

main · 7.8 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import {
3 ChatCompletion,
4 ChatCompletionChunk,
5 ChatCompletionCreateParamsNonStreaming,
6 ChatCompletionCreateParamsStreaming,
7 ChatCompletionMessageParam,
8 Model,
9} from "openai/resources/index";
10import { InceptionConfig } from "../types.js";
11import { chatChunk, customFetch } from "../util.js";
12import { OpenAIApi } from "./OpenAI.js";
13import { FimCreateParamsStreaming } from "./base.js";
14
15// export type InceptionChatCompletionCreateParamsStreaming =
16// ChatCompletionCreateParamsStreaming & {
17// nextEdit?: boolean;
18// };
19
20// export type InceptionChatCompletionCreateParamsNonStreaming =
21// ChatCompletionCreateParamsNonStreaming & {
22// nextEdit?: boolean;
23// };
24
25export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>";
26export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";
27export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/";
28export class InceptionApi extends OpenAIApi {
29 constructor(config: InceptionConfig) {
30 super({
31 ...config,
32 provider: "openai",
33 apiBase: config.apiBase ?? INCEPTION_API_BASE,
34 });
35 }
36
37 // Add custom edit completions method.
38 async *editCompletionStream(
39 body: ChatCompletionCreateParamsStreaming,
40 signal: AbortSignal,
41 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
42 yield* this.streamCustomEndpoint("edit/completions", body, signal);
43 }
44
45 // Add custom edit completions method (non-streaming).
46 async editCompletionNonStream(
47 body: ChatCompletionCreateParamsNonStreaming,
48 signal: AbortSignal,
49 ): Promise<ChatCompletion> {
50 return this.nonStreamCustomEndpoint("edit/completions", body, signal);
51 }
52
53 // Override the regular chat stream method to route to edit endpoint for next edit requests.
54 async *chatCompletionStream(
55 body: ChatCompletionCreateParamsStreaming,
56 signal: AbortSignal,
57 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
58 if (this.isNextEdit(body.messages)) {
59 body.messages = this.removeToken(body.messages, UNIQUE_TOKEN);
60 yield* this.editCompletionStream(body, signal);
61 } else if (this.isApply(body.messages)) {
62 body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN);
63 yield* this.applyCompletionStream(body, signal);
64 } else {
65 yield* super.chatCompletionStream(body, signal);
66 }
67 }
68
69 // Override the regular chat non stream method to route to edit endpoint for next edit requests.
70 async chatCompletionNonStream(
71 body: ChatCompletionCreateParamsNonStreaming,
72 signal: AbortSignal,
73 ): Promise<ChatCompletion> {
74 if (this.isNextEdit(body.messages)) {
75 body.messages = this.removeToken(body.messages, UNIQUE_TOKEN);
76 return this.editCompletionNonStream(body, signal);
77 } else if (this.isApply(body.messages)) {
78 body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN);
79 return this.applyCompletionNonStream(body, signal);
80 } else {
81 return super.chatCompletionNonStream(body, signal);
82 }
83 }
84
85 async *applyCompletionStream(
86 body: ChatCompletionCreateParamsStreaming,
87 signal: AbortSignal,
88 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
89 yield* this.streamCustomEndpoint("apply/completions", body, signal);
90 }
91
92 async applyCompletionNonStream(
93 body: ChatCompletionCreateParamsNonStreaming,
94 signal: AbortSignal,
95 ): Promise<ChatCompletion> {
96 return this.nonStreamCustomEndpoint("apply/completions", body, signal);
97 }
98
99 async *fimStream(
100 body: FimCreateParamsStreaming,
101 signal: AbortSignal,
102 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
103 const endpoint = new URL("completions", this.apiBase);
104 const resp = await customFetch(this.config.requestOptions)(endpoint, {
105 method: "POST",
106 body: JSON.stringify({
107 model: body.model,
108 prompt: body.prompt,
109 suffix: body.suffix.trim() === "" ? "<|endoftext|>" : body.suffix,
110 max_tokens: body.max_tokens ?? 150, // Only want this for /fim, not chat
111 temperature: body.temperature,
112 top_p: body.top_p,
113 frequency_penalty: body.frequency_penalty,
114 presence_penalty: body.presence_penalty,
115 stop: [...(body.stop ?? []), "\n\n", "\n \n"],
116 stream: true,
117 }),
118 headers: {
119 "Content-Type": "application/json",
120 Accept: "application/json",
121 Authorization: `Bearer ${this.config.apiKey}`,
122 },
123 signal,
124 });
125 for await (const chunk of streamSse(resp as any)) {
126 if (!chunk.choices[0]) {
127 continue;
128 }
129 yield chatChunk({
130 content: chunk.choices[0].text,
131 finish_reason: null,
132 model: body.model,
133 });
134 }
135 }
136
137 list(): Promise<Model[]> {
138 throw new Error("Method not implemented.");
139 }
140
141 // Check if any message contains the unique next edit token.
142 private isNextEdit(messages: ChatCompletionMessageParam[]): boolean {
143 return messages.some(
144 (message) =>
145 typeof message.content === "string" &&
146 message.content.endsWith(UNIQUE_TOKEN),
147 );
148 }
149
150 private isApply(messages: ChatCompletionMessageParam[]): boolean {
151 return messages.some(
152 (message) =>
153 typeof message.content === "string" &&
154 message.content.endsWith(APPLY_UNIQUE_TOKEN),
155 );
156 }
157
158 // Remove the unique token from messages.
159 private removeToken(
160 messages: ChatCompletionMessageParam[],
161 token: string,
162 ): ChatCompletionMessageParam[] {
163 const lastMessage = messages[messages.length - 1];
164
165 if (
166 typeof lastMessage?.content === "string" &&
167 lastMessage.content.endsWith(token)
168 ) {
169 const cleanedMessages = [...messages];
170 cleanedMessages[cleanedMessages.length - 1] = {
171 ...lastMessage,
172 content: lastMessage.content.slice(0, -token.length),
173 };
174 return cleanedMessages;
175 }
176
177 return messages;
178 }
179
180 private async *streamCustomEndpoint(
181 path: string,
182 body: ChatCompletionCreateParamsStreaming,
183 signal: AbortSignal,
184 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
185 const endpoint = new URL(path, this.apiBase);
186 const resp = await customFetch(this.config.requestOptions)(endpoint, {
187 method: "POST",
188 body: JSON.stringify({
189 model: body.model,
190 messages: body.messages,
191 max_tokens: body.max_tokens,
192 temperature: body.temperature,
193 top_p: body.top_p,
194 frequency_penalty: body.frequency_penalty,
195 presence_penalty: body.presence_penalty,
196 stop: body.stop,
197 stream: true,
198 }),
199 headers: {
200 "Content-Type": "application/json",
201 Accept: "application/json",
202 Authorization: `Bearer ${this.config.apiKey}`,
203 },
204 signal,
205 });
206
207 for await (const chunk of streamSse(resp as any)) {
208 const deltaContent = chunk.choices?.[0]?.delta?.content;
209 if (deltaContent) {
210 yield chatChunk({
211 content: deltaContent,
212 finish_reason: chunk.choices[0].finish_reason || null,
213 model: body.model,
214 });
215 }
216 }
217 }
218
219 private async nonStreamCustomEndpoint(
220 path: string,
221 body: ChatCompletionCreateParamsNonStreaming,
222 signal: AbortSignal,
223 ): Promise<ChatCompletion> {
224 const endpoint = new URL(path, this.apiBase);
225 const resp = await customFetch(this.config.requestOptions)(endpoint, {
226 method: "POST",
227 body: JSON.stringify({
228 model: body.model,
229 messages: body.messages,
230 max_tokens: body.max_tokens,
231 temperature: body.temperature,
232 top_p: body.top_p,
233 frequency_penalty: body.frequency_penalty,
234 presence_penalty: body.presence_penalty,
235 stop: body.stop,
236 stream: false,
237 }),
238 headers: {
239 "Content-Type": "application/json",
240 Accept: "application/json",
241 Authorization: `Bearer ${this.config.apiKey}`,
242 },
243 signal,
244 });
245
246 const data = await resp.json();
247 return data as ChatCompletion;
248 }
249}