-
Notifications
You must be signed in to change notification settings - Fork 2.5k
feat: add CometAPI as new model provider #7708
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5dd0f70
feat: add CometAPI as new model provider
TensorNull e676bf7
fix: update CometAPI key link text for clarity
TensorNull e214c05
Update src/api/providers/cometapi.ts
TensorNull 9f2baa0
fix: improve error handling and logging for CometAPI model fetching
TensorNull File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import type { ModelInfo } from "../model.js" | ||
|
|
||
| export type CometAPIModelId = string | ||
|
|
||
| export const cometApiDefaultModelId: CometAPIModelId = "claude-sonnet-4-20250514" | ||
|
|
||
| export const cometApiDefaultModelInfo: ModelInfo = { | ||
| maxTokens: undefined, // Let system determine based on contextWindow | ||
| contextWindow: 200000, // Reasonable default for modern models | ||
| supportsImages: false, | ||
| supportsPromptCache: false, | ||
| // Intentionally not setting inputPrice/outputPrice | ||
| } | ||
|
|
||
| // Fallback models for when API is unavailable | ||
| // Small helper to create a map of id -> default info | ||
| const createModelMap = (ids: readonly CometAPIModelId[]): Record<CometAPIModelId, ModelInfo> => | ||
| Object.fromEntries(ids.map((id) => [id, { ...cometApiDefaultModelInfo }])) as Record<CometAPIModelId, ModelInfo> | ||
|
|
||
| // Single, complete list for readability and easy maintenance | ||
| const COMET_FALLBACK_MODEL_IDS = [ | ||
| // OpenAI series | ||
| "gpt-5-chat-latest", | ||
| "gpt-5-mini", | ||
| "gpt-5-nano", | ||
| "gpt-4.1-mini", | ||
| "gpt-4o-mini", | ||
|
|
||
| // Claude series | ||
| "claude-opus-4-1-20250805", | ||
| "claude-sonnet-4-20250514", | ||
| "claude-3-7-sonnet-latest", | ||
| "claude-3-5-haiku-latest", | ||
|
|
||
| // Gemini series | ||
| "gemini-2.5-pro", | ||
| "gemini-2.5-flash", | ||
| "gemini-2.0-flash", | ||
|
|
||
| // DeepSeek series | ||
| "deepseek-v3.1", | ||
| "deepseek-r1-0528", | ||
| "deepseek-reasoner", | ||
|
|
||
| // Other models | ||
| "grok-4-0709", | ||
| "qwen3-30b-a3b", | ||
| "qwen3-coder-plus-2025-07-22", | ||
| ] as const satisfies readonly CometAPIModelId[] | ||
|
|
||
| export const cometApiModels: Record<CometAPIModelId, ModelInfo> = createModelMap(COMET_FALLBACK_MODEL_IDS) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import { Anthropic } from "@anthropic-ai/sdk" | ||
| import OpenAI from "openai" | ||
|
|
||
| import { cometApiDefaultModelId, cometApiDefaultModelInfo, cometApiModels } from "@roo-code/types" | ||
|
|
||
| import type { ApiHandlerOptions } from "../../shared/api" | ||
| import { calculateApiCostOpenAI } from "../../shared/cost" | ||
|
|
||
| import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" | ||
| import { convertToOpenAiMessages } from "../transform/openai-format" | ||
| import { getModelParams } from "../transform/model-params" | ||
|
|
||
| import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata } from "../index" | ||
| import { RouterProvider } from "./router-provider" | ||
|
|
||
| export class CometAPIHandler extends RouterProvider implements SingleCompletionHandler { | ||
| constructor(options: ApiHandlerOptions) { | ||
| super({ | ||
| options: { | ||
| ...options, | ||
| // Add custom headers for CometAPI | ||
| openAiHeaders: { | ||
| "HTTP-Referer": "https://github.com/RooVetGit/Roo-Code", | ||
TensorNull marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "X-Title": "Roo Code", | ||
| ...(options.openAiHeaders || {}), | ||
| }, | ||
| }, | ||
| name: "cometapi", | ||
| baseURL: options.cometApiBaseUrl || "https://api.cometapi.com/v1", | ||
| apiKey: options.cometApiKey || "not-provided", | ||
| modelId: options.cometApiModelId, | ||
| defaultModelId: cometApiDefaultModelId, | ||
| defaultModelInfo: cometApiDefaultModelInfo, | ||
| }) | ||
|
|
||
| // Initialize with fallback models to ensure we always have models available | ||
| this.models = { ...cometApiModels } | ||
| } | ||
|
|
||
| public override async fetchModel() { | ||
| // Fetch dynamic models from API, but keep fallback models if API fails | ||
| try { | ||
| const apiModels = await super.fetchModel() | ||
| // Merge API models with fallback models | ||
| this.models = { ...cometApiModels, ...this.models } | ||
| return apiModels | ||
| } catch (error) { | ||
| console.warn("CometAPI: Failed to fetch models from API, using fallback models", error) | ||
| // Return default model using fallback models | ||
| return this.getModel() | ||
| } | ||
| } | ||
|
|
||
| override getModel() { | ||
| const id = this.options.cometApiModelId ?? cometApiDefaultModelId | ||
| const info = this.models[id] ?? cometApiDefaultModelInfo | ||
|
|
||
| const params = getModelParams({ | ||
| format: "openai", | ||
| modelId: id, | ||
| model: info, | ||
| settings: this.options, | ||
| }) | ||
|
|
||
| return { id, info, ...params } | ||
| } | ||
|
|
||
| override async *createMessage( | ||
| systemPrompt: string, | ||
| messages: Anthropic.Messages.MessageParam[], | ||
| _metadata?: ApiHandlerCreateMessageMetadata, | ||
| ): ApiStream { | ||
| // Ensure we have up-to-date model metadata | ||
| await this.fetchModel() | ||
| const { id: modelId, info, reasoningEffort } = this.getModel() | ||
|
|
||
| const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { | ||
| model: modelId, | ||
| messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)], | ||
| stream: true, | ||
| stream_options: { include_usage: true }, | ||
| reasoning_effort: reasoningEffort, | ||
| } as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming | ||
|
|
||
| if (this.supportsTemperature(modelId)) { | ||
| requestOptions.temperature = this.options.modelTemperature ?? 0 | ||
| } | ||
|
|
||
| if (this.options.includeMaxTokens === true && info.maxTokens) { | ||
| ;(requestOptions as any).max_completion_tokens = this.options.modelMaxTokens || info.maxTokens | ||
| } | ||
|
|
||
| const { data: stream } = await this.client.chat.completions.create(requestOptions).withResponse() | ||
|
|
||
| let lastUsage: OpenAI.CompletionUsage | undefined | ||
| for await (const chunk of stream) { | ||
| const delta = chunk.choices[0]?.delta | ||
|
|
||
| if (delta?.content) { | ||
| yield { type: "text", text: delta.content } | ||
| } | ||
|
|
||
| if (delta && "reasoning_content" in delta && delta.reasoning_content) { | ||
| yield { type: "reasoning", text: (delta.reasoning_content as string | undefined) || "" } | ||
| } | ||
|
|
||
| if (chunk.usage) { | ||
| lastUsage = chunk.usage | ||
| } | ||
| } | ||
|
|
||
| if (lastUsage) { | ||
| const inputTokens = lastUsage.prompt_tokens || 0 | ||
| const outputTokens = lastUsage.completion_tokens || 0 | ||
| const cacheWriteTokens = lastUsage.prompt_tokens_details?.cached_tokens || 0 | ||
| const cacheReadTokens = 0 | ||
|
|
||
| const totalCost = calculateApiCostOpenAI(info, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens) | ||
|
|
||
| const usage: ApiStreamUsageChunk = { | ||
| type: "usage", | ||
| inputTokens, | ||
| outputTokens, | ||
| cacheWriteTokens: cacheWriteTokens || undefined, | ||
| cacheReadTokens: cacheReadTokens || undefined, | ||
| totalCost, | ||
| } | ||
|
|
||
| yield usage | ||
| } | ||
| } | ||
|
|
||
| async completePrompt(prompt: string): Promise<string> { | ||
| const { id: modelId } = this.getModel() | ||
|
|
||
| try { | ||
| const response = await this.client.chat.completions.create({ | ||
| model: modelId, | ||
| messages: [{ role: "user", content: prompt }], | ||
| stream: false, | ||
| }) | ||
|
|
||
| return response.choices[0]?.message?.content || "" | ||
| } catch (error) { | ||
| throw new Error(`CometAPI completion error: ${error}`) | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is a 200k context window a reasonable default for all models? This seems quite high and might not be accurate for many models. Consider using a more conservative default like 8192 or 16384.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here I choose the same default parameters as LiteLLM, which will be improved after the model list interface is upgraded