Elffuss BraidHub

kikocis/continue public

9c134d8c1202 · 6.3 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 INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/";
27export class InceptionApi extends OpenAIApi {
28 constructor(config: InceptionConfig) {
29 super({
30 ...config,
31 provider: "openai",
32 apiBase: config.apiBase ?? INCEPTION_API_BASE,
33 });
34 }
35
36 // Add custom edit completions method.
37 async *editCompletionStream(
38 body: ChatCompletionCreateParamsStreaming,
39 signal: AbortSignal,
40 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
41 const endpoint = new URL("edit/completions", this.apiBase);
42 const resp = await customFetch(this.config.requestOptions)(endpoint, {
43 method: "POST",
44 body: JSON.stringify({
45 model: body.model,
46 messages: body.messages,
47 max_tokens: body.max_tokens,
48 temperature: body.temperature,
49 top_p: body.top_p,
50 frequency_penalty: body.frequency_penalty,
51 presence_penalty: body.presence_penalty,
52 stop: body.stop,
53 stream: true,
54 }),
55 headers: {
56 "Content-Type": "application/json",
57 Accept: "application/json",
58 Authorization: `Bearer ${this.config.apiKey}`,
59 },
60 signal,
61 });
62
63 for await (const chunk of streamSse(resp as any)) {
64 if (chunk.choices?.[0]?.delta?.content) {
65 yield chatChunk({
66 content: chunk.choices[0].delta.content,
67 finish_reason: chunk.choices[0].finish_reason || null,
68 model: body.model,
69 });
70 }
71 }
72 }
73
74 // Add custom edit completions method (non-streaming).
75 async editCompletionNonStream(
76 body: ChatCompletionCreateParamsNonStreaming,
77 signal: AbortSignal,
78 ): Promise<ChatCompletion> {
79 const endpoint = new URL("edit/completions", this.apiBase);
80 const resp = await customFetch(this.config.requestOptions)(endpoint, {
81 method: "POST",
82 body: JSON.stringify({
83 model: body.model,
84 messages: body.messages,
85 max_tokens: body.max_tokens,
86 temperature: body.temperature,
87 top_p: body.top_p,
88 frequency_penalty: body.frequency_penalty,
89 presence_penalty: body.presence_penalty,
90 stop: body.stop,
91 stream: false, // Set to false for non-streaming
92 }),
93 headers: {
94 "Content-Type": "application/json",
95 Accept: "application/json",
96 Authorization: `Bearer ${this.config.apiKey}`,
97 },
98 signal,
99 });
100
101 const data = await resp.json();
102 return data as ChatCompletion;
103 }
104
105 // Override the regular chat stream method to route to edit endpoint for next edit requests.
106 async *chatCompletionStream(
107 body: ChatCompletionCreateParamsStreaming,
108 signal: AbortSignal,
109 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
110 if (this.isNextEdit(body.messages)) {
111 body.messages = this.removeNextEditToken(body.messages);
112 yield* this.editCompletionStream(body, signal);
113 } else {
114 yield* super.chatCompletionStream(body, signal);
115 }
116 }
117
118 // Override the regular chat non stream method to route to edit endpoint for next edit requests.
119 async chatCompletionNonStream(
120 body: ChatCompletionCreateParamsNonStreaming,
121 signal: AbortSignal,
122 ): Promise<ChatCompletion> {
123 if (this.isNextEdit(body.messages)) {
124 body.messages = this.removeNextEditToken(body.messages);
125 return this.editCompletionNonStream(body, signal);
126 } else {
127 return super.chatCompletionNonStream(body, signal);
128 }
129 }
130
131 async *fimStream(
132 body: FimCreateParamsStreaming,
133 signal: AbortSignal,
134 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
135 const endpoint = new URL("completions", this.apiBase);
136 const resp = await customFetch(this.config.requestOptions)(endpoint, {
137 method: "POST",
138 body: JSON.stringify({
139 model: body.model,
140 prompt: body.prompt,
141 suffix: body.suffix.trim() === "" ? "<|endoftext|>" : body.suffix,
142 max_tokens: body.max_tokens ?? 150, // Only want this for /fim, not chat
143 temperature: body.temperature,
144 top_p: body.top_p,
145 frequency_penalty: body.frequency_penalty,
146 presence_penalty: body.presence_penalty,
147 stop: [...(body.stop ?? []), "\n\n", "\n \n"],
148 stream: true,
149 }),
150 headers: {
151 "Content-Type": "application/json",
152 Accept: "application/json",
153 Authorization: `Bearer ${this.config.apiKey}`,
154 },
155 signal,
156 });
157 for await (const chunk of streamSse(resp as any)) {
158 if (!chunk.choices[0]) {
159 continue;
160 }
161 yield chatChunk({
162 content: chunk.choices[0].text,
163 finish_reason: null,
164 model: body.model,
165 });
166 }
167 }
168
169 list(): Promise<Model[]> {
170 throw new Error("Method not implemented.");
171 }
172
173 // Check if any message contains the unique next edit token.
174 private isNextEdit(messages: ChatCompletionMessageParam[]): boolean {
175 return messages.some(
176 (message) =>
177 typeof message.content === "string" &&
178 message.content.endsWith(UNIQUE_TOKEN),
179 );
180 }
181
182 // Remove the unique token from messages.
183 private removeNextEditToken(
184 messages: ChatCompletionMessageParam[],
185 ): ChatCompletionMessageParam[] {
186 const lastMessage = messages[messages.length - 1];
187
188 if (
189 typeof lastMessage?.content === "string" &&
190 lastMessage.content.endsWith(UNIQUE_TOKEN)
191 ) {
192 const cleanedMessages = [...messages];
193 cleanedMessages[cleanedMessages.length - 1] = {
194 ...lastMessage,
195 content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
196 };
197 return cleanedMessages;
198 }
199
200 return messages;
201 }
202}