Elffuss BraidHub

kikocis/continue public

main · 1.8 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { ChatMessage, CompletionOptions } from "../../index.js";
3import { renderChatMessage } from "../../util/messageContent.js";
4import { BaseLLM } from "../index.js";
5
6export default class Cloudflare extends BaseLLM {
7 static providerName = "cloudflare";
8
9 private _convertArgs(options: CompletionOptions) {
10 const finalOptions = {
11 max_tokens: options.maxTokens,
12 };
13
14 return finalOptions;
15 }
16
17 protected async *_streamChat(
18 messages: ChatMessage[],
19 signal: AbortSignal,
20 options: CompletionOptions,
21 ): AsyncGenerator<ChatMessage, any, unknown> {
22 const headers = {
23 "Content-Type": "application/json",
24 Authorization: `Bearer ${this.apiKey}`,
25 ...this.requestOptions?.headers,
26 };
27 const url = this.aiGatewaySlug
28 ? `https://gateway.ai.cloudflare.com/v1/${this.accountId}/${this.aiGatewaySlug}/workers-ai/v1/chat/completions`
29 : `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/ai/v1/chat/completions`;
30 const resp = await this.fetch(new URL(url), {
31 method: "POST",
32 headers,
33 body: JSON.stringify({
34 messages,
35 stream: true,
36 model: this.model,
37 ...this._convertArgs(options),
38 }),
39 signal,
40 });
41
42 for await (const value of streamSse(resp)) {
43 if (value.choices?.[0]?.delta?.content) {
44 yield {
45 role: "assistant",
46 content: value.choices[0].delta.content,
47 };
48 }
49 }
50 }
51
52 protected async *_streamComplete(
53 prompt: string,
54 signal: AbortSignal,
55 options: CompletionOptions,
56 ): AsyncGenerator<string> {
57 for await (const chunk of this._streamChat(
58 [{ role: "user", content: prompt }],
59 signal,
60 options,
61 )) {
62 yield renderChatMessage(chunk);
63 }
64 }
65}