Elffuss BraidHub

kikocis/continue public

d691089ac9f7 · 4.1 KiBRawPermalink
1import { streamJSON } from "@continuedev/fetch";
2import {
3 ChatMessage,
4 Chunk,
5 CompletionOptions,
6 LLMOptions,
7} from "../../index.js";
8import { renderChatMessage, stripImages } from "../../util/messageContent.js";
9import { BaseLLM } from "../index.js";
10
11class Cohere extends BaseLLM {
12 static providerName = "cohere";
13 static defaultOptions: Partial<LLMOptions> = {
14 apiBase: "https://api.cohere.ai/v1",
15 maxEmbeddingBatchSize: 96,
16 };
17 static maxStopSequences = 5;
18
19 private _convertMessages(msgs: ChatMessage[]): any[] {
20 const messages = [];
21 for (const m of msgs) {
22 if (m.role === "system" || !m.content) {
23 continue;
24 }
25 messages.push({
26 role: m.role === "assistant" ? "chatbot" : m.role,
27 message: m.content,
28 });
29 }
30 return messages;
31 }
32
33 private _convertArgs(options: CompletionOptions) {
34 return {
35 model: options.model,
36 stream: options.stream ?? true,
37 temperature: options.temperature,
38 max_tokens: options.maxTokens,
39 k: options.topK,
40 p: options.topP,
41 stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences),
42 frequency_penalty: options.frequencyPenalty,
43 presence_penalty: options.presencePenalty,
44 raw_prompting: options.raw,
45 };
46 }
47
48 protected async *_streamComplete(
49 prompt: string,
50 signal: AbortSignal,
51 options: CompletionOptions,
52 ): AsyncGenerator<string> {
53 const messages = [{ role: "user" as const, content: prompt }];
54 for await (const update of this._streamChat(messages, signal, options)) {
55 yield renderChatMessage(update);
56 }
57 }
58
59 protected async *_streamChat(
60 messages: ChatMessage[],
61 signal: AbortSignal,
62 options: CompletionOptions,
63 ): AsyncGenerator<ChatMessage> {
64 const headers = {
65 "Content-Type": "application/json",
66 Authorization: `Bearer ${this.apiKey}`,
67 ...this.requestOptions?.headers,
68 };
69
70 let preamble: string | undefined = undefined;
71 const systemMessage = messages.find((m) => m.role === "system")?.content;
72 if (systemMessage) {
73 preamble = stripImages(systemMessage);
74 }
75 const resp = await this.fetch(new URL("chat", this.apiBase), {
76 method: "POST",
77 headers,
78 body: JSON.stringify({
79 ...this._convertArgs(options),
80 message: messages.pop()?.content,
81 chat_history: this._convertMessages(messages),
82 preamble,
83 }),
84 signal,
85 });
86
87 if (resp.status === 499) {
88 return; // Aborted by user
89 }
90
91 if (options.stream === false) {
92 const data = await resp.json();
93 yield { role: "assistant", content: data.text };
94 return;
95 }
96
97 for await (const value of streamJSON(resp)) {
98 if (value.event_type === "text-generation") {
99 yield { role: "assistant", content: value.text };
100 }
101 }
102 }
103
104 protected async _embed(chunks: string[]): Promise<number[][]> {
105 const resp = await this.fetch(new URL("embed", this.apiBase), {
106 method: "POST",
107 body: JSON.stringify({
108 texts: chunks,
109 model: this.model,
110 input_type: "search_document",
111 embedding_types: ["float"],
112 truncate: "END",
113 }),
114 headers: {
115 Authorization: `Bearer ${this.apiKey}`,
116 "Content-Type": "application/json",
117 },
118 });
119
120 if (!resp.ok) {
121 throw new Error(await resp.text());
122 }
123
124 const data = (await resp.json()) as any;
125 return data.embeddings.float;
126 }
127
128 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
129 const resp = await this.fetch(new URL("rerank", this.apiBase), {
130 method: "POST",
131 headers: {
132 Authorization: `Bearer ${this.apiKey}`,
133 "Content-Type": "application/json",
134 },
135 body: JSON.stringify({
136 model: this.model,
137 query,
138 documents: chunks.map((chunk) => chunk.content),
139 }),
140 });
141
142 if (!resp.ok) {
143 throw new Error(await resp.text());
144 }
145
146 const data = (await resp.json()) as any;
147 const results = data.results.sort((a: any, b: any) => a.index - b.index);
148 return results.map((result: any) => result.relevance_score);
149 }
150}
151
152export default Cohere;