From 4393e28cab3d7e1c6cd82a088b9dc5f81d3e7331 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 26 Jul 2025 21:43:05 -0700 Subject: [PATCH] model selector --- src/commands/commands.ts | 5 ++ src/services/ModelService.test.ts | 127 ++++++++++++++++++++++++++++++ src/services/ModelService.ts | 117 ++++++++++++++++++++++++++- src/slashCommands.ts | 5 ++ src/ui/ModelSelector.tsx | 73 +++++++++++++++++ src/ui/TUIChat.tsx | 23 ++++++ src/ui/hooks/useChat.ts | 7 ++ src/ui/hooks/useModelSelector.ts | 71 +++++++++++++++++ 8 files changed, 424 insertions(+), 4 deletions(-) create mode 100644 src/services/ModelService.test.ts create mode 100644 src/ui/ModelSelector.tsx create mode 100644 src/ui/hooks/useModelSelector.ts diff --git a/src/commands/commands.ts b/src/commands/commands.ts index b245f9655..ab0569f11 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -47,6 +47,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Switch organization", category: "system", }, + { + name: "model", + description: "Switch between available chat models", + category: "system", + }, { name: "config", description: "Switch configuration", diff --git a/src/services/ModelService.test.ts b/src/services/ModelService.test.ts new file mode 100644 index 000000000..e38f810c6 --- /dev/null +++ b/src/services/ModelService.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect, beforeEach } from '@jest/globals'; +import { ModelService } from './ModelService.js'; +import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml'; +import { AuthConfig } from '../auth/workos.js'; + +describe('ModelService', () => { + let modelService: ModelService; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthConfig; + + beforeEach(() => { + modelService = new ModelService(); + + mockAssistant = { + name: 'test-assistant', + version: '1.0.0', + models: [ + { + provider: 'openai', + model: 'gpt-4', + name: 'GPT-4', + apiKey: 'test-key', + roles: ['chat'], + } as ModelConfig, + { + provider: 'anthropic', + model: 'claude-3', + name: 'Claude 3', + apiKey: 'test-key', + roles: ['chat'], + } as ModelConfig, + { + provider: 'openai', + model: 'gpt-3.5', + name: 'GPT-3.5', + apiKey: 'test-key', + roles: ['embed'], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + accessToken: 'test-token', + refreshToken: 'test-refresh', + userEmail: 'test@example.com', + userId: 'test-user', + organizationId: 'test-org', + expiresAt: Date.now() + 3600000, // 1 hour from now + }; + }); + + describe('getAvailableChatModels', () => { + it('should return only models with chat role', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + const models = modelService.getAvailableChatModels(); + + expect(models).toHaveLength(2); + expect(models[0]).toEqual({ + provider: 'openai', + name: 'GPT-4', + index: 0, + }); + expect(models[1]).toEqual({ + provider: 'anthropic', + name: 'Claude 3', + index: 1, + }); + }); + + it('should return empty array when no chat models available', async () => { + mockAssistant.models = [ + { + provider: 'openai', + model: 'text-embedding-ada-002', + name: 'Ada Embeddings', + roles: ['embed'], + } as ModelConfig, + ]; + + await modelService.initialize(mockAssistant, mockAuthConfig); + + const models = modelService.getAvailableChatModels(); + expect(models).toHaveLength(0); + }); + }); + + describe('switchModel', () => { + it('should switch to a different model by index', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + const initialModel = modelService.getModelInfo(); + expect(initialModel?.name).toBe('GPT-4'); + + await modelService.switchModel(1); + + const newModel = modelService.getModelInfo(); + expect(newModel?.name).toBe('Claude 3'); + }); + + it('should throw error for invalid model index', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + await expect(modelService.switchModel(5)).rejects.toThrow('Invalid model index: 5'); + await expect(modelService.switchModel(-1)).rejects.toThrow('Invalid model index: -1'); + }); + + it('should throw error when service not initialized', async () => { + await expect(modelService.switchModel(0)).rejects.toThrow('ModelService not initialized'); + }); + }); + + describe('getCurrentModelIndex', () => { + it('should return correct index of current model', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + expect(modelService.getCurrentModelIndex()).toBe(0); + + await modelService.switchModel(1); + expect(modelService.getCurrentModelIndex()).toBe(1); + }); + + it('should return -1 when no model is set', () => { + expect(modelService.getCurrentModelIndex()).toBe(-1); + }); + }); +}); \ No newline at end of file diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts index a2a84c1a6..d69afa6da 100644 --- a/src/services/ModelService.ts +++ b/src/services/ModelService.ts @@ -1,7 +1,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; import { getLlmApi } from '../config.js'; -import { AuthConfig } from '../auth/workos.js'; +import { AuthConfig, getAccessToken, getOrganizationId } from '../auth/workos.js'; import logger from '../util/logger.js'; import { ModelServiceState } from './types.js'; @@ -14,6 +14,9 @@ export class ModelService { llmApi: null, model: null }; + private availableModels: ModelConfig[] = []; + private assistant: AssistantUnrolled | null = null; + private authConfig: AuthConfig | null = null; /** * Initialize the model service @@ -25,6 +28,12 @@ export class ModelService { logger.debug('Initializing ModelService'); try { + this.assistant = assistant; + this.authConfig = authConfig; + this.availableModels = (assistant.models?.filter((model) => + model && model.roles?.includes("chat") + ) || []) as ModelConfig[]; + const [llmApi, model] = getLlmApi(assistant, authConfig); this.currentState = { @@ -34,7 +43,8 @@ export class ModelService { logger.debug('ModelService initialized successfully', { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed' + modelName: (model as any).name || 'unnamed', + availableModels: this.availableModels.length }); return this.currentState; @@ -61,6 +71,12 @@ export class ModelService { logger.debug('Updating ModelService'); try { + this.assistant = assistant; + this.authConfig = authConfig; + this.availableModels = (assistant.models?.filter((model) => + model && model.roles?.includes("chat") + ) || []) as ModelConfig[]; + const [llmApi, model] = getLlmApi(assistant, authConfig); this.currentState = { @@ -70,7 +86,8 @@ export class ModelService { logger.debug('ModelService updated successfully', { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed' + modelName: (model as any).name || 'unnamed', + availableModels: this.availableModels.length }); return this.currentState; @@ -100,4 +117,96 @@ export class ModelService { name: (this.currentState.model as any).name || 'unnamed' }; } + + /** + * Get list of available chat models + */ + getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> { + return this.availableModels.map((model, index) => ({ + provider: model.provider, + name: (model as any).name || (model as any).model || 'unnamed', + index + })); + } + + /** + * Switch to a different chat model by index + */ + async switchModel(modelIndex: number): Promise { + if (!this.assistant || !this.authConfig) { + throw new Error('ModelService not initialized'); + } + + if (modelIndex < 0 || modelIndex >= this.availableModels.length) { + throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`); + } + + const selectedModel = this.availableModels[modelIndex]; + logger.debug('Switching to model', { + modelIndex, + provider: selectedModel.provider, + name: (selectedModel as any).name || 'unnamed' + }); + + try { + const accessToken = getAccessToken(this.authConfig); + const organizationId = getOrganizationId(this.authConfig); + + const config: LLMConfig = + selectedModel.provider === "continue-proxy" + ? { + provider: selectedModel.provider, + requestOptions: selectedModel.requestOptions, + apiBase: selectedModel.apiBase, + apiKey: accessToken ?? undefined, + env: { + apiKeyLocation: (selectedModel as any).apiKeyLocation, + orgScopeId: organizationId, + proxyUrl: undefined, + }, + } + : { + provider: selectedModel.provider as any, + apiKey: selectedModel.apiKey, + apiBase: selectedModel.apiBase, + requestOptions: selectedModel.requestOptions, + env: selectedModel.env, + }; + + const llmApi = constructLlmApi(config); + + if (!llmApi) { + throw new Error('Failed to initialize LLM with selected model'); + } + + this.currentState = { + llmApi, + model: selectedModel + }; + + logger.debug('Model switched successfully', { + modelProvider: selectedModel.provider, + modelName: (selectedModel as any).name || 'unnamed' + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to switch model:', error); + throw error; + } + } + + /** + * Get current model index + */ + getCurrentModelIndex(): number { + if (!this.currentState.model) { + return -1; + } + + return this.availableModels.findIndex(model => + model.provider === this.currentState.model?.provider && + (model as any).name === (this.currentState.model as any).name + ); + } } \ No newline at end of file diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 1cee4bda6..e9e121c11 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -18,6 +18,7 @@ export async function handleSlashCommands( newInput?: string; clear?: boolean; openConfigSelector?: boolean; + openModelSelector?: boolean; } | null> { // Only trigger slash commands if slash is the very first character if (input.startsWith("/") && input.trim().startsWith("/")) { @@ -102,6 +103,10 @@ export async function handleSlashCommands( }; } + case "model": + // Open model selector UI + return { openModelSelector: true }; + case "org": // Organization switching command if (args.length === 0) { diff --git a/src/ui/ModelSelector.tsx b/src/ui/ModelSelector.tsx new file mode 100644 index 000000000..5cf04a8d3 --- /dev/null +++ b/src/ui/ModelSelector.tsx @@ -0,0 +1,73 @@ +import React, { useEffect, useState } from "react"; +import { services } from "../services/index.js"; +import Selector, { SelectorOption } from "./Selector.js"; + +interface ModelOption extends SelectorOption { + index: number; + provider: string; +} + +interface ModelSelectorProps { + onSelect: (model: ModelOption) => void; + onCancel: () => void; +} + +const ModelSelector: React.FC = ({ + onSelect, + onCancel, +}) => { + const [models, setModels] = useState([]); + const [selectedIndex, setSelectedIndex] = useState(0); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [currentModelIndex, setCurrentModelIndex] = useState(-1); + + useEffect(() => { + const loadModels = async () => { + try { + const availableModels = services.model.getAvailableChatModels(); + const currentIndex = services.model.getCurrentModelIndex(); + + if (availableModels.length === 0) { + setError("No chat models available in the configuration"); + setLoading(false); + return; + } + + const modelOptions: ModelOption[] = availableModels.map((model) => ({ + id: `${model.provider}-${model.name}-${model.index}`, + name: `${model.provider}/${model.name}`, + index: model.index, + provider: model.provider, + })); + + setModels(modelOptions); + setCurrentModelIndex(currentIndex); + setSelectedIndex(Math.max(0, currentIndex)); + setLoading(false); + } catch (err: any) { + setError(err.message || "Failed to load models"); + setLoading(false); + } + }; + + loadModels(); + }, []); + + return ( + = 0 && models[currentModelIndex] ? models[currentModelIndex].id : null} + onSelect={onSelect} + onCancel={onCancel} + onNavigate={setSelectedIndex} + /> + ); +}; + +export default ModelSelector; \ No newline at end of file diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 90bf0da37..749cfaa2c 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -16,9 +16,11 @@ import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; import { useChat } from "./hooks/useChat.js"; import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; +import { useModelSelector } from "./hooks/useModelSelector.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import IntroMessage from "./IntroMessage.js"; import LoadingAnimation from "./LoadingAnimation.js"; +import ModelSelector from "./ModelSelector.js"; import OrganizationSelector from "./OrganizationSelector.js"; import Timer from "./Timer.js"; import UpdateNotification from "./UpdateNotification.js"; @@ -151,6 +153,7 @@ const TUIChat: React.FC = ({ additionalRules, onShowOrgSelector: () => showOrganizationSelector(), onShowConfigSelector: () => showConfigSelectorUI(), + onShowModelSelector: () => showModelSelectorUI(), onLoginPrompt: handleLoginPrompt, onReload: handleReload, // Remote mode configuration @@ -187,6 +190,17 @@ const TUIChat: React.FC = ({ onChatReset: resetChatHistory, }); + const { + showModelSelector, + handleModelSelect, + handleModelCancel, + showModelSelectorUI, + } = useModelSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + }); + // Handle free trial transition completion const handleFreeTrialTransitionComplete = () => { setIsShowingFreeTrialTransition(false); @@ -208,6 +222,7 @@ const TUIChat: React.FC = ({ const isInputDisabled = showOrgSelector || showConfigSelector || + showModelSelector || !!loginPrompt || isShowingFreeTrialTransition || !!activePermissionRequest; @@ -296,6 +311,14 @@ const TUIChat: React.FC = ({ /> )} + {/* Model selector - shows above input when active */} + {showModelSelector && ( + + )} + {/* Free trial transition UI - replaces input when active */} {isShowingFreeTrialTransition && ( void; onShowConfigSelector: () => void; + onShowModelSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; // Remote mode props @@ -44,6 +45,7 @@ export function useChat({ additionalRules, onShowOrgSelector, onShowConfigSelector, + onShowModelSelector, onLoginPrompt, onReload, isRemoteMode = false, @@ -339,6 +341,11 @@ export function useChat({ return; } + if (commandResult.openModelSelector && onShowModelSelector) { + onShowModelSelector(); + return; + } + if (commandResult.clear) { const systemMessage = chatHistory.find( (msg) => msg.role === "system" diff --git a/src/ui/hooks/useModelSelector.ts b/src/ui/hooks/useModelSelector.ts new file mode 100644 index 000000000..c3b3b3d5a --- /dev/null +++ b/src/ui/hooks/useModelSelector.ts @@ -0,0 +1,71 @@ +import { useState } from "react"; +import { services, serviceContainer, SERVICE_NAMES } from "../../services/index.js"; +import { ModelServiceState } from "../../services/types.js"; + +interface ModelOption { + id: string; + name: string; + index: number; + provider: string; +} + +interface UseModelSelectorProps { + onMessage: (message: { + role: string; + content: string; + messageType: "system"; + }) => void; + onModelSwitch?: () => void; +} + +export function useModelSelector({ + onMessage, + onModelSwitch, +}: UseModelSelectorProps) { + const [showModelSelector, setShowModelSelector] = useState(false); + + const handleModelSelect = async (model: ModelOption) => { + setShowModelSelector(false); + + try { + await services.model.switchModel(model.index); + const modelInfo = services.model.getModelInfo(); + + // Update the service container to trigger re-renders + const currentState = services.model.getState(); + serviceContainer.set(SERVICE_NAMES.MODEL, currentState); + + onMessage({ + role: "system", + content: `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`, + messageType: "system", + }); + + // Trigger any additional actions after model switch + if (onModelSwitch) { + onModelSwitch(); + } + } catch (error: any) { + onMessage({ + role: "system", + content: `Failed to switch model: ${error.message}`, + messageType: "system", + }); + } + }; + + const handleModelCancel = () => { + setShowModelSelector(false); + }; + + const showModelSelectorUI = () => { + setShowModelSelector(true); + }; + + return { + showModelSelector, + handleModelSelect, + handleModelCancel, + showModelSelectorUI, + }; +} \ No newline at end of file