| 1 | import { |
| 2 | ChatMessage, |
| 3 | Chunk, |
| 4 | CompletionOptions, |
| 5 | LLMOptions, |
| 6 | } from "../../index.js"; |
| 7 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 8 | import { BaseLLM } from "../index.js"; |
| 9 | import { streamJSON } from "../stream.js"; |
| 10 | |
| 11 | class 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 (options.stream === false) { |
| 88 | const data = await resp.json(); |
| 89 | yield { role: "assistant", content: data.text }; |
| 90 | return; |
| 91 | } |
| 92 | |
| 93 | for await (const value of streamJSON(resp)) { |
| 94 | if (value.event_type === "text-generation") { |
| 95 | yield { role: "assistant", content: value.text }; |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 101 | const resp = await this.fetch(new URL("embed", this.apiBase), { |
| 102 | method: "POST", |
| 103 | body: JSON.stringify({ |
| 104 | texts: chunks, |
| 105 | model: this.model, |
| 106 | input_type: "search_document", |
| 107 | embedding_types: ["float"], |
| 108 | truncate: "END", |
| 109 | }), |
| 110 | headers: { |
| 111 | Authorization: `Bearer ${this.apiKey}`, |
| 112 | "Content-Type": "application/json", |
| 113 | }, |
| 114 | }); |
| 115 | |
| 116 | if (!resp.ok) { |
| 117 | throw new Error(await resp.text()); |
| 118 | } |
| 119 | |
| 120 | const data = (await resp.json()) as any; |
| 121 | return data.embeddings.float; |
| 122 | } |
| 123 | |
| 124 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 125 | const resp = await this.fetch(new URL("rerank", this.apiBase), { |
| 126 | method: "POST", |
| 127 | headers: { |
| 128 | Authorization: `Bearer ${this.apiKey}`, |
| 129 | "Content-Type": "application/json", |
| 130 | }, |
| 131 | body: JSON.stringify({ |
| 132 | model: this.model, |
| 133 | query, |
| 134 | documents: chunks.map((chunk) => chunk.content), |
| 135 | }), |
| 136 | }); |
| 137 | |
| 138 | if (!resp.ok) { |
| 139 | throw new Error(await resp.text()); |
| 140 | } |
| 141 | |
| 142 | const data = (await resp.json()) as any; |
| 143 | const results = data.results.sort((a: any, b: any) => a.index - b.index); |
| 144 | return results.map((result: any) => result.relevance_score); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | export default Cohere; |