Elffuss BraidHub

kikocis/continue public

main · 8.7 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import {
3 ChatMessage,
4 Chunk,
5 CompletionOptions,
6 LLMOptions,
7 MessageContent,
8} from "../../index.js";
9import { renderChatMessage, stripImages } from "../../util/messageContent.js";
10import { BaseLLM } from "../index.js";
11
12class Cohere extends BaseLLM {
13 static providerName = "cohere";
14 static defaultOptions: Partial<LLMOptions> = {
15 apiBase: "https://api.cohere.ai/v2",
16 maxEmbeddingBatchSize: 96,
17 };
18 static maxStopSequences = 5;
19
20 private _convertMessages(msgs: ChatMessage[]): any[] {
21 const messages = [];
22 let lastToolPlan: MessageContent | undefined;
23 for (const m of msgs) {
24 if (!m.content) {
25 continue;
26 }
27 switch (m.role) {
28 case "user":
29 if (typeof m.content === "string") {
30 messages.push({
31 role: m.role,
32 content: m.content,
33 });
34 break;
35 }
36
37 messages.push({
38 role: m.role,
39 content: m.content.map((part) => {
40 if (part.type === "imageUrl") {
41 return {
42 type: "image_url",
43 image_url: { url: part.imageUrl.url },
44 };
45 }
46 return part;
47 }),
48 });
49 break;
50 case "thinking":
51 lastToolPlan = m.content;
52 break;
53 case "assistant":
54 if (m.toolCalls) {
55 if (!lastToolPlan) {
56 throw new Error("No tool plan found");
57 }
58 messages.push({
59 role: m.role,
60 tool_calls: m.toolCalls.map((toolCall) => ({
61 id: toolCall.id,
62 type: "function",
63 function: {
64 name: toolCall.function?.name,
65 arguments: toolCall.function?.arguments,
66 },
67 })),
68 // Ideally the tool plan would be in this message, but it is
69 // split in another, usually the previous, this one's content is
70 // a space.
71 // tool_plan: m.content,
72 tool_plan: lastToolPlan,
73 });
74 lastToolPlan = undefined;
75 break;
76 }
77 messages.push({
78 role: m.role,
79 content: m.content,
80 });
81 break;
82 case "system":
83 messages.push({
84 role: m.role,
85 content: stripImages(m.content),
86 });
87 break;
88 case "tool":
89 messages.push({
90 role: m.role,
91 content: m.content,
92 tool_call_id: m.toolCallId,
93 });
94 break;
95 default:
96 break;
97 }
98 }
99 return messages;
100 }
101
102 private _convertArgs(options: CompletionOptions) {
103 return {
104 model: options.model,
105 stream: options.stream ?? true,
106 temperature: options.temperature,
107 max_tokens: options.maxTokens,
108 k: options.topK,
109 p: options.topP,
110 stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences),
111 frequency_penalty: options.frequencyPenalty,
112 presence_penalty: options.presencePenalty,
113 tools: options.tools?.map((tool) => ({
114 type: "function",
115 function: {
116 name: tool.function.name,
117 parameters: tool.function.parameters,
118 description: tool.function.description,
119 },
120 })),
121 };
122 }
123
124 protected async *_streamComplete(
125 prompt: string,
126 signal: AbortSignal,
127 options: CompletionOptions,
128 ): AsyncGenerator<string> {
129 const messages = [{ role: "user" as const, content: prompt }];
130 for await (const update of this._streamChat(messages, signal, options)) {
131 yield renderChatMessage(update);
132 }
133 }
134
135 protected async *_streamChat(
136 messages: ChatMessage[],
137 signal: AbortSignal,
138 options: CompletionOptions,
139 ): AsyncGenerator<ChatMessage> {
140 const headers = {
141 "Content-Type": "application/json",
142 Authorization: `Bearer ${this.apiKey}`,
143 ...this.requestOptions?.headers,
144 };
145
146 const resp = await this.fetch(new URL("chat", this.apiBase), {
147 method: "POST",
148 headers,
149 body: JSON.stringify({
150 ...this._convertArgs(options),
151 messages: this._convertMessages(messages),
152 }),
153 signal,
154 });
155
156 if (resp.status === 499) {
157 return; // Aborted by user
158 }
159
160 if (options.stream === false) {
161 const data = await resp.json();
162 if (data.message.tool_calls) {
163 yield {
164 // Use the "thinking" role for `tool_plan`, since there is no such
165 // role in the Cohere API at the moment and it is a "a
166 // chain-of-thought style reflection".
167 role: "thinking",
168 content: data.message.tool_plan,
169 };
170 yield {
171 role: "assistant",
172 content: "",
173 toolCalls: data.message.tool_calls.map((toolCall: any) => ({
174 id: toolCall.id,
175 type: "function",
176 function: {
177 name: toolCall.function?.name,
178 arguments: toolCall.function?.arguments,
179 },
180 })),
181 };
182 return;
183 }
184 yield { role: "assistant", content: data.message.content[0].text };
185 return;
186 }
187
188 let lastToolUseId: string | undefined;
189 let lastToolUseName: string | undefined;
190 for await (const value of streamSse(resp)) {
191 // https://docs.cohere.com/v2/docs/streaming#stream-events
192 switch (value.type) {
193 // https://docs.cohere.com/v2/docs/streaming#content-delta
194 case "content-delta":
195 yield {
196 role: "assistant",
197 content: value.delta.message.content.text,
198 };
199 break;
200 // https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan
201 case "tool-plan-delta":
202 // Use the "thinking" role for `tool_plan`, since there is no such
203 // role in the Cohere API at the moment and it is a "a
204 // chain-of-thought style reflection".
205 yield {
206 role: "thinking",
207 content: value.delta.message.tool_plan,
208 };
209 break;
210 case "tool-call-start":
211 lastToolUseId = value.delta.message.tool_calls.id;
212 lastToolUseName = value.delta.message.tool_calls.function.name;
213 yield {
214 role: "assistant",
215 content: "",
216 toolCalls: [
217 {
218 id: lastToolUseId,
219 type: "function",
220 function: {
221 name: lastToolUseName,
222 arguments: value.delta.message.tool_calls.function.arguments,
223 },
224 },
225 ],
226 };
227 break;
228 case "tool-call-delta":
229 if (!lastToolUseId || !lastToolUseName) {
230 throw new Error("No tool use found");
231 }
232 yield {
233 role: "assistant",
234 content: "",
235 toolCalls: [
236 {
237 id: lastToolUseId,
238 type: "function",
239 function: {
240 name: lastToolUseName,
241 arguments: value.delta.message.tool_calls.function.arguments,
242 },
243 },
244 ],
245 };
246 break;
247 case "tool-call-end":
248 lastToolUseId = undefined;
249 lastToolUseName = undefined;
250 break;
251 default:
252 break;
253 }
254 }
255 }
256
257 protected async _embed(chunks: string[]): Promise<number[][]> {
258 const resp = await this.fetch(new URL("embed", this.apiBase), {
259 method: "POST",
260 body: JSON.stringify({
261 texts: chunks,
262 model: this.model,
263 input_type: "search_document",
264 embedding_types: ["float"],
265 truncate: "END",
266 }),
267 headers: {
268 Authorization: `Bearer ${this.apiKey}`,
269 "Content-Type": "application/json",
270 },
271 });
272
273 if (!resp.ok) {
274 throw new Error(await resp.text());
275 }
276
277 const data = (await resp.json()) as any;
278 return data.embeddings.float;
279 }
280
281 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
282 const resp = await this.fetch(new URL("rerank", this.apiBase), {
283 method: "POST",
284 headers: {
285 Authorization: `Bearer ${this.apiKey}`,
286 "Content-Type": "application/json",
287 },
288 body: JSON.stringify({
289 model: this.model,
290 query,
291 documents: chunks.map((chunk) => chunk.content),
292 }),
293 });
294
295 if (!resp.ok) {
296 throw new Error(await resp.text());
297 }
298
299 const data = (await resp.json()) as any;
300 const results = data.results.sort((a: any, b: any) => a.index - b.index);
301 return results.map((result: any) => result.relevance_score);
302 }
303}
304
305export default Cohere;