Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 7.1 KiBRawPermalink
1import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
2import { getHeaders } from "../../continueServer/stubs/headers.js";
3import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
4import {
5 ChatMessage,
6 Chunk,
7 CompletionOptions,
8 LLMOptions,
9} from "../../index.js";
10import { BaseLLM } from "../index.js";
11import { streamResponse } from "../stream.js";
12
13class FreeTrial extends BaseLLM {
14 static providerName = "free-trial";
15 static defaultOptions: Partial<LLMOptions> | undefined = {
16 maxEmbeddingBatchSize: 128,
17 model: "voyage-code-2",
18 };
19
20 private ghAuthToken: string | undefined = undefined;
21
22 constructor(options: LLMOptions) {
23 super(options);
24 this.embeddingId = `${this.constructor.name}::${this.model}`;
25 }
26
27 setupGhAuthToken(ghAuthToken: string | undefined) {
28 this.ghAuthToken = ghAuthToken;
29 }
30
31 private async _getHeaders() {
32 if (!this.ghAuthToken) {
33 throw new Error(
34 "Please sign in with GitHub in order to use the free trial. If you'd like to use Continue without signing in, you can set up your own local model or API key.",
35 );
36 }
37 return {
38 "Content-Type": "application/json",
39 Authorization: `Bearer ${this.ghAuthToken}`,
40 ...(await getHeaders()),
41 };
42 }
43
44 private async _countTokens(prompt: string, model: string, isPrompt: boolean) {
45 // Removed to reduce PostHog bill
46 // if (!Telemetry.client) {
47 // throw new Error(
48 // "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.",
49 // );
50 // }
51 // const event = isPrompt
52 // ? "free_trial_prompt_tokens"
53 // : "free_trial_completion_tokens";
54 // Telemetry.capture(event, {
55 // tokens: this.countTokens(prompt),
56 // model,
57 // });
58 }
59
60 private _convertArgs(options: CompletionOptions): any {
61 return {
62 model: options.model,
63 frequency_penalty: options.frequencyPenalty,
64 presence_penalty: options.presencePenalty,
65 max_tokens: options.maxTokens,
66 stop:
67 options.model === TRIAL_FIM_MODEL
68 ? options.stop
69 : options.stop?.slice(0, 2),
70 temperature: options.temperature,
71 top_p: options.topP,
72 };
73 }
74
75 protected async *_streamComplete(
76 prompt: string,
77 signal: AbortSignal,
78 options: CompletionOptions,
79 ): AsyncGenerator<string> {
80 const args = this._convertArgs(this.collectArgs(options));
81
82 await this._countTokens(prompt, args.model, true);
83
84 const response = await this.fetch(`${TRIAL_PROXY_URL}/stream_complete`, {
85 method: "POST",
86 headers: await this._getHeaders(),
87 body: JSON.stringify({
88 prompt,
89 ...args,
90 }),
91 signal,
92 });
93
94 let completion = "";
95 for await (const value of streamResponse(response)) {
96 yield value;
97 completion += value;
98 }
99 void this._countTokens(completion, args.model, false);
100 }
101
102 protected _convertMessage(message: ChatMessage) {
103 if (message.role === "tool") {
104 return {
105 role: "tool",
106 content: message.content,
107 tool_call_id: message.toolCallId,
108 };
109 }
110
111 if (typeof message.content === "string") {
112 return message;
113 }
114
115 const parts = message.content.map((part) => {
116 if (part.type === "imageUrl") {
117 return {
118 type: "image_url",
119 image_url: {
120 url: part.imageUrl.url,
121 detail: "low",
122 },
123 };
124 }
125 return {
126 type: "text",
127 text: part.text,
128 };
129 });
130 return {
131 ...message,
132 content: parts,
133 };
134 }
135
136 protected async *_streamChat(
137 messages: ChatMessage[],
138 signal: AbortSignal,
139 options: CompletionOptions,
140 ): AsyncGenerator<ChatMessage> {
141 const args = this._convertArgs(this.collectArgs(options));
142
143 await this._countTokens(
144 messages.map((m) => m.content).join("\n"),
145 args.model,
146 true,
147 );
148
149 const response = await this.fetch(`${TRIAL_PROXY_URL}/stream_chat`, {
150 method: "POST",
151 headers: await this._getHeaders(),
152 body: JSON.stringify({
153 messages: messages.map(this._convertMessage),
154 ...args,
155 }),
156 signal,
157 });
158
159 let completion = "";
160 for await (const chunk of streamResponse(response)) {
161 yield {
162 role: "assistant",
163 content: chunk,
164 };
165 completion += chunk;
166 }
167 await this._countTokens(completion, args.model, false);
168 }
169
170 supportsFim(): boolean {
171 return this.model === "codestral-latest";
172 }
173
174 async *_streamFim(
175 prefix: string,
176 suffix: string,
177 signal: AbortSignal,
178 options: CompletionOptions,
179 ): AsyncGenerator<string> {
180 const args = this._convertArgs(this.collectArgs(options));
181
182 try {
183 const resp = await this.fetch(`${TRIAL_PROXY_URL}/stream_fim`, {
184 method: "POST",
185 headers: await this._getHeaders(),
186 body: JSON.stringify({
187 prefix,
188 suffix,
189 ...args,
190 }),
191 signal,
192 });
193
194 let completion = "";
195 for await (const value of streamResponse(resp)) {
196 yield value;
197 completion += value;
198 }
199 await this._countTokens(completion, args.model, false);
200 } catch (e: any) {
201 if (e.message.startsWith("HTTP 429")) {
202 throw new Error(
203 "You have reached the 2000 request limit for the autocomplete free trial. To continue using autocomplete, please set up a local model or your own Codestral API key.",
204 );
205 }
206 throw e;
207 }
208 }
209
210 async listModels(): Promise<string[]> {
211 return [
212 "codestral-latest",
213 "claude-3-5-sonnet-latest",
214 "llama3.1-405b",
215 "llama3.1-70b",
216 "gpt-4o",
217 "gpt-3.5-turbo",
218 "claude-3-5-haiku-latest",
219 "gemini-1.5-pro-latest",
220 ];
221 }
222
223 protected async _embed(chunks: string[]): Promise<number[][]> {
224 const resp = await this.fetch(new URL("embeddings", TRIAL_PROXY_URL), {
225 method: "POST",
226 body: JSON.stringify({
227 input: chunks,
228 model: this.model,
229 }),
230 headers: {
231 "Content-Type": "application/json",
232 ...(await getHeaders()),
233 },
234 });
235
236 if (resp.status !== 200) {
237 throw new Error(`Failed to embed: ${resp.status} ${await resp.text()}`);
238 }
239
240 const data = (await resp.json()) as any;
241 return data.embeddings;
242 }
243
244 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
245 if (chunks.length === 0) {
246 return [];
247 }
248 const resp = await this.fetch(new URL("rerank", TRIAL_PROXY_URL), {
249 method: "POST",
250 headers: {
251 "Content-Type": "application/json",
252 ...(await getHeaders()),
253 },
254 body: JSON.stringify({
255 query,
256 documents: chunks.map((chunk) => chunk.content),
257 }),
258 });
259
260 if (!resp.ok) {
261 throw new Error(await resp.text());
262 }
263
264 const data = (await resp.json()) as any;
265 const results = data.sort((a: any, b: any) => a.index - b.index);
266 return results.map((result: any) => result.relevance_score);
267 }
268}
269
270export default FreeTrial;