Skip to content

An AI-powered search engine with a generative UI

refactor: improve search mode architecture and add model selection control

Yoshiki Miura5c55d88cb9ce
diff --git a/.env.local.example b/.env.local.example
index 414514bc..dc47cc2c 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -90,6 +90,7 @@ TAVILY_API_KEY=[YOUR_TAVILY_API_KEY] # Get your API key at: https://app.tavily.
# Enable extra functionality as needed
#------------------------------------------------------------------------------
# NEXT_PUBLIC_ENABLE_SHARE=true # Enable sharing of chat conversations
+# NEXT_PUBLIC_SHOW_MODEL_SELECTOR=true # Show model selector in UI (default: hidden, uses search mode defaults)
# SERPER_API_KEY=[YOUR_SERPER_API_KEY] # Enable video search capability
# JINA_API_KEY=[YOUR_JINA_API_KEY] # Alternative to Tavily for retrieve tool
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 6e7a30b6..e2fcef5b 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -2,20 +2,13 @@ import { cookies } from 'next/headers'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
-import { Model } from '@/lib/types/models'
+import { selectModel } from '@/lib/utils/model-selection'
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { resetAllCounters } from '@/lib/utils/perf-tracking'
import { isProviderEnabled } from '@/lib/utils/registry'
export const maxDuration = 30
-const DEFAULT_MODEL: Model = {
- id: 'gpt-4o-mini',
- name: 'GPT-4o mini',
- provider: 'OpenAI',
- providerId: 'openai'
-}
-
export async function POST(req: Request) {
const startTime = performance.now()
const abortSignal = req.signal
@@ -73,17 +66,12 @@ export async function POST(req: Request) {
}
const cookieStore = await cookies()
- const modelJson = cookieStore.get('selectedModel')?.value
-
- let selectedModel = DEFAULT_MODEL
-
- if (modelJson) {
- try {
- selectedModel = JSON.parse(modelJson) as Model
- } catch (e) {
- console.error('Failed to parse selected model:', e)
- }
- }
+
+ // Select the appropriate model based on configuration and user preferences
+ const selectedModel = selectModel({
+ cookieStore,
+ searchModeFromRequest: searchMode
+ })
if (!isProviderEnabled(selectedModel.providerId)) {
return new Response(
@@ -95,7 +83,6 @@ export async function POST(req: Request) {
)
}
- const streamStart = performance.now()
const response = await createChatStreamResponse({
message,
model: selectedModel,
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 188ce632..8054263f 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -202,8 +202,10 @@ export function ChatPanel({
{/* Bottom menu area */}
<div className="flex items-center justify-between p-3">
<div className="flex items-center gap-2">
- <ModelSelector models={models || []} />
<SearchModeSelector />
+ {process.env.NEXT_PUBLIC_SHOW_MODEL_SELECTOR === 'true' && (
+ <ModelSelector models={models || []} />
+ )}
</div>
<div className="flex items-center gap-2">
{messages.length > 0 && (
diff --git a/components/chat.tsx b/components/chat.tsx
index edd413b4..17b7d6f2 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -6,7 +6,6 @@ import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
import { toast } from 'sonner'
-import { SearchMode } from '@/lib/agents/researcher'
import { generateId } from '@/lib/db/schema'
import { UploadedFile } from '@/lib/types'
import type { UIMessage } from '@/lib/types/ai'
@@ -16,6 +15,7 @@ import {
isToolTypePart
} from '@/lib/types/dynamic-tools'
import { Model } from '@/lib/types/models'
+import { SearchMode } from '@/lib/types/search'
import { cn } from '@/lib/utils'
import { getCookie } from '@/lib/utils/cookies'
diff --git a/components/search-mode-selector.tsx b/components/search-mode-selector.tsx
index 0e68ccba..1f81baee 100644
--- a/components/search-mode-selector.tsx
+++ b/components/search-mode-selector.tsx
@@ -2,9 +2,10 @@
import { useEffect, useState } from 'react'
-import { Check, ChevronDown, GitBranch, Sparkles, Zap } from 'lucide-react'
+import { Check, ChevronDown } from 'lucide-react'
-import { SearchMode } from '@/lib/agents/researcher'
+import { SEARCH_MODE_CONFIGS } from '@/lib/config/search-modes'
+import { SearchMode } from '@/lib/types/search'
import { cn } from '@/lib/utils'
import { getCookie, setCookie } from '@/lib/utils/cookies'
@@ -16,42 +17,6 @@ import {
DropdownMenuTrigger
} from './ui/dropdown-menu'
-interface SearchModeOption {
- value: SearchMode
- label: string
- description: string
- model: string
- icon: React.ComponentType<{ className?: string }>
- color: string
-}
-
-const searchModes: SearchModeOption[] = [
- {
- value: 'quick',
- label: 'Quick',
- description: 'Fast, concise responses',
- model: 'MoonshotAI/Kimi K2',
- icon: Zap,
- color: 'text-yellow-500'
- },
- {
- value: 'planning',
- label: 'Planning',
- description: 'Detailed, structured research',
- model: 'OpenAI GPT-5',
- icon: GitBranch,
- color: 'text-blue-500'
- },
- {
- value: 'auto',
- label: 'Auto',
- description: 'Balanced, adaptive approach',
- model: 'Auto',
- icon: Sparkles,
- color: 'text-purple-500'
- }
-]
-
export function SearchModeSelector() {
const [value, setValue] = useState<SearchMode>('auto')
const [open, setOpen] = useState(false)
@@ -69,8 +34,8 @@ export function SearchModeSelector() {
setOpen(false)
}
- const selectedMode = searchModes.find(mode => mode.value === value)
- const Icon = selectedMode?.icon || Sparkles
+ const selectedMode = SEARCH_MODE_CONFIGS.find(config => config.value === value)
+ const Icon = selectedMode?.icon
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
@@ -79,9 +44,11 @@ export function SearchModeSelector() {
variant="outline"
className="text-sm rounded-full shadow-none gap-1 transition-all !ring-0 !outline-none !ring-offset-0 [&:focus]:!ring-0 [&:focus]:!outline-none [&:focus-visible]:!ring-0 [&:focus-visible]:!ring-offset-0"
>
- <Icon
- className={cn('h-4 w-4 transition-colors', selectedMode?.color)}
- />
+ {Icon && (
+ <Icon
+ className={cn('h-4 w-4 transition-colors', selectedMode?.color)}
+ />
+ )}
<span className="text-xs font-medium">{selectedMode?.label}</span>
<ChevronDown
className={cn(
@@ -92,13 +59,13 @@ export function SearchModeSelector() {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-64" sideOffset={5}>
- {searchModes.map(mode => {
- const ModeIcon = mode.icon
- const isSelected = value === mode.value
+ {SEARCH_MODE_CONFIGS.map(config => {
+ const ModeIcon = config.icon
+ const isSelected = value === config.value
return (
<DropdownMenuItem
- key={mode.value}
- onClick={() => handleModeSelect(mode.value)}
+ key={config.value}
+ onClick={() => handleModeSelect(config.value)}
className="relative flex flex-col items-start gap-1 py-2 pl-8 pr-2 cursor-pointer focus:outline-none"
>
{isSelected && (
@@ -106,16 +73,16 @@ export function SearchModeSelector() {
)}
<div className="flex items-center gap-2">
<ModeIcon
- className={cn('h-4 w-4 transition-colors', mode.color)}
+ className={cn('h-4 w-4 transition-colors', config.color)}
/>
- <span className="text-sm font-medium">{mode.label}</span>
+ <span className="text-sm font-medium">{config.label}</span>
</div>
<div className="flex flex-col gap-0.5 ml-6">
<span className="text-xs text-muted-foreground">
- {mode.description}
+ {config.description}
</span>
<span className="text-xs text-muted-foreground/70">
- {mode.model}
+ {config.displayModel}
</span>
</div>
</DropdownMenuItem>
diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.ts
index 2a29805b..90de2c96 100644
--- a/lib/agents/researcher.ts
+++ b/lib/agents/researcher.ts
@@ -9,12 +9,10 @@ import { fetchTool } from '../tools/fetch'
import { createQuestionTool } from '../tools/question'
import { createSearchTool } from '../tools/search'
import { createTodoTools } from '../tools/todo'
+import { SearchMode } from '../types/search'
import { getModel } from '../utils/registry'
import { isTracingEnabled } from '../utils/telemetry'
-// Search mode type
-export type SearchMode = 'quick' | 'planning' | 'auto'
-
// Quick Mode System Prompt - Minimal, direct responses
const QUICK_MODE_PROMPT = `
Instructions:
diff --git a/lib/config/search-modes.ts b/lib/config/search-modes.ts
new file mode 100644
index 00000000..3ddb966f
--- /dev/null
+++ b/lib/config/search-modes.ts
@@ -0,0 +1,91 @@
+import { GitBranch, Sparkles, Zap } from 'lucide-react'
+
+import { Model } from '@/lib/types/models'
+import { SearchMode } from '@/lib/types/search'
+
+export interface SearchModeConfig {
+ value: SearchMode
+ label: string
+ description: string
+ icon: 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
+export const SEARCH_MODE_CONFIGS: SearchModeConfig[] = [
+ {
+ value: 'quick',
+ label: 'Quick',
+ description: 'Fast, concise responses',
+ icon: Zap,
+ color: 'text-yellow-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'
+ }
+ }
+ }
+ },
+ {
+ value: 'planning',
+ label: 'Planning',
+ description: 'Detailed, structured research',
+ icon: GitBranch,
+ 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'
+ }
+ }
+ }
+ },
+ {
+ value: 'auto',
+ label: 'Auto',
+ description: 'Balanced, adaptive approach',
+ icon: Sparkles,
+ color: 'text-purple-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'
+ }
+ }
+ }
+ }
+]
+
+// 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 config
+export function getSearchModeConfig(mode: SearchMode): SearchModeConfig | undefined {
+ return SEARCH_MODE_CONFIGS.find(config => config.value === mode)
+}
\ No newline at end of file
diff --git a/lib/streaming/types.ts b/lib/streaming/types.ts
index a6c763ff..e3361008 100644
--- a/lib/streaming/types.ts
+++ b/lib/streaming/types.ts
@@ -1,7 +1,7 @@
import { UIMessage } from '@ai-sdk/react'
-import { SearchMode } from '../agents/researcher'
import { Model } from '../types/models'
+import { SearchMode } from '../types/search'
export interface BaseStreamConfig {
message: UIMessage | null
diff --git a/lib/types/index.ts b/lib/types/index.ts
index 8698f2c2..43676fe7 100644
--- a/lib/types/index.ts
+++ b/lib/types/index.ts
@@ -1,3 +1,6 @@
+// Re-export SearchMode for convenience
+export type { SearchMode } from './search'
+
export type SearchResults = {
images: SearchResultImage[]
results: SearchResultItem[]
diff --git a/lib/types/search.ts b/lib/types/search.ts
new file mode 100644
index 00000000..44d2117d
--- /dev/null
+++ b/lib/types/search.ts
@@ -0,0 +1,2 @@
+// Search mode type definition
+export type SearchMode = 'quick' | 'planning' | 'auto'
\ No newline at end of file
diff --git a/lib/utils/model-selection.ts b/lib/utils/model-selection.ts
new file mode 100644
index 00000000..3c28bde9
--- /dev/null
+++ b/lib/utils/model-selection.ts
@@ -0,0 +1,61 @@
+import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'
+
+import { getSearchModeModels } from '@/lib/config/search-modes'
+import { Model } from '@/lib/types/models'
+import { SearchMode } from '@/lib/types/search'
+
+const DEFAULT_MODEL: Model = {
+ id: 'gpt-4o-mini',
+ name: 'GPT-4o mini',
+ provider: 'OpenAI',
+ providerId: 'openai'
+}
+
+interface ModelSelectionParams {
+ cookieStore: ReadonlyRequestCookies
+ searchModeFromRequest?: SearchMode
+ showModelSelector?: boolean
+}
+
+/**
+ * Determines which model to use based on the current configuration and user preferences
+ *
+ * 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
+ */
+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 | 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)
+ }
+ }
+
+ // 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
+ return DEFAULT_MODEL
+}
+
+export { DEFAULT_MODEL }
\ No newline at end of file