| 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | import { ChatCompletionChunk, Model } from "openai/resources/index"; |
| 3 | import { MoonshotConfig } from "../types.js"; |
| 4 | import { chatChunk, customFetch } from "../util.js"; |
| 5 | import { OpenAIApi } from "./OpenAI.js"; |
| 6 | import { FimCreateParamsStreaming } from "./base.js"; |
| 7 | |
| 8 | export class MoonshotApi extends OpenAIApi { |
| 9 | apiBase: string = "https://api.moonshot.cn/"; |
| 10 | constructor(config: MoonshotConfig) { |
| 11 | super({ |
| 12 | ...config, |
| 13 | provider: "openai", |
| 14 | }); |
| 15 | } |
| 16 | |
| 17 | async *fimStream( |
| 18 | body: FimCreateParamsStreaming, |
| 19 | signal: AbortSignal, |
| 20 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 21 | const endpoint = new URL("v1/chat/completions", this.apiBase); |
| 22 | const resp = await customFetch(this.config.requestOptions)(endpoint, { |
| 23 | method: "POST", |
| 24 | body: JSON.stringify({ |
| 25 | model: body.model, |
| 26 | messages: [ |
| 27 | { |
| 28 | role: "user", |
| 29 | content: body.prompt + "[fill]" + body.suffix, |
| 30 | }, |
| 31 | ], |
| 32 | max_tokens: body.max_tokens, |
| 33 | temperature: body.temperature, |
| 34 | top_p: body.top_p, |
| 35 | frequency_penalty: body.frequency_penalty, |
| 36 | presence_penalty: body.presence_penalty, |
| 37 | stop: body.stop, |
| 38 | stream: true, |
| 39 | }), |
| 40 | headers: { |
| 41 | "Content-Type": "application/json", |
| 42 | Accept: "application/json", |
| 43 | Authorization: `Bearer ${this.config.apiKey}`, |
| 44 | }, |
| 45 | signal, |
| 46 | }); |
| 47 | |
| 48 | for await (const chunk of streamSse(resp as any)) { |
| 49 | yield chatChunk({ |
| 50 | content: chunk.choices[0].delta.content, |
| 51 | finish_reason: chunk.finish_reason, |
| 52 | model: body.model, |
| 53 | }); |
| 54 | } |
| 55 | } |
| 56 | list(): Promise<Model[]> { |
| 57 | throw new Error("Method not implemented."); |
| 58 | } |
| 59 | } |