An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: separate model selection from search modes
Yoshiki Miura18b07eef4084
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 016e7f0e..cc873ac3 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -67,10 +67,9 @@ export async function POST(req: Request) {const cookieStore = await cookies()- // Select the appropriate model based on configuration and user preferences+ // Select the appropriate model based on model type preferenceconst selectedModel = selectModel({- cookieStore,- searchModeFromRequest: searchMode+ cookieStore})if (!isProviderEnabled(selectedModel.providerId)) {diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 7a847a05..626752ed 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -18,7 +18,7 @@ import { Button } from './ui/button'import { IconLogo } from './ui/icons'import { ActionButtons } from './action-buttons'import { FileUploadButton } from './file-upload-button'-import { ModelSelector } from './model-selector'+import { ModelTypeSelector } from './model-type-selector'import { SearchModeSelector } from './search-mode-selector'import { UploadedFileList } from './uploaded-file-list'@@ -251,9 +251,6 @@ export function ChatPanel({}}/><SearchModeSelector />- {process.env.NEXT_PUBLIC_SHOW_MODEL_SELECTOR === 'true' && (- <ModelSelector models={models || []} />- )}</div><div className="flex items-center gap-2">{messages.length > 0 && (@@ -268,6 +265,7 @@ export function ChatPanel({<MessageCirclePlus className="size-4 group-hover:rotate-12 transition-all" /></Button>)}+ <ModelTypeSelector /><Buttontype={isLoading ? 'button' : 'submit'}size={'icon'}diff --git a/components/model-selector.tsx b/components/model-selector.tsxdeleted file mode 100644index 2d65e83b..00000000--- a/components/model-selector.tsx+++ /dev/null@@ -1,146 +0,0 @@-'use client'--import { useEffect, useState } from 'react'-import Image from 'next/image'--import { Check, ChevronsUpDown } from 'lucide-react'--import { Model } from '@/lib/types/models'-import { getCookie, setCookie } from '@/lib/utils/cookies'--import { createModelId } from '../lib/utils'--import { Button } from './ui/button'-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList-} from './ui/command'-import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'--function groupModelsByProvider(models: Model[]) {- return models.reduce(- (groups, model) => {- const provider = model.provider- if (!groups[provider]) {- groups[provider] = []- }- groups[provider].push(model)- return groups- },- {} as Record<string, Model[]>- )-}--interface ModelSelectorProps {- models: Model[]-}--export function ModelSelector({ models }: ModelSelectorProps) {- const [open, setOpen] = useState(false)- const [value, setValue] = useState('')-- useEffect(() => {- const savedModel = getCookie('selectedModel')- if (savedModel) {- try {- const model = JSON.parse(savedModel) as Model- setValue(createModelId(model))- } catch (e) {- console.error('Failed to parse saved model:', e)- }- }- }, [])-- const handleModelSelect = (id: string) => {- const newValue = id === value ? '' : id- setValue(newValue)-- const selectedModel = models.find(- model => createModelId(model) === newValue- )- if (selectedModel) {- setCookie('selectedModel', JSON.stringify(selectedModel))- } else {- setCookie('selectedModel', '')- }-- setOpen(false)- }-- const selectedModel = models.find(model => createModelId(model) === value)- const groupedModels = groupModelsByProvider(models)-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Button- variant="outline"- role="combobox"- aria-expanded={open}- className="text-sm rounded-full shadow-none focus:ring-0"- >- {selectedModel ? (- <div className="flex items-center space-x-1">- <Image- src={`/providers/logos/${selectedModel.providerId}.svg`}- alt={selectedModel.provider}- width={18}- height={18}- className="bg-white rounded-full border"- />- <span className="text-xs font-medium">{selectedModel.name}</span>- </div>- ) : (- 'Select model'- )}- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent className="w-72 p-0" align="start">- <Command>- <CommandInput placeholder="Search models..." />- <CommandList>- <CommandEmpty>No model found.</CommandEmpty>- {Object.entries(groupedModels).map(([provider, models]) => (- <CommandGroup key={provider} heading={provider}>- {models.map(model => {- const modelId = createModelId(model)- return (- <CommandItem- key={modelId}- value={modelId}- onSelect={handleModelSelect}- className="flex justify-between"- >- <div className="flex items-center space-x-2">- <Image- src={`/providers/logos/${model.providerId}.svg`}- alt={model.provider}- width={18}- height={18}- className="bg-white rounded-full border"- />- <span className="text-xs font-medium">- {model.name}- </span>- </div>- <Check- className={`h-4 w-4 ${- value === modelId ? 'opacity-100' : 'opacity-0'- }`}- />- </CommandItem>- )- })}- </CommandGroup>- ))}- </CommandList>- </Command>- </PopoverContent>- </Popover>- )-}diff --git a/components/model-type-selector.tsx b/components/model-type-selector.tsxnew file mode 100644index 00000000..e99f3655--- /dev/null+++ b/components/model-type-selector.tsx@@ -0,0 +1,80 @@+'use client'++import { useEffect, useState } from 'react'++import { Check, ChevronDown } from 'lucide-react'++import { ModelType } from '@/lib/types/model-type'+import { getCookie, setCookie } from '@/lib/utils/cookies'++import { Button } from './ui/button'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger+} from './ui/dropdown-menu'++const MODEL_TYPE_OPTIONS: { value: ModelType; label: string }[] = [+ { value: 'speed', label: 'Speed' },+ { value: 'quality', label: 'Quality' }+]++export function ModelTypeSelector() {+ const [value, setValue] = useState<ModelType>('speed')+ const [dropdownOpen, setDropdownOpen] = useState(false)++ useEffect(() => {+ const savedType = getCookie('modelType')+ if (savedType && ['speed', 'quality'].includes(savedType)) {+ setValue(savedType as ModelType)+ }+ }, [])++ const handleTypeSelect = (type: ModelType) => {+ setValue(type)+ setCookie('modelType', type)+ setDropdownOpen(false)+ }++ const selectedOption = MODEL_TYPE_OPTIONS.find(opt => opt.value === value)++ return (+ <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ className="text-sm rounded-full shadow-none gap-1 transition-all px-3 py-2 h-auto bg-muted border-none"+ >+ <span className="text-xs font-medium">{selectedOption?.label}</span>+ <ChevronDown+ className={`h-3 w-3 ml-0.5 opacity-50 transition-transform duration-200 ${+ dropdownOpen ? 'rotate-180' : ''+ }`}+ />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="min-w-[120px]"+ sideOffset={5}+ >+ {MODEL_TYPE_OPTIONS.map(option => {+ const isSelected = value === option.value+ return (+ <DropdownMenuItem+ key={option.value}+ onClick={() => handleTypeSelect(option.value)}+ className="relative flex items-center cursor-pointer"+ >+ <div className="w-4 h-4 mr-2 flex items-center justify-center">+ {isSelected && <Check className="h-3 w-3" />}+ </div>+ <span className="text-sm">{option.label}</span>+ </DropdownMenuItem>+ )+ })}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/lib/config/model-types.ts b/lib/config/model-types.tsnew file mode 100644index 00000000..9ca1895c--- /dev/null+++ b/lib/config/model-types.ts@@ -0,0 +1,35 @@+import { ModelType } from '@/lib/types/model-type'+import { Model } from '@/lib/types/models'++// Model configurations for each model type+export const MODEL_TYPE_CONFIGS: Record<ModelType, Model> = {+ speed: {+ id: 'gpt-5-nano-2025-08-07',+ name: 'GPT-5 nano',+ provider: 'OpenAI',+ providerId: 'openai',+ providerOptions: {+ openai: {+ reasoningEffort: 'low',+ reasoningSummary: 'detailed'+ }+ }+ },+ quality: {+ id: 'gpt-5-2025-08-07',+ name: 'GPT-5',+ provider: 'OpenAI',+ providerId: 'openai',+ providerOptions: {+ openai: {+ reasoningEffort: 'low',+ reasoningSummary: 'detailed'+ }+ }+ }+}++// Helper function to get model for a specific type+export function getModelForType(type: ModelType): Model {+ return MODEL_TYPE_CONFIGS[type]+}diff --git a/lib/config/search-modes.ts b/lib/config/search-modes.tsindex c1e51be6..ca6df36c 100644--- a/lib/config/search-modes.ts+++ b/lib/config/search-modes.ts@@ -1,6 +1,5 @@import { ListChecks, Search, Sparkles } from 'lucide-react'-import { Model } from '@/lib/types/models'import { SearchMode } from '@/lib/types/search'export interface SearchModeConfig {@@ -9,8 +8,6 @@ export interface SearchModeConfig {description: stringicon: React.ComponentType<{ className?: string }>color: string- displayModel: string // Model name shown in UI- actualModel: Model // Actual model configuration used by API}// Centralized search mode configuration@@ -20,74 +17,24 @@ export const SEARCH_MODE_CONFIGS: SearchModeConfig[] = [label: 'Adaptive',description: 'Automatically adjusts search strategy to match your needs',icon: Sparkles,- color: 'text-violet-500',- displayModel: 'Auto',- actualModel: {- id: 'gpt-5-mini-2025-08-07',- name: 'GPT-5 mini',- provider: 'OpenAI',- providerId: 'openai',- providerOptions: {- openai: {- reasoningEffort: 'low',- reasoningSummary: 'detailed'- }- }- }+ color: 'text-violet-500'},{value: 'planning',label: 'Planning',description: 'Structured multi-step approach for comprehensive research',icon: ListChecks,- color: 'text-blue-500',- displayModel: 'OpenAI GPT-5',- actualModel: {- id: 'gpt-5-2025-08-07',- name: 'GPT-5',- provider: 'OpenAI',- providerId: 'openai',- providerOptions: {- openai: {- reasoningEffort: 'low',- reasoningSummary: 'detailed'- }- }- }+ color: 'text-blue-500'},{value: 'quick',label: 'Quick',description: 'Streamlined search for fast, concise responses',icon: Search,- color: 'text-amber-500',- displayModel: 'MoonshotAI/Kimi K2',- actualModel: {- id: 'gpt-5-nano-2025-08-07',- name: 'GPT-5 nano',- provider: 'OpenAI',- providerId: 'openai',- providerOptions: {- openai: {- reasoningEffort: 'low',- reasoningSummary: 'detailed'- }- }- }+ color: 'text-amber-500'}]-// Helper function to get model mapping for API use-export function getSearchModeModels(): Record<SearchMode, Model> {- return SEARCH_MODE_CONFIGS.reduce(- (acc, config) => {- acc[config.value] = config.actualModel- return acc- },- {} as Record<SearchMode, Model>- )-}-// Helper function to get a specific mode configexport function getSearchModeConfig(mode: SearchModediff --git a/lib/types/model-type.ts b/lib/types/model-type.tsnew file mode 100644index 00000000..4cc6649a--- /dev/null+++ b/lib/types/model-type.ts@@ -0,0 +1,2 @@+// Model type definition for speed/quality selection+export type ModelType = 'speed' | 'quality'diff --git a/lib/utils/model-selection.ts b/lib/utils/model-selection.tsindex 0deb7330..4b4cada7 100644--- a/lib/utils/model-selection.ts+++ b/lib/utils/model-selection.ts@@ -1,8 +1,8 @@import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'-import { getSearchModeModels } from '@/lib/config/search-modes'+import { getModelForType } from '@/lib/config/model-types'+import { ModelType } from '@/lib/types/model-type'import { Model } from '@/lib/types/models'-import { SearchMode } from '@/lib/types/search'const DEFAULT_MODEL: Model = {id: 'gpt-4o-mini',@@ -13,50 +13,26 @@ const DEFAULT_MODEL: Model = {interface ModelSelectionParams {cookieStore: ReadonlyRequestCookies- searchModeFromRequest?: SearchMode- showModelSelector?: boolean}/**- * Determines which model to use based on the current configuration and user preferences+ * Determines which model to use based on the model type preference** Priority order:- * 1. If model selector is enabled AND user has selected a model -> use selected model- * 2. If search mode is provided in request -> use mode's default model- * 3. If search mode is in cookie -> use mode's default model- * 4. Otherwise -> use DEFAULT_MODEL+ * 1. If model type is in cookie -> use corresponding model+ * 2. Otherwise -> use DEFAULT_MODEL*/-export function selectModel({- cookieStore,- searchModeFromRequest,- showModelSelector = process.env.NEXT_PUBLIC_SHOW_MODEL_SELECTOR === 'true'-}: ModelSelectionParams): Model {- const modelJson = cookieStore.get('selectedModel')?.value- const searchModeCookie = cookieStore.get('searchMode')?.value as- | SearchMode+export function selectModel({ cookieStore }: ModelSelectionParams): Model {+ const modelTypeCookie = cookieStore.get('modelType')?.value as+ | ModelType| undefined- const SEARCH_MODE_MODELS = getSearchModeModels()- // Priority 1: Model selector is enabled and user has selected a model- if (showModelSelector && modelJson) {- try {- return JSON.parse(modelJson) as Model- } catch (e) {- console.error('Failed to parse selected model:', e)- }+ // If model type is set, use the corresponding model+ if (modelTypeCookie && ['speed', 'quality'].includes(modelTypeCookie)) {+ return getModelForType(modelTypeCookie)}- // Priority 2: Search mode from request- if (searchModeFromRequest && searchModeFromRequest in SEARCH_MODE_MODELS) {- return SEARCH_MODE_MODELS[searchModeFromRequest]- }-- // Priority 3: Search mode from cookie- if (searchModeCookie && searchModeCookie in SEARCH_MODE_MODELS) {- return SEARCH_MODE_MODELS[searchModeCookie]- }-- // Priority 4: Default model+ // Default modelreturn DEFAULT_MODEL}