|
| 1 | +import { Anthropic } from "@anthropic-ai/sdk" |
| 2 | +import OpenAI from "openai" |
| 3 | + |
| 4 | +import { cometApiDefaultModelId, cometApiDefaultModelInfo, cometApiModels } from "@roo-code/types" |
| 5 | + |
| 6 | +import type { ApiHandlerOptions } from "../../shared/api" |
| 7 | +import { calculateApiCostOpenAI } from "../../shared/cost" |
| 8 | + |
| 9 | +import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" |
| 10 | +import { convertToOpenAiMessages } from "../transform/openai-format" |
| 11 | +import { getModelParams } from "../transform/model-params" |
| 12 | + |
| 13 | +import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata } from "../index" |
| 14 | +import { RouterProvider } from "./router-provider" |
| 15 | + |
| 16 | +export class CometAPIHandler extends RouterProvider implements SingleCompletionHandler { |
| 17 | + constructor(options: ApiHandlerOptions) { |
| 18 | + super({ |
| 19 | + options: { |
| 20 | + ...options, |
| 21 | + // Add custom headers for CometAPI |
| 22 | + openAiHeaders: { |
| 23 | + "HTTP-Referer": "https://github.com/RooVetGit/Roo-Code", |
| 24 | + "X-Title": "Roo Code", |
| 25 | + ...(options.openAiHeaders || {}), |
| 26 | + }, |
| 27 | + }, |
| 28 | + name: "cometapi", |
| 29 | + baseURL: options.cometApiBaseUrl || "https://api.cometapi.com/v1", |
| 30 | + apiKey: options.cometApiKey || "not-provided", |
| 31 | + modelId: options.cometApiModelId, |
| 32 | + defaultModelId: cometApiDefaultModelId, |
| 33 | + defaultModelInfo: cometApiDefaultModelInfo, |
| 34 | + }) |
| 35 | + |
| 36 | + // Initialize with fallback models to ensure we always have models available |
| 37 | + this.models = { ...cometApiModels } |
| 38 | + } |
| 39 | + |
| 40 | + public override async fetchModel() { |
| 41 | + // Fetch dynamic models from API, but keep fallback models if API fails |
| 42 | + try { |
| 43 | + const apiModels = await super.fetchModel() |
| 44 | + // Merge API models with fallback models |
| 45 | + this.models = { ...cometApiModels, ...this.models } |
| 46 | + return apiModels |
| 47 | + } catch (error) { |
| 48 | + console.warn("CometAPI: Failed to fetch models from API, using fallback models", error) |
| 49 | + // Return default model using fallback models |
| 50 | + return this.getModel() |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + override getModel() { |
| 55 | + const id = this.options.cometApiModelId ?? cometApiDefaultModelId |
| 56 | + const info = this.models[id] ?? cometApiDefaultModelInfo |
| 57 | + |
| 58 | + const params = getModelParams({ |
| 59 | + format: "openai", |
| 60 | + modelId: id, |
| 61 | + model: info, |
| 62 | + settings: this.options, |
| 63 | + }) |
| 64 | + |
| 65 | + return { id, info, ...params } |
| 66 | + } |
| 67 | + |
| 68 | + override async *createMessage( |
| 69 | + systemPrompt: string, |
| 70 | + messages: Anthropic.Messages.MessageParam[], |
| 71 | + _metadata?: ApiHandlerCreateMessageMetadata, |
| 72 | + ): ApiStream { |
| 73 | + // Ensure we have up-to-date model metadata |
| 74 | + await this.fetchModel() |
| 75 | + const { id: modelId, info, reasoningEffort } = this.getModel() |
| 76 | + |
| 77 | + const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { |
| 78 | + model: modelId, |
| 79 | + messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)], |
| 80 | + stream: true, |
| 81 | + stream_options: { include_usage: true }, |
| 82 | + reasoning_effort: reasoningEffort, |
| 83 | + } as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming |
| 84 | + |
| 85 | + if (this.supportsTemperature(modelId)) { |
| 86 | + requestOptions.temperature = this.options.modelTemperature ?? 0 |
| 87 | + } |
| 88 | + |
| 89 | + if (this.options.includeMaxTokens === true && info.maxTokens) { |
| 90 | + ;(requestOptions as any).max_completion_tokens = this.options.modelMaxTokens || info.maxTokens |
| 91 | + } |
| 92 | + |
| 93 | + const { data: stream } = await this.client.chat.completions.create(requestOptions).withResponse() |
| 94 | + |
| 95 | + let lastUsage: OpenAI.CompletionUsage | undefined |
| 96 | + for await (const chunk of stream) { |
| 97 | + const delta = chunk.choices[0]?.delta |
| 98 | + |
| 99 | + if (delta?.content) { |
| 100 | + yield { type: "text", text: delta.content } |
| 101 | + } |
| 102 | + |
| 103 | + if (delta && "reasoning_content" in delta && delta.reasoning_content) { |
| 104 | + yield { type: "reasoning", text: (delta.reasoning_content as string | undefined) || "" } |
| 105 | + } |
| 106 | + |
| 107 | + if (chunk.usage) { |
| 108 | + lastUsage = chunk.usage |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + if (lastUsage) { |
| 113 | + const inputTokens = lastUsage.prompt_tokens || 0 |
| 114 | + const outputTokens = lastUsage.completion_tokens || 0 |
| 115 | + const cacheWriteTokens = lastUsage.prompt_tokens_details?.cached_tokens || 0 |
| 116 | + const cacheReadTokens = 0 |
| 117 | + |
| 118 | + const totalCost = calculateApiCostOpenAI(info, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens) |
| 119 | + |
| 120 | + const usage: ApiStreamUsageChunk = { |
| 121 | + type: "usage", |
| 122 | + inputTokens, |
| 123 | + outputTokens, |
| 124 | + cacheWriteTokens: cacheWriteTokens || undefined, |
| 125 | + cacheReadTokens: cacheReadTokens || undefined, |
| 126 | + totalCost, |
| 127 | + } |
| 128 | + |
| 129 | + yield usage |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + async completePrompt(prompt: string): Promise<string> { |
| 134 | + const { id: modelId } = this.getModel() |
| 135 | + |
| 136 | + try { |
| 137 | + const response = await this.client.chat.completions.create({ |
| 138 | + model: modelId, |
| 139 | + messages: [{ role: "user", content: prompt }], |
| 140 | + stream: false, |
| 141 | + }) |
| 142 | + |
| 143 | + return response.choices[0]?.message?.content || "" |
| 144 | + } catch (error) { |
| 145 | + throw new Error(`CometAPI completion error: ${error}`) |
| 146 | + } |
| 147 | + } |
| 148 | +} |
0 commit comments