| 1 | import { streamJSON } from "@continuedev/fetch"; |
| 2 | import { OpenAI } from "openai/index"; |
| 3 | import { |
| 4 | ChatCompletion, |
| 5 | ChatCompletionChunk, |
| 6 | ChatCompletionCreateParams, |
| 7 | ChatCompletionCreateParamsNonStreaming, |
| 8 | ChatCompletionCreateParamsStreaming, |
| 9 | Completion, |
| 10 | CompletionCreateParamsNonStreaming, |
| 11 | CompletionCreateParamsStreaming, |
| 12 | CreateEmbeddingResponse, |
| 13 | EmbeddingCreateParams, |
| 14 | Model, |
| 15 | } from "openai/resources/index"; |
| 16 | import { CohereConfig } from "../types.js"; |
| 17 | import { chatCompletion, customFetch, embedding } from "../util.js"; |
| 18 | import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; |
| 19 | import { |
| 20 | BaseLlmApi, |
| 21 | CreateRerankResponse, |
| 22 | FimCreateParamsStreaming, |
| 23 | RerankCreateParams, |
| 24 | } from "./base.js"; |
| 25 | |
| 26 | export class CohereApi implements BaseLlmApi { |
| 27 | apiBase: string = "https://api.cohere.com/v1"; |
| 28 | |
| 29 | static maxStopSequences = 5; |
| 30 | |
| 31 | constructor(protected config: CohereConfig) { |
| 32 | this.apiBase = config.apiBase ?? this.apiBase; |
| 33 | } |
| 34 | |
| 35 | private _convertMessages( |
| 36 | msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], |
| 37 | ): any[] { |
| 38 | return msgs.map((m) => ({ |
| 39 | role: m.role === "assistant" ? "CHATBOT" : "USER", |
| 40 | message: m.content, |
| 41 | })); |
| 42 | } |
| 43 | |
| 44 | private _convertBody(oaiBody: ChatCompletionCreateParams) { |
| 45 | return { |
| 46 | message: oaiBody.messages.pop()?.content, |
| 47 | chat_history: this._convertMessages( |
| 48 | oaiBody.messages.filter((msg) => msg.role !== "system"), |
| 49 | ), |
| 50 | preamble: oaiBody.messages.find((msg) => msg.role === "system")?.content, |
| 51 | model: oaiBody.model, |
| 52 | stream: oaiBody.stream, |
| 53 | temperature: oaiBody.temperature, |
| 54 | max_tokens: oaiBody.max_tokens, |
| 55 | p: oaiBody.top_p, |
| 56 | stop_sequences: oaiBody.stop?.slice(0, CohereApi.maxStopSequences), |
| 57 | frequency_penalty: oaiBody.frequency_penalty, |
| 58 | presence_penalty: oaiBody.presence_penalty, |
| 59 | }; |
| 60 | } |
| 61 | |
| 62 | async chatCompletionNonStream( |
| 63 | body: ChatCompletionCreateParamsNonStreaming, |
| 64 | signal: AbortSignal, |
| 65 | ): Promise<ChatCompletion> { |
| 66 | const headers = { |
| 67 | "Content-Type": "application/json", |
| 68 | Authorization: `Bearer ${this.config.apiKey}`, |
| 69 | }; |
| 70 | |
| 71 | const resp = await customFetch(this.config.requestOptions)( |
| 72 | new URL("chat", this.apiBase), |
| 73 | { |
| 74 | method: "POST", |
| 75 | headers, |
| 76 | body: JSON.stringify(this._convertBody(body)), |
| 77 | signal, |
| 78 | }, |
| 79 | ); |
| 80 | |
| 81 | if (resp.status === 499) { |
| 82 | return EMPTY_CHAT_COMPLETION; |
| 83 | } |
| 84 | |
| 85 | const data = (await resp.json()) as any; |
| 86 | const { input_tokens, output_tokens } = data.meta.tokens; |
| 87 | return chatCompletion({ |
| 88 | model: body.model, |
| 89 | id: data.id, |
| 90 | content: data.text, |
| 91 | usage: { |
| 92 | total_tokens: input_tokens + output_tokens, |
| 93 | completion_tokens: output_tokens, |
| 94 | prompt_tokens: input_tokens, |
| 95 | }, |
| 96 | }); |
| 97 | } |
| 98 | |
| 99 | async *chatCompletionStream( |
| 100 | body: ChatCompletionCreateParamsStreaming, |
| 101 | signal: AbortSignal, |
| 102 | ): AsyncGenerator<ChatCompletionChunk> { |
| 103 | const headers = { |
| 104 | "Content-Type": "application/json", |
| 105 | Authorization: `Bearer ${this.config.apiKey}`, |
| 106 | }; |
| 107 | |
| 108 | const resp = await customFetch(this.config.requestOptions)( |
| 109 | new URL("chat", this.apiBase), |
| 110 | { |
| 111 | method: "POST", |
| 112 | headers, |
| 113 | body: JSON.stringify(this._convertBody(body)), |
| 114 | signal, |
| 115 | }, |
| 116 | ); |
| 117 | |
| 118 | for await (const value of streamJSON(resp as any)) { |
| 119 | if (value.event_type === "text-generation") { |
| 120 | yield { |
| 121 | id: value.id, |
| 122 | object: "chat.completion.chunk", |
| 123 | model: body.model, |
| 124 | created: Date.now(), |
| 125 | choices: [ |
| 126 | { |
| 127 | index: 0, |
| 128 | logprobs: undefined, |
| 129 | finish_reason: null, |
| 130 | delta: { |
| 131 | role: "assistant", |
| 132 | content: value.text, |
| 133 | }, |
| 134 | }, |
| 135 | ], |
| 136 | usage: undefined, |
| 137 | }; |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | completionNonStream( |
| 142 | body: CompletionCreateParamsNonStreaming, |
| 143 | ): Promise<Completion> { |
| 144 | throw new Error("Method not implemented."); |
| 145 | } |
| 146 | completionStream( |
| 147 | body: CompletionCreateParamsStreaming, |
| 148 | ): AsyncGenerator<Completion> { |
| 149 | throw new Error("Method not implemented."); |
| 150 | } |
| 151 | fimStream( |
| 152 | body: FimCreateParamsStreaming, |
| 153 | ): AsyncGenerator<ChatCompletionChunk> { |
| 154 | throw new Error("Method not implemented."); |
| 155 | } |
| 156 | async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { |
| 157 | const endpoint = new URL("rerank", this.apiBase); |
| 158 | const response = await customFetch(this.config.requestOptions)(endpoint, { |
| 159 | method: "POST", |
| 160 | body: JSON.stringify(body), |
| 161 | headers: { |
| 162 | "Content-Type": "application/json", |
| 163 | Accept: "application/json", |
| 164 | "x-api-key": this.config.apiKey ?? "", |
| 165 | Authorization: `Bearer ${this.config.apiKey}`, |
| 166 | }, |
| 167 | }); |
| 168 | const data = (await response.json()) as any; |
| 169 | return { |
| 170 | object: "list", |
| 171 | data: data.results.map((result: any) => ({ |
| 172 | index: result.index, |
| 173 | relevance_score: result.relevance_score, |
| 174 | })), |
| 175 | model: body.model, |
| 176 | usage: { |
| 177 | total_tokens: 0, |
| 178 | }, |
| 179 | }; |
| 180 | } |
| 181 | |
| 182 | async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> { |
| 183 | const url = new URL("/embed", this.apiBase); |
| 184 | const texts = typeof body.input === "string" ? [body.input] : body.input; |
| 185 | const response = await customFetch(this.config.requestOptions)(url, { |
| 186 | method: "POST", |
| 187 | headers: { |
| 188 | "Content-Type": "application/json", |
| 189 | Authorization: `Bearer ${this.config.apiKey}`, |
| 190 | }, |
| 191 | body: JSON.stringify({ |
| 192 | texts, |
| 193 | model: body.model, |
| 194 | input_type: "search_document", |
| 195 | }), |
| 196 | }); |
| 197 | const data = (await response.json()) as any; |
| 198 | |
| 199 | return embedding({ |
| 200 | model: body.model, |
| 201 | usage: { |
| 202 | total_tokens: 0, |
| 203 | prompt_tokens: 0, |
| 204 | }, |
| 205 | data: data.embeddings.map((embedding: any) => embedding), |
| 206 | }); |
| 207 | } |
| 208 | |
| 209 | list(): Promise<Model[]> { |
| 210 | throw new Error("Method not implemented."); |
| 211 | } |
| 212 | } |