model selector
This commit is contained in:
parent
d8f6e6caf2
commit
4393e28cab
8 changed files with 424 additions and 4 deletions
|
|
@ -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",
|
||||
|
|
|
|||
127
src/services/ModelService.test.ts
Normal file
127
src/services/ModelService.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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<ModelServiceState> {
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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) {
|
||||
|
|
|
|||
73
src/ui/ModelSelector.tsx
Normal file
73
src/ui/ModelSelector.tsx
Normal file
|
|
@ -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<ModelSelectorProps> = ({
|
||||
onSelect,
|
||||
onCancel,
|
||||
}) => {
|
||||
const [models, setModels] = useState<ModelOption[]>([]);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [currentModelIndex, setCurrentModelIndex] = useState<number>(-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 (
|
||||
<Selector
|
||||
title="Select Model"
|
||||
options={models}
|
||||
selectedIndex={selectedIndex}
|
||||
loading={loading}
|
||||
error={error}
|
||||
loadingMessage="Loading available models..."
|
||||
currentId={currentModelIndex >= 0 && models[currentModelIndex] ? models[currentModelIndex].id : null}
|
||||
onSelect={onSelect}
|
||||
onCancel={onCancel}
|
||||
onNavigate={setSelectedIndex}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModelSelector;
|
||||
|
|
@ -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<TUIChatProps> = ({
|
|||
additionalRules,
|
||||
onShowOrgSelector: () => showOrganizationSelector(),
|
||||
onShowConfigSelector: () => showConfigSelectorUI(),
|
||||
onShowModelSelector: () => showModelSelectorUI(),
|
||||
onLoginPrompt: handleLoginPrompt,
|
||||
onReload: handleReload,
|
||||
// Remote mode configuration
|
||||
|
|
@ -187,6 +190,17 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
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<TUIChatProps> = ({
|
|||
const isInputDisabled =
|
||||
showOrgSelector ||
|
||||
showConfigSelector ||
|
||||
showModelSelector ||
|
||||
!!loginPrompt ||
|
||||
isShowingFreeTrialTransition ||
|
||||
!!activePermissionRequest;
|
||||
|
|
@ -296,6 +311,14 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
/>
|
||||
)}
|
||||
|
||||
{/* Model selector - shows above input when active */}
|
||||
{showModelSelector && (
|
||||
<ModelSelector
|
||||
onSelect={handleModelSelect}
|
||||
onCancel={handleModelCancel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Free trial transition UI - replaces input when active */}
|
||||
{isShowingFreeTrialTransition && (
|
||||
<FreeTrialTransitionUI
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ interface UseChatProps {
|
|||
additionalRules?: string[];
|
||||
onShowOrgSelector: () => void;
|
||||
onShowConfigSelector: () => void;
|
||||
onShowModelSelector?: () => void;
|
||||
onLoginPrompt?: (promptText: string) => Promise<string>;
|
||||
onReload?: () => Promise<void>;
|
||||
// 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"
|
||||
|
|
|
|||
71
src/ui/hooks/useModelSelector.ts
Normal file
71
src/ui/hooks/useModelSelector.ts
Normal file
|
|
@ -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<ModelServiceState>(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,
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue