LiteLLM provider dynamic model fetching (#7679)

* add dynamic model fetching for litellm provider and get rid of manual model config; also implement dynamic modelinfo lookup

* don't clear the models list when a fetch fails
This commit is contained in:
celestial-vault authored and GitHub committed 2025-11-26 10:54:51 -08:00
1 parent 22c22a1cfc
commit 550428eabd
12 files changed
+349 -261

No files matched your search

+5
View File
@@ -27,8 +27,12 @@ service ModelsService {
rpc refreshRequestyModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns Hicap models
rpc refreshHicapModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns LiteLLM models
rpc refreshLiteLlmModelsRpc(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Subscribe to OpenRouter models updates
rpc subscribeToOpenRouterModels(EmptyRequest) returns (stream OpenRouterCompatibleModelInfo);
// Subscribe to LiteLLM models updates
rpc subscribeToLiteLlmModels(EmptyRequest) returns (stream OpenRouterCompatibleModelInfo);
// Updates API configuration (legacy - uses combined configuration)
rpc updateApiConfigurationProto(UpdateApiConfigurationRequest) returns (Empty);
// Updates API configuration (new - uses separate options and secrets)
@@ -98,6 +102,7 @@ message OpenRouterModelInfo {
repeated ModelTier tiers = 12;
optional string name = 13;
optional double temperature = 14;
optional bool supports_reasoning = 15;
}
// Shared response message for model information
+81 -49
View File
@@ -1,6 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
import { StateManager } from "@/core/storage/StateManager"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { isAnthropicModelId } from "@/utils/model-utils"
@@ -19,6 +20,14 @@ interface LiteLlmHandlerOptions extends CommonApiHandlerOptions {
ulid?: string
}
/**
* Extended chat completion parameters that include LiteLLM-specific options
* not present in the standard OpenAI SDK types
*/
interface LiteLlmChatCompletionCreateParams extends OpenAI.Chat.ChatCompletionCreateParamsStreaming {
drop_params?: boolean
}
export interface LiteLlmModelInfoResponse {
data: Array<{
model_name: string
@@ -37,6 +46,54 @@ export interface LiteLlmModelInfoResponse {
}>
}
/**
* Exported utility function to fetch LiteLLM model info
* @param baseUrl The base URL for the LiteLLM API
* @param apiKey The API key for authentication
* @returns The model info response or undefined if fetch fails
*/
export async function fetchLiteLlmModelsInfo(baseUrl: string, apiKey: string): Promise<LiteLlmModelInfoResponse | undefined> {
// Handle base URLs that already include /v1 to avoid double /v1/v1/
const normalizedBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`
const url = `${normalizedBaseUrl}/model/info`
try {
const response = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
"x-litellm-api-key": apiKey,
},
})
if (response.ok) {
const data: LiteLlmModelInfoResponse = await response.json()
return data
} else {
console.error("Failed to fetch LiteLLM model info:", response.statusText)
// Try with Authorization header instead
const retryResponse = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
Authorization: `Bearer ${apiKey}`,
},
})
if (retryResponse.ok) {
const data: LiteLlmModelInfoResponse = await retryResponse.json()
return data
} else {
console.error("Failed to fetch LiteLLM model info with Authorization header:", retryResponse.statusText)
throw new Error(`Failed to fetch LiteLLM model info: ${retryResponse.statusText}`)
}
}
} catch (error) {
console.error("Error fetching LiteLLM model info:", error)
throw error
}
}
export class LiteLlmHandler implements ApiHandler {
private options: LiteLlmHandlerOptions
private client: OpenAI | undefined
@@ -84,49 +141,14 @@ export class LiteLlmHandler implements ApiHandler {
}
const client = this.ensureClient()
// Handle base URLs that already include /v1 to avoid double /v1/v1/
const baseUrl = client.baseURL.endsWith("/v1") ? client.baseURL : `${client.baseURL}/v1`
const url = `${baseUrl}/model/info`
const data = await fetchLiteLlmModelsInfo(client.baseURL, this.options.liteLlmApiKey || "")
try {
const response = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
"x-litellm-api-key": this.options.liteLlmApiKey || "",
},
})
if (response.ok) {
const data: LiteLlmModelInfoResponse = await response.json()
this.modelInfoCache = data
this.modelInfoCacheTimestamp = now
return data
} else {
console.warn("Failed to fetch LiteLLM model info:", response.statusText)
// Try with Authorization header instead
const retryResponse = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
Authorization: `Bearer ${this.options.liteLlmApiKey || ""}`,
},
})
if (retryResponse.ok) {
const data: LiteLlmModelInfoResponse = await retryResponse.json()
this.modelInfoCache = data
this.modelInfoCacheTimestamp = now
return data
} else {
console.warn("Failed to fetch LiteLLM model info with Authorization header:", retryResponse.statusText)
return undefined
}
}
} catch (error) {
console.warn("Error fetching LiteLLM model info:", error)
return undefined
if (data) {
this.modelInfoCache = data
this.modelInfoCacheTimestamp = now
}
return data
}
private async getModelCostInfo(publicModelName: string): Promise<{
@@ -186,6 +208,7 @@ export class LiteLlmHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam | Anthropic.Messages.TextBlockParam = {
role: "system",
@@ -193,23 +216,23 @@ export class LiteLlmHandler implements ApiHandler {
}
const modelId = this.options.liteLlmModelId || liteLlmDefaultModelId
const isOminiModel = modelId.includes("o1-mini") || modelId.includes("o3-mini") || modelId.includes("o4-mini")
const isCodexModel = modelId.toLowerCase().includes("codex")
// Configuration for extended thinking
const budgetTokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = budgetTokens !== 0
const thinkingConfig = reasoningOn ? { type: "enabled", budget_tokens: budgetTokens } : undefined
let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 0
let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 1
if ((isOminiModel || isAnthropicModelId(modelId)) && reasoningOn) {
temperature = undefined // OAI omni and Anthropic extended thinking mode doesn't support temperature
}
const modelInfo = await this.modelInfo(modelId)
// Automatically enable caching if the model supports it
const cacheControl =
this.options.liteLlmUsePromptCache && Boolean(modelInfo?.model_info.supports_prompt_caching)
? { cache_control: { type: "ephemeral" } }
: undefined
(modelInfo?.model_info.supports_prompt_caching ?? false) ? { cache_control: { type: "ephemeral" } } : undefined
if (cacheControl) {
// Add cache_control to system message if enabled
@@ -277,10 +300,11 @@ export class LiteLlmHandler implements ApiHandler {
messages: [systemMessage, ...enhancedMessages],
temperature,
stream: true,
stream_options: { include_usage: true },
drop_params: true,
...(!isCodexModel && { stream_options: { include_usage: true } }), // Codex models are only on the responses api, which doesn't take the stream_options parameter. we will need to migrate to the responses api for this to work
...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable
...(this.options.ulid && { litellm_session_id: `cline-${this.options.ulid}` }), // Add session ID for LiteLLM tracking
})
} as LiteLlmChatCompletionCreateParams)
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
@@ -344,9 +368,17 @@ export class LiteLlmHandler implements ApiHandler {
}
getModel() {
const modelId = this.options.liteLlmModelId || liteLlmDefaultModelId
// Try to get model info from StateManager cache first
const cachedModelInfo = StateManager.get().getModelInfo("liteLlm", modelId)
// Fall back to provided model info or defaults if not in cache
const modelInfo = cachedModelInfo || liteLlmModelInfoSaneDefaults
return {
id: this.options.liteLlmModelId || liteLlmDefaultModelId,
info: this.options.liteLlmModelInfo || liteLlmModelInfoSaneDefaults,
id: modelId,
info: modelInfo,
}
}
}
@@ -0,0 +1,78 @@
import type { ModelInfo } from "@shared/api"
import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
import { fetchLiteLlmModelsInfo } from "@/core/api/providers/litellm"
import { StateManager } from "@/core/storage/StateManager"
import { toProtobufModels } from "@/shared/proto-conversions/models/typeConversion"
import { sendLiteLlmModelsEvent } from "./subscribeToLiteLlmModels"
/**
* Core function: Refreshes the LiteLLM models and returns application types
* @param controller The controller instance
* @returns Record of model ID to ModelInfo (application types)
*/
export async function refreshLiteLlmModels(): Promise<Record<string, ModelInfo>> {
const models: Record<string, ModelInfo> = {}
const stateManager = StateManager.get()
try {
// Get the LiteLLM configuration
const apiConfiguration = stateManager.getApiConfiguration()
const baseUrl = apiConfiguration.liteLlmBaseUrl || ""
const apiKey = apiConfiguration.liteLlmApiKey
if (!apiKey) {
throw new Error("LiteLLM API key is not configured or is invalid")
}
// Use the shared utility function to fetch model info
const data = await fetchLiteLlmModelsInfo(baseUrl, apiKey)
if (data?.data) {
for (const rawModel of data.data) {
const modelInfo: ModelInfo = {
name: rawModel.model_name,
maxTokens: rawModel.model_info?.max_output_tokens ?? rawModel.model_info?.max_tokens ?? 4096,
contextWindow: rawModel.model_info?.max_input_tokens ?? rawModel.model_info?.max_tokens ?? 8192,
supportsImages: rawModel.model_info?.supports_vision ?? false,
supportsPromptCache: rawModel.model_info?.supports_prompt_caching ?? false,
supportsReasoning: rawModel.model_info?.supports_reasoning ?? false,
inputPrice: rawModel.model_info?.input_cost_per_token
? rawModel.model_info.input_cost_per_token * 1_000_000
: 0,
outputPrice: rawModel.model_info?.output_cost_per_token
? rawModel.model_info.output_cost_per_token * 1_000_000
: 0,
cacheWritesPrice: rawModel.model_info?.cache_creation_input_token_cost
? rawModel.model_info.cache_creation_input_token_cost * 1_000_000
: undefined,
cacheReadsPrice: rawModel.model_info?.cache_read_input_token_cost
? rawModel.model_info.cache_read_input_token_cost * 1_000_000
: undefined,
description: undefined,
}
models[rawModel.model_name] = modelInfo
}
}
} catch (error) {
console.error("Error fetching LiteLLM models:", error)
throw error
}
// Store in StateManager's in-memory cache
StateManager.get().setModelsCache("liteLlm", models)
// Send event to subscribers
try {
await sendLiteLlmModelsEvent(
OpenRouterCompatibleModelInfo.create({
models: toProtobufModels(models),
}),
)
} catch (error) {
console.error("Error sending LiteLLM models event:", error)
}
return models
}
@@ -0,0 +1,21 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
import { toProtobufModels } from "../../../shared/proto-conversions/models/typeConversion"
import type { Controller } from "../index"
import { refreshLiteLlmModels } from "./refreshLiteLlmModels"
/**
* Refreshes LiteLLM models and returns protobuf types for gRPC
* @param controller The controller instance
* @param request Empty request (unused but required for gRPC signature)
* @returns OpenRouterCompatibleModelInfo with protobuf types
*/
export async function refreshLiteLlmModelsRpc(
_controller: Controller,
_request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
const models = await refreshLiteLlmModels()
return OpenRouterCompatibleModelInfo.create({
models: toProtobufModels(models),
})
}
@@ -0,0 +1,56 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active LiteLLM models subscriptions
const activeLiteLlmModelsSubscriptions = new Set<StreamingResponseHandler<OpenRouterCompatibleModelInfo>>()
/**
* Subscribe to LiteLLM models events
* @param controller The controller instance
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToLiteLlmModels(
_controller: Controller,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<OpenRouterCompatibleModelInfo>,
requestId?: string,
): Promise<void> {
// Add this subscription to the active subscriptions
activeLiteLlmModelsSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeLiteLlmModelsSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "liteLlmModels_subscription" }, responseStream)
}
}
/**
* Send a LiteLLM models event to all active subscribers
* @param models The LiteLLM models to send
*/
export async function sendLiteLlmModelsEvent(models: OpenRouterCompatibleModelInfo): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeLiteLlmModelsSubscriptions).map(async (responseStream) => {
try {
await responseStream(
models,
false, // Not the last message
)
} catch (error) {
console.error("Error sending LiteLLM models event:", error)
// Remove the subscription if there was an error
activeLiteLlmModelsSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
@@ -8,6 +8,7 @@ import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplace
import { refreshBasetenModels } from "../models/refreshBasetenModels"
import { refreshGroqModels } from "../models/refreshGroqModels"
import { refreshHicapModels } from "../models/refreshHicapModels"
import { refreshLiteLlmModels } from "../models/refreshLiteLlmModels"
import { refreshOpenRouterModels } from "../models/refreshOpenRouterModels"
import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels"
@@ -194,6 +195,9 @@ export async function initializeWebview(controller: Controller, _request: EmptyR
}
})
// State update event sent within the refreshLiteLlmModels function
refreshLiteLlmModels()
// GUI relies on model info to be up-to-date to provide the most accurate pricing, so we need to fetch the latest details on launch.
// We do this for all users since many users switch between api providers and if they were to switch back to openrouter it would be showing outdated model info if we hadn't retrieved the latest at this point
// (see normalizeApiConfiguration > openrouter)
+22 -3
View File
@@ -55,6 +55,7 @@ export class StateManager {
huaweiCloudMaasModels: Record<string, ModelInfo> | null
hicapModels: Record<string, ModelInfo> | null
aihubmixModels: Record<string, ModelInfo> | null
liteLlmModels: Record<string, ModelInfo> | null
} = {
openRouterModels: null,
groqModels: null,
@@ -64,6 +65,7 @@ export class StateManager {
huaweiCloudMaasModels: null,
hicapModels: null,
aihubmixModels: null,
liteLlmModels: null,
}
// Debounced persistence state
@@ -374,7 +376,16 @@ export class StateManager {
* Set models cache for a specific provider (in-memory only, not persisted)
*/
setModelsCache(
provider: "openRouter" | "groq" | "baseten" | "huggingFace" | "requesty" | "huaweiCloudMaas" | "hicap" | "aihubmix",
provider:
| "openRouter"
| "groq"
| "baseten"
| "huggingFace"
| "requesty"
| "huaweiCloudMaas"
| "hicap"
| "aihubmix"
| "liteLlm",
models: Record<string, ModelInfo>,
): void {
const cacheKey = `${provider}Models` as keyof typeof this.modelInfoCache
@@ -385,11 +396,19 @@ export class StateManager {
* Get model info by provider and model ID (from in-memory cache)
*/
getModelInfo(
provider: "openRouter" | "groq" | "baseten" | "huggingFace" | "requesty" | "huaweiCloudMaas" | "hicap" | "aihubmix",
provider:
| "openRouter"
| "groq"
| "baseten"
| "huggingFace"
| "requesty"
| "huaweiCloudMaas"
| "hicap"
| "aihubmix"
| "liteLlm",
modelId: string,
): ModelInfo | undefined {
const cacheKey = `${provider}Models` as keyof typeof this.modelInfoCache
console.log("[OpenRouter] modelInfoCache:", this.modelInfoCache)
return this.modelInfoCache[cacheKey]?.[modelId]
}
+1
View File
@@ -236,6 +236,7 @@ export interface ModelInfo {
contextWindow?: number
supportsImages?: boolean
supportsPromptCache: boolean // this value is hardcoded for now
supportsReasoning?: boolean // Whether the model supports reasoning/thinking mode
inputPrice?: number // Keep for non-tiered input models
outputPrice?: number // Keep for non-tiered output models
thinkingConfig?: {
@@ -48,6 +48,7 @@ export function fromProtobufModelInfo(protoInfo: OpenRouterModelInfo): ModelInfo
contextWindow: protoInfo.contextWindow,
supportsImages: protoInfo.supportsImages,
supportsPromptCache: protoInfo.supportsPromptCache,
supportsReasoning: protoInfo.supportsReasoning,
inputPrice: protoInfo.inputPrice,
outputPrice: protoInfo.outputPrice,
cacheWritesPrice: protoInfo.cacheWritesPrice,
@@ -68,6 +69,7 @@ export function toProtobufModelInfo(modelInfo: ModelInfo): OpenRouterModelInfo {
contextWindow: modelInfo.contextWindow,
supportsImages: modelInfo.supportsImages,
supportsPromptCache: modelInfo.supportsPromptCache,
supportsReasoning: modelInfo.supportsReasoning,
inputPrice: modelInfo.inputPrice,
outputPrice: modelInfo.outputPrice,
cacheWritesPrice: modelInfo.cacheWritesPrice,
@@ -1,15 +1,15 @@
import { liteLlmModelInfoSaneDefaults } from "@shared/api"
import { UpdateApiConfigurationRequestNew } from "@shared/proto/index.cline"
import { Mode } from "@shared/storage/types"
import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { useState } from "react"
import { VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { useEffect } from "react"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ModelsServiceClient } from "@/services/grpc-client"
import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles"
import { DebouncedTextField } from "../common/DebouncedTextField"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
/**
* Props for the LiteLlmProvider component
@@ -20,20 +20,36 @@ interface LiteLlmProviderProps {
currentMode: Mode
}
/**
* The LiteLLM provider configuration component
*/
export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: LiteLlmProviderProps) => {
const { apiConfiguration } = useExtensionState()
const { apiConfiguration, liteLlmModels, refreshLiteLlmModels } = useExtensionState()
const { handleModeFieldsChange } = useApiConfigurationHandlers()
const modeFields = getModeSpecificFields(apiConfiguration, currentMode)
// Get the normalized configuration
const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration, currentMode)
// Get the normalized configuration with model info
const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration, currentMode, liteLlmModels)
// Get mode-specific fields
const { liteLlmModelId, liteLlmModelInfo } = getModeSpecificFields(apiConfiguration, currentMode)
// Refresh models on mount
useEffect(() => {
refreshLiteLlmModels()
}, [refreshLiteLlmModels, apiConfiguration?.liteLlmApiKey])
// Local state for collapsible model configuration section
const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false)
// Handle model change
const handleModelChange = (e: any) => {
const newModelId = e.target.value
const modelInfo = liteLlmModels[newModelId]
handleModeFieldsChange(
{
liteLlmModelId: { plan: "planModeLiteLlmModelId", act: "actModeLiteLlmModelId" },
liteLlmModelInfo: { plan: "planModeLiteLlmModelInfo", act: "actModeLiteLlmModelInfo" },
},
{
liteLlmModelId: newModelId,
liteLlmModelInfo: modelInfo,
},
currentMode,
)
}
return (
<div>
@@ -75,58 +91,20 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite
type="password">
<span style={{ fontWeight: 500 }}>API Key</span>
</DebouncedTextField>
<DebouncedTextField
initialValue={liteLlmModelId || ""}
onChange={async (value) => {
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create(
currentMode === "plan"
? {
updates: { options: { planModeLiteLlmModelId: value } },
updateMask: ["options.planModeLiteLlmModelId"],
}
: {
updates: { options: { actModeLiteLlmModelId: value } },
updateMask: ["options.actModeLiteLlmModelId"],
},
),
)
}}
placeholder={"e.g. anthropic/claude-sonnet-4-20250514"}
style={{ width: "100%" }}>
<span style={{ fontWeight: 500 }}>Model ID</span>
</DebouncedTextField>
{showModelOptions && (
<>
<ModelSelector
label="Model"
models={liteLlmModels}
onChange={handleModelChange}
selectedModelId={selectedModelId}
/>
<div style={{ display: "flex", flexDirection: "column", marginTop: 10, marginBottom: 10 }}>
{selectedModelInfo.supportsPromptCache && (
<>
<VSCodeCheckbox
checked={apiConfiguration?.liteLlmUsePromptCache || false}
onChange={async (e: any) => {
const isChecked = e.target.checked === true
{selectedModelInfo?.supportsReasoning && <ThinkingBudgetSlider currentMode={currentMode} />}
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create({
updates: {
options: {
liteLlmUsePromptCache: isChecked,
},
},
updateMask: ["options.liteLlmUsePromptCache"],
}),
)
}}
style={{ fontWeight: 500, color: "var(--vscode-charts-green)" }}>
Use prompt caching (GA)
</VSCodeCheckbox>
<p style={{ fontSize: "12px", marginTop: 3, color: "var(--vscode-charts-green)" }}>
Prompt caching requires a supported provider and model
</p>
</>
)}
</div>
<ThinkingBudgetSlider currentMode={currentMode} />
<ModelInfoView isPopup={isPopup} modelInfo={selectedModelInfo} selectedModelId={selectedModelId} />
</>
)}
<p
style={{
fontSize: "12px",
@@ -141,144 +119,6 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite
</VSCodeLink>
</p>
<div
onClick={() => setModelConfigurationSelected((val) => !val)}
style={{
color: getAsVar(VSC_DESCRIPTION_FOREGROUND),
display: "flex",
margin: "10px 0",
cursor: "pointer",
alignItems: "center",
}}>
<span
className={`codicon ${modelConfigurationSelected ? "codicon-chevron-down" : "codicon-chevron-right"}`}
style={{
marginRight: "4px",
}}></span>
<span
style={{
fontWeight: 700,
textTransform: "uppercase",
}}>
Model Configuration
</span>
</div>
{modelConfigurationSelected && (
<>
<VSCodeCheckbox
checked={!!liteLlmModelInfo?.supportsImages}
onChange={async (e: any) => {
const isChecked = e.target.checked === true
const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults }
modelInfo.supportsImages = isChecked
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create(
currentMode === "plan"
? {
updates: { options: { planModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.planModeLiteLlmModelInfo"],
}
: {
updates: { options: { actModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.actModeLiteLlmModelInfo"],
},
),
)
}}>
Supports Images
</VSCodeCheckbox>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={
liteLlmModelInfo?.contextWindow
? liteLlmModelInfo.contextWindow.toString()
: (liteLlmModelInfoSaneDefaults.contextWindow?.toString() ?? "")
}
onChange={async (value) => {
const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults }
modelInfo.contextWindow = Number(value)
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create(
currentMode === "plan"
? {
updates: { options: { planModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.planModeLiteLlmModelInfo"],
}
: {
updates: { options: { actModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.actModeLiteLlmModelInfo"],
},
),
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>Context Window Size</span>
</DebouncedTextField>
<DebouncedTextField
initialValue={
liteLlmModelInfo?.maxTokens
? liteLlmModelInfo.maxTokens.toString()
: (liteLlmModelInfoSaneDefaults.maxTokens?.toString() ?? "")
}
onChange={async (value) => {
const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults }
modelInfo.maxTokens = Number(value)
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create(
currentMode === "plan"
? {
updates: { options: { planModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.planModeLiteLlmModelInfo"],
}
: {
updates: { options: { actModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.actModeLiteLlmModelInfo"],
},
),
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>Max Output Tokens</span>
</DebouncedTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={
liteLlmModelInfo?.temperature !== undefined
? liteLlmModelInfo.temperature.toString()
: (liteLlmModelInfoSaneDefaults.temperature?.toString() ?? "")
}
onChange={async (value) => {
const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults }
// Check if the input ends with a decimal point or has trailing zeros after decimal
const _shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0"))
modelInfo.temperature =
value === "" ? liteLlmModelInfoSaneDefaults.temperature : parseFloat(value)
await ModelsServiceClient.updateApiConfiguration(
UpdateApiConfigurationRequestNew.create(
currentMode === "plan"
? {
updates: { options: { planModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.planModeLiteLlmModelInfo"],
}
: {
updates: { options: { actModeLiteLlmModelInfo: modelInfo } },
updateMask: ["options.actModeLiteLlmModelInfo"],
},
),
)
}}>
<span style={{ fontWeight: 500 }}>Temperature</span>
</DebouncedTextField>
</div>
</>
)}
<p
style={{
fontSize: "12px",
@@ -291,10 +131,6 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite
</VSCodeLink>{" "}
for more information.
</p>
{showModelOptions && (
<ModelInfoView isPopup={isPopup} modelInfo={selectedModelInfo} selectedModelId={selectedModelId} />
)}
</div>
)
}
@@ -83,6 +83,7 @@ export interface NormalizedApiConfig {
export function normalizeApiConfiguration(
apiConfiguration: ApiConfiguration | undefined,
currentMode: Mode,
liteLlmModels?: Record<string, ModelInfo>,
): NormalizedApiConfig {
const provider =
(currentMode === "plan" ? apiConfiguration?.planModeApiProvider : apiConfiguration?.actModeApiProvider) || "anthropic"
@@ -244,12 +245,12 @@ export function normalizeApiConfiguration(
case "litellm":
const liteLlmModelId =
currentMode === "plan" ? apiConfiguration?.planModeLiteLlmModelId : apiConfiguration?.actModeLiteLlmModelId
const liteLlmModelInfo =
currentMode === "plan" ? apiConfiguration?.planModeLiteLlmModelInfo : apiConfiguration?.actModeLiteLlmModelInfo
// model info lookup
const liteLlmModelInfo = liteLlmModels?.[liteLlmModelId || ""]
return {
selectedProvider: provider,
selectedModelId: liteLlmModelId || "",
selectedModelInfo: liteLlmModelInfo || liteLlmModelInfoSaneDefaults,
selectedModelInfo: liteLlmModelInfo || ({} as ModelInfo),
}
case "xai":
return getProviderData(xaiModels, xaiDefaultModelId)
@@ -36,6 +36,7 @@ export interface ExtensionStateContextType extends ExtensionState {
onboardingModels: OnboardingModelGroup | undefined
openRouterModels: Record<string, ModelInfo>
hicapModels: Record<string, ModelInfo>
liteLlmModels: Record<string, ModelInfo>
openAiModels: string[]
requestyModels: Record<string, ModelInfo>
groqModels: Record<string, ModelInfo>
@@ -87,6 +88,7 @@ export interface ExtensionStateContextType extends ExtensionState {
// Refresh functions
refreshOpenRouterModels: () => void
refreshHicapModels: () => void
refreshLiteLlmModels: () => void
setUserInfo: (userInfo?: UserInfo) => void
// Navigation state setters
@@ -250,6 +252,7 @@ export const ExtensionStateContextProvider: React.FC<{
[openRouterDefaultModelId]: openRouterDefaultModelInfo,
})
const [hicapModels, setHicapModels] = useState<Record<string, ModelInfo>>({})
const [liteLlmModels, setLiteLlmModels] = useState<Record<string, ModelInfo>>({})
const [totalTasksSize, setTotalTasksSize] = useState<number | null>(null)
const [availableTerminalProfiles, setAvailableTerminalProfiles] = useState<TerminalProfile[]>([])
@@ -280,6 +283,7 @@ export const ExtensionStateContextProvider: React.FC<{
const partialMessageUnsubscribeRef = useRef<(() => void) | null>(null)
const mcpMarketplaceUnsubscribeRef = useRef<(() => void) | null>(null)
const openRouterModelsUnsubscribeRef = useRef<(() => void) | null>(null)
const liteLlmModelsUnsubscribeRef = useRef<(() => void) | null>(null)
const workspaceUpdatesUnsubscribeRef = useRef<(() => void) | null>(null)
const relinquishControlUnsubscribeRef = useRef<(() => void) | null>(null)
@@ -508,6 +512,20 @@ export const ExtensionStateContextProvider: React.FC<{
},
})
// Subscribe to LiteLLM models updates
liteLlmModelsUnsubscribeRef.current = ModelsServiceClient.subscribeToLiteLlmModels(EmptyRequest.create({}), {
onResponse: (response: OpenRouterCompatibleModelInfo) => {
const models = fromProtobufModels(response.models)
setLiteLlmModels(models)
},
onError: (error) => {
console.error("Error in LiteLLM models subscription:", error)
},
onComplete: () => {
console.log("LiteLLM models subscription completed")
},
})
// Initialize webview using gRPC
UiServiceClient.initializeWebview(EmptyRequest.create({}))
.then(() => {
@@ -608,6 +626,10 @@ export const ExtensionStateContextProvider: React.FC<{
openRouterModelsUnsubscribeRef.current()
openRouterModelsUnsubscribeRef.current = null
}
if (liteLlmModelsUnsubscribeRef.current) {
liteLlmModelsUnsubscribeRef.current()
liteLlmModelsUnsubscribeRef.current = null
}
if (workspaceUpdatesUnsubscribeRef.current) {
workspaceUpdatesUnsubscribeRef.current()
workspaceUpdatesUnsubscribeRef.current = null
@@ -654,6 +676,15 @@ export const ExtensionStateContextProvider: React.FC<{
.catch((error: Error) => console.error("Failed to refresh Hicap models:", error))
}, [])
const refreshLiteLlmModels = useCallback(() => {
ModelsServiceClient.refreshLiteLlmModelsRpc(EmptyRequest.create({}))
.then((response: OpenRouterCompatibleModelInfo) => {
const models = fromProtobufModels(response.models)
setLiteLlmModels(models)
})
.catch((error: Error) => console.error("Failed to refresh LiteLLM models:", error))
}, [])
const contextValue: ExtensionStateContextType = {
...state,
didHydrateState,
@@ -661,6 +692,7 @@ export const ExtensionStateContextProvider: React.FC<{
onboardingModels,
openRouterModels,
hicapModels,
liteLlmModels,
openAiModels,
requestyModels,
groqModels: groqModelsState,
@@ -768,6 +800,7 @@ export const ExtensionStateContextProvider: React.FC<{
setTotalTasksSize,
refreshOpenRouterModels,
refreshHicapModels,
refreshLiteLlmModels,
onRelinquishControl,
setUserInfo: (userInfo?: UserInfo) => setState((prevState) => ({ ...prevState, userInfo })),
expandTaskHeader,