Skip to content

An AI-powered search engine with a generative UI

fix: align model selection flow for local/docker and gateway

Yoshiki Miurae3e2dc28fe58
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index deacf9cb..93d6aa1b 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -92,22 +92,7 @@ export async function POST(req: Request) {
? (searchModeCookie as SearchMode)
: 'quick'
- const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
- const forceSpeed = isGuest || isCloudDeployment
- const modelCookieStore = forceSpeed
- ? ({
- get: (name: string) =>
- name === 'modelType'
- ? ({ value: 'speed' } as const)
- : cookieStore.get(name)
- } as typeof cookieStore)
- : cookieStore
-
- // Select the appropriate model based on model type preference and search mode
- const selectedModel = selectModel({
- cookieStore: modelCookieStore,
- searchMode
- })
+ const selectedModel = await selectModel({ searchMode, cookieStore })
if (!isProviderEnabled(selectedModel.providerId)) {
return new Response(
@@ -119,13 +104,6 @@ export async function POST(req: Request) {
)
}
- // Resolve model type from cookie (forced to speed for guests and cloud)
- const modelTypeCookie = cookieStore.get('modelType')?.value
- const resolvedModelType =
- modelTypeCookie === 'quality' || modelTypeCookie === 'speed'
- ? modelTypeCookie
- : undefined
- const modelType = forceSpeed ? 'speed' : resolvedModelType
if (!isGuest) {
const overallLimitResponse = await checkAndEnforceOverallChatLimit(userId)
if (overallLimitResponse) return overallLimitResponse
@@ -133,7 +111,7 @@ export async function POST(req: Request) {
const streamStart = performance.now()
perfLog(
- `createChatStreamResponse - Start: model=${selectedModel.providerId}:${selectedModel.id}, searchMode=${searchMode}, modelType=${modelType}`
+ `createChatStreamResponse - Start: model=${selectedModel.providerId}:${selectedModel.id}, searchMode=${searchMode}`
)
const response = isGuest
@@ -142,7 +120,6 @@ export async function POST(req: Request) {
model: selectedModel,
abortSignal,
searchMode,
- modelType,
chatId
})
: await createChatStreamResponse({
@@ -154,8 +131,7 @@ export async function POST(req: Request) {
messageId,
abortSignal,
isNewChat,
- searchMode,
- modelType
+ searchMode
})
perfTime('createChatStreamResponse resolved', streamStart)
@@ -178,7 +154,6 @@ export async function POST(req: Request) {
if (!isGuest && userId) {
await trackChatEvent({
searchMode,
- modelType: modelTypeCookie === 'quality' ? 'quality' : 'speed',
conversationTurn,
isNewChat: isNewChat ?? false,
trigger:
@@ -186,6 +161,7 @@ export async function POST(req: Request) {
'submit-message',
chatId,
userId,
+ providerId: selectedModel.providerId,
modelId: selectedModel.id
})
}
diff --git a/app/page.tsx b/app/page.tsx
index 12593f5d..7ab870b3 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -1,8 +1,18 @@
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { Chat } from '@/components/chat'
export default async function Page() {
const userId = await getCurrentUserId()
- return <Chat isGuest={!userId} />
+ const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const modelSelectorData = await getModelSelectorData()
+
+ return (
+ <Chat
+ isGuest={!userId}
+ isCloudDeployment={isCloudDeployment}
+ modelSelectorData={modelSelectorData}
+ />
+ )
}
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index 77e499f8..749c1900 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -4,6 +4,7 @@ import { UIMessage } from 'ai'
import { loadChat } from '@/lib/actions/chat'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { Chat } from '@/components/chat'
@@ -43,6 +44,16 @@ export default async function SearchPage(props: {
}
const messages: UIMessage[] = chat.messages
-
- return <Chat id={id} savedMessages={messages} isGuest={!userId} />
+ const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const modelSelectorData = await getModelSelectorData()
+
+ return (
+ <Chat
+ id={id}
+ savedMessages={messages}
+ isGuest={!userId}
+ isCloudDeployment={isCloudDeployment}
+ modelSelectorData={modelSelectorData}
+ />
+ )
}
diff --git a/app/search/page.tsx b/app/search/page.tsx
index 5d82d7e4..db1ce83d 100644
--- a/app/search/page.tsx
+++ b/app/search/page.tsx
@@ -1,6 +1,7 @@
import { redirect } from 'next/navigation'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getModelSelectorData } from '@/lib/model-selector/get-model-selector-data'
import { generateUUID } from '@/lib/utils'
import { Chat } from '@/components/chat'
@@ -17,5 +18,16 @@ export default async function SearchPage(props: {
const id = generateUUID()
const userId = await getCurrentUserId()
- return <Chat id={id} query={q} isGuest={!userId} />
+ const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const modelSelectorData = await getModelSelectorData()
+
+ return (
+ <Chat
+ id={id}
+ query={q}
+ isGuest={!userId}
+ isCloudDeployment={isCloudDeployment}
+ modelSelectorData={modelSelectorData}
+ />
+ )
}
diff --git a/bun.lock b/bun.lock
index 6f25d58c..15fd98a7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -56,9 +56,9 @@
"langfuse-vercel": "^3.38.4",
"lucide-react": "^0.507.0",
"next": "^16.2.1",
- "next-themes": "^0.3.0",
+ "next-themes": "0.4.6",
"node-html-parser": "^6.1.13",
- "ollama-ai-provider-v2": "^1.5.0",
+ "ollama-ai-provider-v2": "3.5.0",
"postgres": "^3.4.5",
"react": "^19.2.0",
"react-dom": "^19.2.0",
@@ -1787,7 +1787,7 @@
"next": ["[email protected]", "", { "dependencies": { "@next/env": "16.2.1", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.2.1", "@next/swc-darwin-x64": "16.2.1", "@next/swc-linux-arm64-gnu": "16.2.1", "@next/swc-linux-arm64-musl": "16.2.1", "@next/swc-linux-x64-gnu": "16.2.1", "@next/swc-linux-x64-musl": "16.2.1", "@next/swc-win32-arm64-msvc": "16.2.1", "@next/swc-win32-x64-msvc": "16.2.1", "sharp": "^0.34.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-VaChzNL7o9rbfdt60HUj8tev4m6d7iC1igAy157526+cJlXOQu5LzsBXNT+xaJnTP/k+utSX5vMv7m0G+zKH+Q=="],
- "next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18", "react-dom": "^16.8 || ^17 || ^18" } }, "sha512-/QHIrsYpd6Kfk7xakK4svpDI5mmXP0gfvCoJdGpZQ2TOrQZmsW0QxjaiLn8wbIKjtm4BTSqLoix4lxYYOnLJ/w=="],
+ "next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
"node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
@@ -1815,7 +1815,7 @@
"object.values": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA=="],
- "ollama-ai-provider-v2": ["[email protected]", "", { "dependencies": { "@ai-sdk/provider": "^2.0.0", "@ai-sdk/provider-utils": "^3.0.7" }, "peerDependencies": { "zod": "^4.0.16" } }, "sha512-o8nR80AaENpetYdCtlnZGEwO47N6Z6eEsBetitrh4nTXrbfWdRF4OWE5p5oHyo0R8sxg4zdxUsjmGVzPd3zBUQ=="],
+ "ollama-ai-provider-v2": ["[email protected]", "", { "dependencies": { "@ai-sdk/provider": "^3.0.8", "@ai-sdk/provider-utils": "^4.0.19" }, "peerDependencies": { "ai": "^5.0.0 || ^6.0.0", "zod": "^4.0.16" } }, "sha512-+s/aYIYa91z2Vk3AkGAz3BaPAQ0flS2eFZD3BN2mD/N6W6YQbcookyu6pc2cbc8SP5VGpNB857WJ0eHDjKXsXw=="],
"openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-+AuTc5pVjlnTuA9zvn8rA/k+1RluPIx9AD4eDcnutv6JNwHHZxIhkFy+tmMKCvmMFDQzfA/r1ujvPWB19DQkYg=="],
@@ -2383,9 +2383,7 @@
"node-fetch/whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
- "ollama-ai-provider-v2/@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA=="],
-
- "ollama-ai-provider-v2/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.5" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-cDj1iigu7MW2tgAQeBzOiLhjHOUM9vENsgh4oAVitek0d//WdgfPCsKO3euP7m7LyO/j9a1vr/So+BGNdpFXYw=="],
+ "ollama-ai-provider-v2/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="],
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
@@ -2527,8 +2525,6 @@
"node-fetch/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
- "ollama-ai-provider-v2/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA=="],
-
"@aws-crypto/sha1-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 6ae02694..ea63a950 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -10,6 +10,7 @@ import { toast } from 'sonner'
import { UploadedFile } from '@/lib/types'
import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
+import type { ModelSelectorData } from '@/lib/types/model-selector'
import { cn } from '@/lib/utils'
import { useArtifact } from './artifact/artifact-context'
@@ -17,7 +18,7 @@ import { Button } from './ui/button'
import { IconBlinkingLogo } from './ui/icons'
import { ActionButtons } from './action-buttons'
import { FileUploadButton } from './file-upload-button'
-import { ModelTypeSelector } from './model-type-selector'
+import { ModelSelectorClient } from './model-selector-client'
import { SearchModeSelector } from './search-mode-selector'
import { UploadedFileList } from './uploaded-file-list'
@@ -45,6 +46,9 @@ interface ChatPanelProps {
onNewChat?: () => void
/** Whether the current session is guest */
isGuest?: boolean
+ /** Whether the deployment is cloud mode */
+ isCloudDeployment?: boolean
+ modelSelectorData?: ModelSelectorData
}
export function ChatPanel({
@@ -63,7 +67,9 @@ export function ChatPanel({
setUploadedFiles,
scrollContainerRef,
onNewChat,
- isGuest = false
+ isGuest = false,
+ isCloudDeployment = false,
+ modelSelectorData
}: ChatPanelProps) {
const router = useRouter()
const inputRef = useRef<HTMLTextAreaElement>(null)
@@ -283,6 +289,9 @@ export function ChatPanel({
<SearchModeSelector />
</div>
<div className="flex items-center gap-2">
+ {!isCloudDeployment && modelSelectorData && (
+ <ModelSelectorClient data={modelSelectorData} />
+ )}
{messages.length > 0 && (
<Button
variant="outline"
@@ -295,9 +304,6 @@ export function ChatPanel({
<MessageCirclePlus className="size-4 group-hover:rotate-12 transition-all" />
</Button>
)}
- {process.env.NEXT_PUBLIC_MORPHIC_CLOUD_DEPLOYMENT !== 'true' && (
- <ModelTypeSelector disabled={isGuest} />
- )}
<Button
type={isLoading ? 'button' : 'submit'}
size={'icon'}
diff --git a/components/chat.tsx b/components/chat.tsx
index b085222a..0570c5fb 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -15,6 +15,7 @@ import {
isToolCallPart,
isToolTypePart
} from '@/lib/types/dynamic-tools'
+import type { ModelSelectorData } from '@/lib/types/model-selector'
import { cn } from '@/lib/utils'
import { useFileDropzone } from '@/hooks/use-file-dropzone'
@@ -35,12 +36,16 @@ export function Chat({
id: providedId,
savedMessages = [],
query,
- isGuest = false
+ isGuest = false,
+ isCloudDeployment = false,
+ modelSelectorData
}: {
id?: string
savedMessages?: UIMessage[]
query?: string
isGuest?: boolean
+ isCloudDeployment?: boolean
+ modelSelectorData?: ModelSelectorData
}) {
const router = useRouter()
@@ -489,6 +494,8 @@ export function Chat({
scrollContainerRef={scrollContainerRef}
onNewChat={handleNewChat}
isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ modelSelectorData={modelSelectorData}
/>
<DragOverlay visible={dragHandlers.isDragging} />
<ErrorModal
diff --git a/components/model-selector-client.tsx b/components/model-selector-client.tsx
new file mode 100644
index 00000000..300640d4
--- /dev/null
+++ b/components/model-selector-client.tsx
@@ -0,0 +1,166 @@
+'use client'
+
+import { useMemo, useState } from 'react'
+import Image from 'next/image'
+
+import { Check, ChevronDown } from 'lucide-react'
+
+import {
+ MODEL_SELECTION_COOKIE,
+ serializeModelSelectionCookie
+} from '@/lib/config/model-selection-cookie'
+import { ModelSelectorData } from '@/lib/types/model-selector'
+import { Model } from '@/lib/types/models'
+import { cn } from '@/lib/utils'
+import { setCookie } from '@/lib/utils/cookies'
+
+import { Button } from './ui/button'
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList
+} from './ui/command'
+import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'
+
+function modelKey(model: Model): string {
+ return `${model.providerId}:${model.id}`
+}
+
+const PROVIDER_LOGO_BY_ID: Record<string, string> = {
+ openai: '/providers/logos/openai.svg',
+ anthropic: '/providers/logos/anthropic.svg',
+ google: '/providers/logos/google.svg',
+ gateway: '/providers/logos/gateway.svg',
+ 'openai-compatible': '/providers/logos/openai-compatible.svg',
+ ollama: '/providers/logos/ollama.svg'
+}
+
+function ProviderLogo({ providerId }: { providerId: string }) {
+ const logoSrc = PROVIDER_LOGO_BY_ID[providerId]
+ if (!logoSrc) {
+ return <span className="size-4 rounded-full bg-muted-foreground/30" />
+ }
+
+ return (
+ <Image
+ src={logoSrc}
+ alt={`${providerId} logo`}
+ width={16}
+ height={16}
+ className="size-4 shrink-0 object-contain"
+ />
+ )
+}
+
+interface ModelSelectorClientProps {
+ data: ModelSelectorData
+}
+
+export function ModelSelectorClient({ data }: ModelSelectorClientProps) {
+ const [open, setOpen] = useState(false)
+ const [selectedModelKey, setSelectedModelKey] = useState<string>(
+ data.selectedModelKey
+ )
+
+ const providerEntries = useMemo(
+ () =>
+ Object.entries(data.modelsByProvider).sort(([providerA], [providerB]) =>
+ providerA.localeCompare(providerB)
+ ),
+ [data.modelsByProvider]
+ )
+
+ const selectableModels = useMemo(
+ () => providerEntries.flatMap(([, models]) => models),
+ [providerEntries]
+ )
+
+ const selectableByKey = useMemo(
+ () =>
+ Object.fromEntries(
+ selectableModels.map(model => [modelKey(model), model])
+ ) as Record<string, Model>,
+ [selectableModels]
+ )
+
+ const selectedModel = selectableByKey[selectedModelKey] ?? data.defaultModel
+
+ if (!data.enabled) {
+ return null
+ }
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="text-sm rounded-full shadow-none gap-1 transition-all px-3 py-2 h-auto bg-muted border-none"
+ >
+ <ProviderLogo providerId={selectedModel.providerId} />
+ <span className="truncate max-w-40 text-xs font-medium">
+ {selectedModel.name}
+ </span>
+ <ChevronDown
+ className={cn(
+ 'h-3 w-3 ml-0.5 opacity-50 transition-transform duration-200',
+ open && 'rotate-180'
+ )}
+ />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[300px] p-0" align="end" sideOffset={6}>
+ <Command>
+ <CommandInput placeholder="Search models..." />
+ <CommandList>
+ <CommandEmpty>No model found.</CommandEmpty>
+ {providerEntries.map(([provider, models]) => (
+ <CommandGroup key={provider} heading={provider}>
+ {models.map(model => {
+ const value = modelKey(model)
+ const isSelected = selectedModelKey === value
+ return (
+ <CommandItem
+ key={value}
+ value={`${value} ${model.name} ${provider}`}
+ onSelect={() => {
+ const nextModel = selectableByKey[value]
+ if (!nextModel) {
+ return
+ }
+
+ setSelectedModelKey(value)
+ setCookie(
+ MODEL_SELECTION_COOKIE,
+ serializeModelSelectionCookie({
+ providerId: nextModel.providerId,
+ modelId: nextModel.id
+ })
+ )
+ setOpen(false)
+ }}
+ className="cursor-pointer"
+ >
+ <Check
+ className={cn(
+ 'h-4 w-4',
+ isSelected ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ <ProviderLogo providerId={model.providerId} />
+ <span className="truncate">{model.name}</span>
+ </CommandItem>
+ )
+ })}
+ </CommandGroup>
+ ))}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/components/model-type-selector.tsx b/components/model-type-selector.tsx
deleted file mode 100644
index 2934d591..00000000
--- a/components/model-type-selector.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-'use client'
-
-import { useEffect, useState, useSyncExternalStore } from 'react'
-
-import { Check, ChevronDown } from 'lucide-react'
-
-import { ModelType } from '@/lib/types/model-type'
-import {
- getCookie,
- setCookie,
- subscribeToCookieChange
-} 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({
- disabled = false
-}: {
- disabled?: boolean
-}) {
- const value = useSyncExternalStore(
- subscribeToCookieChange,
- () => {
- const savedType = getCookie('modelType')
- return savedType === 'quality' ? 'quality' : 'speed'
- },
- () => 'speed'
- )
- const [dropdownOpen, setDropdownOpen] = useState(false)
-
- useEffect(() => {
- if (disabled) {
- setCookie('modelType', 'speed')
- }
- }, [disabled])
-
- const handleTypeSelect = (type: ModelType) => {
- if (disabled) return
- setCookie('modelType', type)
- setDropdownOpen(false)
- }
-
- const selectedValue = disabled ? 'speed' : value
- const selectedOption = MODEL_TYPE_OPTIONS.find(
- opt => opt.value === selectedValue
- )
-
- 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"
- disabled={disabled}
- >
- <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 = selectedValue === 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/components/theme-provider.tsx b/components/theme-provider.tsx
index d4b4bbfd..70d5ec2c 100644
--- a/components/theme-provider.tsx
+++ b/components/theme-provider.tsx
@@ -2,7 +2,7 @@
import * as React from 'react'
import { ThemeProvider as NextThemesProvider } from 'next-themes'
-import { type ThemeProviderProps } from 'next-themes/dist/types'
+import { type ThemeProviderProps } from 'next-themes'
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
diff --git a/config/models/cloud.json b/config/models/cloud.json
index 9cda078e..11e7e805 100644
--- a/config/models/cloud.json
+++ b/config/models/cloud.json
@@ -1,59 +1,28 @@
{
- "version": 1,
+ "version": 2,
"models": {
- "byMode": {
- "quick": {
- "speed": {
- "id": "gemini-3.1-flash-lite-preview",
- "name": "Gemini 3.1 Flash Lite Preview",
- "provider": "Google",
- "providerId": "google",
- "providerOptions": {
- "google": {
- "thinkingConfig": {
- "includeThoughts": true
- }
- }
- }
- },
- "quality": {
- "id": "gemini-3.1-pro-preview",
- "name": "Gemini 3.1 Pro Preview",
- "provider": "Google",
- "providerId": "google",
- "providerOptions": {
- "google": {
- "thinkingConfig": {
- "includeThoughts": true
- }
- }
+ "quick": {
+ "id": "gemini-3.1-flash-lite-preview",
+ "name": "Gemini 3.1 Flash Lite Preview",
+ "provider": "Google",
+ "providerId": "google",
+ "providerOptions": {
+ "google": {
+ "thinkingConfig": {
+ "includeThoughts": true
}
}
- },
- "adaptive": {
- "speed": {
- "id": "gemini-3-flash-preview",
- "name": "Gemini 3 Flash Preview",
- "provider": "Google",
- "providerId": "google",
- "providerOptions": {
- "google": {
- "thinkingConfig": {
- "includeThoughts": true
- }
- }
- }
- },
- "quality": {
- "id": "gpt-5.2",
- "name": "GPT-5.2",
- "provider": "OpenAI",
- "providerId": "openai",
- "providerOptions": {
- "openai": {
- "reasoningEffort": "medium",
- "reasoningSummary": "auto"
- }
+ }
+ },
+ "adaptive": {
+ "id": "gemini-3-flash-preview",
+ "name": "Gemini 3 Flash Preview",
+ "provider": "Google",
+ "providerId": "google",
+ "providerOptions": {
+ "google": {
+ "thinkingConfig": {
+ "includeThoughts": true
}
}
}
diff --git a/config/models/default.json b/config/models/default.json
deleted file mode 100644
index fd778866..00000000
--- a/config/models/default.json
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "version": 1,
- "models": {
- "byMode": {
- "quick": {
- "speed": {
- "id": "gpt-5-mini",
- "name": "GPT-5 mini",
- "provider": "OpenAI",
- "providerId": "openai",
- "providerOptions": {
- "openai": {
- "reasoningEffort": "low",
- "reasoningSummary": "auto"
- }
- }
- },
- "quality": {
- "id": "gpt-5.2",
- "name": "GPT-5.2",
- "provider": "OpenAI",
- "providerId": "openai",
- "providerOptions": {
- "openai": {
- "reasoningEffort": "low",
- "reasoningSummary": "auto"
- }
- }
- }
- },
- "adaptive": {
- "speed": {
- "id": "gpt-5-mini",
- "name": "GPT-5 mini",
- "provider": "OpenAI",
- "providerId": "openai",
- "providerOptions": {
- "openai": {
- "reasoningEffort": "medium",
- "reasoningSummary": "auto"
- }
- }
- },
- "quality": {
- "id": "gpt-5.2",
- "name": "GPT-5.2",
- "provider": "OpenAI",
- "providerId": "openai",
- "providerOptions": {
- "openai": {
- "reasoningEffort": "medium",
- "reasoningSummary": "auto"
- }
- }
- }
- }
- },
- "relatedQuestions": {
- "id": "gpt-4.1",
- "name": "GPT-4.1",
- "provider": "OpenAI",
- "providerId": "openai"
- }
- }
-}
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 4e7054be..03c2df0f 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -224,49 +224,34 @@ If `BRAVE_SEARCH_API_KEY` is not configured, `type="general"` searches will auto
## Additional AI Providers
-Models are configured in `config/models/*.json` files. Each provider requires its corresponding API key to be set in the environment variables.
+Model selection behavior differs by deployment type:
+
+- **Cloud (`MORPHIC_CLOUD_DEPLOYMENT=true`)**: models are fixed by `config/models/cloud.json`
+- **Local/Docker (`MORPHIC_CLOUD_DEPLOYMENT=false`)**: models are fetched dynamically from provider APIs and selected in the UI; selection is persisted in `selectedModel` cookie
+
+If no user-selected model exists in Local/Docker, Morphic falls back to an internal default model.
### Model Configuration
-Model configuration files use the following structure:
+Cloud model configuration uses the following structure:
```json
{
- "version": 1,
+ "version": 2,
"models": {
- "byMode": {
- "quick": {
- "speed": {
- "id": "model-id",
- "name": "Model Name",
- "provider": "Provider Name",
- "providerId": "provider-id",
- "providerOptions": {}
- },
- "quality": {
- "id": "model-id",
- "name": "Model Name",
- "provider": "Provider Name",
- "providerId": "provider-id",
- "providerOptions": {}
- }
- },
- "adaptive": {
- "speed": {
- "id": "model-id",
- "name": "Model Name",
- "provider": "Provider Name",
- "providerId": "provider-id",
- "providerOptions": {}
- },
- "quality": {
- "id": "model-id",
- "name": "Model Name",
- "provider": "Provider Name",
- "providerId": "provider-id",
- "providerOptions": {}
- }
- }
+ "quick": {
+ "id": "model-id",
+ "name": "Model Name",
+ "provider": "Provider Name",
+ "providerId": "provider-id",
+ "providerOptions": {}
+ },
+ "adaptive": {
+ "id": "model-id",
+ "name": "Model Name",
+ "provider": "Provider Name",
+ "providerId": "provider-id",
+ "providerOptions": {}
},
"relatedQuestions": {
"id": "model-id",
@@ -278,7 +263,9 @@ Model configuration files use the following structure:
}
```
-Define all four combinations to control which model runs for every search mode (`quick`, `adaptive`) and preference (`speed`, `quality`). For example, you can pair `quick/speed` with `gemini-2.5-flash-lite` while keeping `adaptive/quality` on GPT-5. The default config ships with OpenAI models for every slot so Morphic works out-of-the-box.
+In Cloud, `quick` and `adaptive` are selected by search mode, and `relatedQuestions` is used for follow-up question generation.
+
+In Local/Docker, `cloud.json` is not used for normal chat model selection.
### Supported Providers
@@ -318,16 +305,7 @@ AI_GATEWAY_API_KEY=[YOUR_AI_GATEWAY_API_KEY]
OLLAMA_BASE_URL=http://localhost:11434
```
-Then update your `config/models/*.json` files to use Ollama models:
-
-```json
-{
- "id": "qwen3:latest",
- "name": "Qwen 3",
- "provider": "Ollama",
- "providerId": "ollama"
-}
-```
+When configured, Ollama models are discovered dynamically and appear in the Local/Docker model selector.
**Important Notes:**
diff --git a/lib/agents/generate-related-questions.ts b/lib/agents/generate-related-questions.ts
index c6d93761..3ecc7cf2 100644
--- a/lib/agents/generate-related-questions.ts
+++ b/lib/agents/generate-related-questions.ts
@@ -2,6 +2,7 @@ import { type ModelMessage, Output, streamText } from 'ai'
import { getRelatedQuestionsModel } from '../config/model-types'
import { relatedQuestionSchema } from '../schema/related'
+import { Model } from '../types/models'
import { getModel } from '../utils/registry'
import { isTracingEnabled } from '../utils/telemetry'
@@ -10,10 +11,11 @@ import { RELATED_QUESTIONS_PROMPT } from './prompts/related-questions-prompt'
export function createRelatedQuestionsStream(
messages: ModelMessage[],
abortSignal?: AbortSignal,
- parentTraceId?: string
+ parentTraceId?: string,
+ localSelectedModel?: Model
) {
- // Use the related questions model configuration from JSON
- const relatedModel = getRelatedQuestionsModel()
+ // Use cloud related-questions model when available, otherwise local default model.
+ const relatedModel = getRelatedQuestionsModel(localSelectedModel)
const modelId = `${relatedModel.providerId}:${relatedModel.id}`
return streamText({
diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.ts
index 1b02833a..c404c65e 100644
--- a/lib/agents/researcher.ts
+++ b/lib/agents/researcher.ts
@@ -1,7 +1,6 @@
import { stepCountIs, tool, ToolLoopAgent } from 'ai'
import type { ResearcherTools } from '@/lib/types/agent'
-import { type ModelType } from '@/lib/types/model-type'
import { type Model } from '@/lib/types/models'
import { fetchTool } from '../tools/fetch'
@@ -69,14 +68,12 @@ export function createResearcher({
model,
modelConfig,
parentTraceId,
- searchMode = 'adaptive',
- modelType
+ searchMode = 'adaptive'
}: {
model: string
modelConfig?: Model
parentTraceId?: string
searchMode?: SearchMode
- modelType?: ModelType
}) {
try {
const currentDate = new Date().toLocaleString()
@@ -108,7 +105,7 @@ export function createResearcher({
systemPrompt = getAdaptiveModePrompt()
activeToolsList = ['search', 'fetch', 'todoWrite']
console.log(
- `[Researcher] Adaptive mode: maxSteps=50, modelType=${modelType}, tools=[${activeToolsList.join(', ')}]`
+ `[Researcher] Adaptive mode: maxSteps=50, tools=[${activeToolsList.join(', ')}]`
)
maxSteps = 50
searchTool = originalSearchTool
diff --git a/lib/analytics/track-chat-event.ts b/lib/analytics/track-chat-event.ts
index 370d7c1b..baeb074b 100644
--- a/lib/analytics/track-chat-event.ts
+++ b/lib/analytics/track-chat-event.ts
@@ -18,12 +18,12 @@ import type { ChatEventData } from './types'
* ```typescript
* await trackChatEvent({
* searchMode: 'quick',
- * modelType: 'quality',
* conversationTurn: 1,
* isNewChat: true,
* trigger: 'submit-message',
* chatId: 'clx3k2j5m0000qzrmn4y8b9wy',
* userId: '550e8400-e29b-41d4-a716-446655440000',
+ * providerId: 'openai',
* modelId: 'gpt-4'
* })
* ```
@@ -38,12 +38,12 @@ export async function trackChatEvent(data: ChatEventData): Promise<void> {
// Send event to Vercel Analytics
await track('chat_message_sent', {
searchMode: data.searchMode,
- modelType: data.modelType,
conversationTurn: data.conversationTurn,
isNewChat: data.isNewChat,
trigger: data.trigger,
chatId: data.chatId, // CUID2 - safe for tracking
userId: data.userId, // Supabase UUID - pseudonymized identifier
+ providerId: data.providerId,
modelId: data.modelId
})
} catch (error) {
diff --git a/lib/analytics/types.ts b/lib/analytics/types.ts
index fa2877c7..85f66dd2 100644
--- a/lib/analytics/types.ts
+++ b/lib/analytics/types.ts
@@ -12,8 +12,6 @@
export interface ChatEventData {
/** Search mode used for the chat */
searchMode: 'quick' | 'planning' | 'adaptive'
- /** Model type preference */
- modelType: 'speed' | 'quality'
/** Conversation turn number (1-indexed, represents follow-up count) */
conversationTurn: number
/** Whether this is a new chat session */
@@ -24,6 +22,8 @@ export interface ChatEventData {
chatId: string
/** User ID (Supabase UUID - pseudonymized identifier) */
userId: string
+ /** Provider identifier used for the chat */
+ providerId: string
/** Model identifier used for the chat */
modelId: string
}
diff --git a/lib/config/default-model.ts b/lib/config/default-model.ts
new file mode 100644
index 00000000..c09ff8b5
--- /dev/null
+++ b/lib/config/default-model.ts
@@ -0,0 +1,14 @@
+import { Model } from '@/lib/types/models'
+
+export const DEFAULT_MODEL: Model = {
+ id: 'gpt-5-mini',
+ name: 'GPT-5 mini',
+ provider: 'OpenAI',
+ providerId: 'openai',
+ providerOptions: {
+ openai: {
+ reasoningEffort: 'low',
+ reasoningSummary: 'auto'
+ }
+ }
+}
diff --git a/lib/config/load-models-config.ts b/lib/config/load-models-config.ts
index 87d03778..debd9fc8 100644
--- a/lib/config/load-models-config.ts
+++ b/lib/config/load-models-config.ts
@@ -1,22 +1,20 @@
import cloudConfig from '@/config/models/cloud.json'
-import defaultConfig from '@/config/models/default.json'
-import { ModelType } from '@/lib/types/model-type'
import { Model } from '@/lib/types/models'
import { SearchMode } from '@/lib/types/search'
export interface ModelsConfig {
version: number
models: {
- byMode: Record<SearchMode, Record<ModelType, Model>>
+ quick: Model
+ adaptive: Model
relatedQuestions: Model
}
}
let cachedConfig: ModelsConfig | null = null
-let cachedProfile: string | null = null
+let cachedForCloudDeployment = false
-const VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']
const VALID_SEARCH_MODES: SearchMode[] = ['quick', 'adaptive']
function validateModelsConfigStructure(
@@ -32,63 +30,63 @@ function validateModelsConfigStructure(
if (!parsed.models || typeof parsed.models !== 'object') {
throw new Error('Invalid models config: missing models')
}
- if (!parsed.models.byMode || !parsed.models.relatedQuestions) {
+ if (!parsed.models.relatedQuestions) {
throw new Error('Invalid models config: missing required sections')
}
- if (typeof parsed.models.byMode !== 'object') {
- throw new Error('Invalid models config: byMode must be an object')
- }
if (typeof parsed.models.relatedQuestions !== 'object') {
throw new Error('Invalid models config: relatedQuestions must be an object')
}
for (const searchMode of VALID_SEARCH_MODES) {
- const modeEntry = parsed.models.byMode[searchMode]
+ const modeEntry = parsed.models[searchMode]
if (!modeEntry || typeof modeEntry !== 'object') {
throw new Error(
`Invalid models config: missing configuration for mode "${searchMode}"`
)
}
- for (const modelType of VALID_MODEL_TYPES) {
- if (!modeEntry[modelType]) {
- throw new Error(
- `Invalid models config: missing definition for mode "${searchMode}" and model type "${modelType}"`
- )
- }
- }
}
}
+export function isCloudDeployment(): boolean {
+ return process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+}
+
export async function loadModelsConfig(): Promise<ModelsConfig> {
- const profile =
- process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true' ? 'cloud' : 'default'
+ if (!isCloudDeployment()) {
+ throw new Error(
+ 'loadModelsConfig is only available when MORPHIC_CLOUD_DEPLOYMENT=true'
+ )
+ }
- if (cachedConfig && cachedProfile === profile) {
+ if (cachedConfig && cachedForCloudDeployment) {
return cachedConfig
}
- const config = profile === 'cloud' ? cloudConfig : defaultConfig
+ const config = cloudConfig
validateModelsConfigStructure(config)
cachedConfig = config as ModelsConfig
- cachedProfile = profile
+ cachedForCloudDeployment = true
return cachedConfig
}
// Synchronous load (for code paths that need sync access)
export function loadModelsConfigSync(): ModelsConfig {
- const profile =
- process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true' ? 'cloud' : 'default'
+ if (!isCloudDeployment()) {
+ throw new Error(
+ 'loadModelsConfigSync is only available when MORPHIC_CLOUD_DEPLOYMENT=true'
+ )
+ }
- if (cachedConfig && cachedProfile === profile) {
+ if (cachedConfig && cachedForCloudDeployment) {
return cachedConfig
}
- const config = profile === 'cloud' ? cloudConfig : defaultConfig
+ const config = cloudConfig
validateModelsConfigStructure(config)
cachedConfig = config as ModelsConfig
- cachedProfile = profile
+ cachedForCloudDeployment = true
return cachedConfig
}
diff --git a/lib/config/model-selection-cookie.ts b/lib/config/model-selection-cookie.ts
new file mode 100644
index 00000000..2ea55e77
--- /dev/null
+++ b/lib/config/model-selection-cookie.ts
@@ -0,0 +1,40 @@
+export const MODEL_SELECTION_COOKIE = 'selectedModel'
+
+export interface ParsedModelSelectionCookie {
+ providerId: string
+ modelId: string
+}
+
+export function serializeModelSelectionCookie(
+ value: ParsedModelSelectionCookie
+): string {
+ return `${encodeURIComponent(value.providerId)}:${encodeURIComponent(
+ value.modelId
+ )}`
+}
+
+export function parseModelSelectionCookie(
+ rawValue?: string | null
+): ParsedModelSelectionCookie | null {
+ if (!rawValue) {
+ return null
+ }
+
+ const separatorIndex = rawValue.indexOf(':')
+ if (separatorIndex <= 0 || separatorIndex === rawValue.length - 1) {
+ return null
+ }
+
+ try {
+ const providerId = decodeURIComponent(rawValue.slice(0, separatorIndex))
+ const modelId = decodeURIComponent(rawValue.slice(separatorIndex + 1))
+
+ if (!providerId || !modelId) {
+ return null
+ }
+
+ return { providerId, modelId }
+ } catch {
+ return null
+ }
+}
diff --git a/lib/config/model-types.ts b/lib/config/model-types.ts
index 93c9214f..4a11293d 100644
--- a/lib/config/model-types.ts
+++ b/lib/config/model-types.ts
@@ -1,20 +1,27 @@
-import { ModelType } from '@/lib/types/model-type'
+import { DEFAULT_MODEL } from '@/lib/config/default-model'
import { Model } from '@/lib/types/models'
import { SearchMode } from '@/lib/types/search'
-import { getModelsConfig } from './load-models-config'
+import { getModelsConfig, isCloudDeployment } from './load-models-config'
+
+// Retrieve the cloud model assigned to a specific search mode.
+export function getModelForMode(mode: SearchMode): Model | undefined {
+ if (!isCloudDeployment()) {
+ return undefined
+ }
-// Retrieve the model assigned to a specific search mode and model type combination.
-export function getModelForModeAndType(
- mode: SearchMode,
- type: ModelType
-): Model | undefined {
const cfg = getModelsConfig()
- return cfg.models.byMode?.[mode]?.[type]
+ return cfg.models?.[mode]
}
-// Accessor for the related questions model configuration.
-export function getRelatedQuestionsModel(): Model {
+// Accessor for related questions model.
+// In local/docker, reuse the selected local model when available to keep
+// provider routing consistent with the main chat flow.
+export function getRelatedQuestionsModel(localSelectedModel?: Model): Model {
+ if (!isCloudDeployment()) {
+ return localSelectedModel ?? DEFAULT_MODEL
+ }
+
const cfg = getModelsConfig()
return cfg.models.relatedQuestions
}
diff --git a/lib/config/ollama-validator.ts b/lib/config/ollama-validator.ts
index 241bb992..b05062b4 100644
--- a/lib/config/ollama-validator.ts
+++ b/lib/config/ollama-validator.ts
@@ -1,4 +1,7 @@
-import { loadModelsConfig } from '@/lib/config/load-models-config'
+import {
+ isCloudDeployment,
+ loadModelsConfig
+} from '@/lib/config/load-models-config'
import { OllamaClient } from '@/lib/ollama/client'
import { Model } from '@/lib/types/models'
@@ -13,23 +16,26 @@ let validationError: Error | null = null
* Extract all Ollama models from the configuration
*/
async function getConfiguredOllamaModels(): Promise<Model[]> {
+ if (!isCloudDeployment()) {
+ return []
+ }
+
const ollamaModels: Model[] = []
try {
const config = await loadModelsConfig()
- // Check byMode models
- for (const mode of Object.values(config.models.byMode)) {
- for (const model of Object.values(mode as Record<string, Model>)) {
- if (model.providerId === 'ollama') {
- ollamaModels.push(model)
- }
- }
- }
+ // Check quick/adaptive models
+ const cloudModels = [
+ config.models.quick,
+ config.models.adaptive,
+ config.models.relatedQuestions
+ ]
- // Check relatedQuestions model
- if (config.models.relatedQuestions?.providerId === 'ollama') {
- ollamaModels.push(config.models.relatedQuestions)
+ for (const model of cloudModels) {
+ if (model?.providerId === 'ollama') {
+ ollamaModels.push(model)
+ }
}
} catch (error) {
console.warn('Failed to load model configuration:', error)
diff --git a/lib/model-selector/get-model-selector-data.ts b/lib/model-selector/get-model-selector-data.ts
new file mode 100644
index 00000000..146488be
--- /dev/null
+++ b/lib/model-selector/get-model-selector-data.ts
@@ -0,0 +1,85 @@
+import { cookies } from 'next/headers'
+
+import { DEFAULT_MODEL } from '@/lib/config/default-model'
+import {
+ MODEL_SELECTION_COOKIE,
+ parseModelSelectionCookie
+} from '@/lib/config/model-selection-cookie'
+import { fetchAvailableModels } from '@/lib/models/fetch-models'
+import { ModelSelectorData } from '@/lib/types/model-selector'
+import { Model } from '@/lib/types/models'
+
+import 'server-only'
+
+function ensureModelInGroup(
+ modelsByProvider: Record<string, Model[]>,
+ model: Model
+): Record<string, Model[]> {
+ const next = { ...modelsByProvider }
+ const providerModels = next[model.provider] ?? []
+ const exists = providerModels.some(
+ item => item.id === model.id && item.providerId === model.providerId
+ )
+
+ if (!exists) {
+ next[model.provider] = [...providerModels, model].sort((a, b) =>
+ a.name.localeCompare(b.name)
+ )
+ }
+
+ return next
+}
+
+function modelKey(model: Model): string {
+ return `${model.providerId}:${model.id}`
+}
+
+function resolveSelectedModelKey(
+ modelsByProvider: Record<string, Model[]>,
+ defaultModel: Model,
+ cookieValue?: string
+): string {
+ const parsedCookie = parseModelSelectionCookie(cookieValue)
+ if (!parsedCookie) {
+ return modelKey(defaultModel)
+ }
+
+ const matched = Object.values(modelsByProvider)
+ .flat()
+ .some(
+ model =>
+ model.providerId === parsedCookie.providerId &&
+ model.id === parsedCookie.modelId
+ )
+
+ return matched
+ ? `${parsedCookie.providerId}:${parsedCookie.modelId}`
+ : modelKey(defaultModel)
+}
+
+export async function getModelSelectorData(): Promise<ModelSelectorData> {
+ if (process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true') {
+ return {
+ enabled: false,
+ modelsByProvider: {},
+ defaultModel: DEFAULT_MODEL,
+ selectedModelKey: modelKey(DEFAULT_MODEL)
+ }
+ }
+
+ const fetchedModels = await fetchAvailableModels()
+ const modelsByProvider = ensureModelInGroup(fetchedModels, DEFAULT_MODEL)
+ const cookieStore = await cookies()
+ const selectedModelKey = resolveSelectedModelKey(
+ modelsByProvider,
+ DEFAULT_MODEL,
+ cookieStore.get(MODEL_SELECTION_COOKIE)?.value
+ )
+
+ return {
+ enabled: true,
+ modelsByProvider,
+ defaultModel: DEFAULT_MODEL,
+ selectedModelKey
+ }
+}
diff --git a/lib/models/__tests__/fetch-models.test.ts b/lib/models/__tests__/fetch-models.test.ts
new file mode 100644
index 00000000..d5b0709e
--- /dev/null
+++ b/lib/models/__tests__/fetch-models.test.ts
@@ -0,0 +1,236 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@ai-sdk/gateway', () => ({
+ createGateway: vi.fn()
+}))
+
+vi.mock('@/lib/utils/registry', () => ({
+ isProviderEnabled: vi.fn()
+}))
+
+import { createGateway } from '@ai-sdk/gateway'
+
+import * as fetchModels from '@/lib/models/fetch-models'
+import { isProviderEnabled } from '@/lib/utils/registry'
+
+const mockCreateGateway = vi.mocked(createGateway)
+const mockIsProviderEnabled = vi.mocked(isProviderEnabled)
+
+describe('fetch-models', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ delete process.env.OLLAMA_BASE_URL
+ })
+
+ it('filters non-chat and snapshot OpenAI models', async () => {
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'openai'
+ )
+
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: async () => ({
+ data: [
+ { id: 'gpt-5-mini' },
+ { id: 'gpt-4o' },
+ { id: 'gpt-5-2025-08-07' },
+ { id: 'gpt-5-chat-latest' },
+ { id: 'gpt-4-turbo' },
+ { id: 'text-embedding-3-large' },
+ { id: 'o3-mini' },
+ { id: 'whisper-1' },
+ { id: 'dall-e-3' }
+ ]
+ })
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const models = await fetchModels.fetchOpenAIModels()
+ expect(models.map(model => model.id)).toEqual(['gpt-5-mini', 'o3-mini'])
+ })
+
+ it('groups models by provider and caches results', async () => {
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'openai' || providerId === 'anthropic'
+ )
+
+ const fetchMock = vi.fn((url: string) => {
+ if (url.includes('api.openai.com/v1/models')) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: async () => ({
+ data: [{ id: 'gpt-5-mini' }]
+ })
+ })
+ }
+
+ if (url.includes('api.anthropic.com/v1/models')) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: async () => ({
+ data: [
+ { id: 'claude-sonnet-4', display_name: 'Claude Sonnet 4' },
+ { id: 'claude-3-5-sonnet', display_name: 'Claude 3.5 Sonnet' }
+ ],
+ has_more: false
+ })
+ })
+ }
+
+ throw new Error(`Unexpected URL: ${url}`)
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const grouped = await fetchModels.fetchAvailableModels({
+ forceRefresh: true
+ })
+ expect(Object.keys(grouped).sort()).toEqual(['Anthropic', 'OpenAI'])
+ expect(grouped.OpenAI?.[0]?.id).toBe('gpt-5-mini')
+ expect(grouped.Anthropic?.[0]?.id).toBe('claude-sonnet-4')
+
+ await fetchModels.fetchAvailableModels()
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('normalizes gateway models with providerId as gateway', async () => {
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'gateway'
+ )
+
+ const getAvailableModels = vi.fn().mockResolvedValue({
+ models: [
+ {
+ id: 'openai/gpt-5-mini',
+ name: 'GPT-5 Mini',
+ modelType: 'language'
+ },
+ {
+ id: 'openai/gpt-4o',
+ name: 'GPT-4o',
+ modelType: 'language'
+ },
+ {
+ id: 'openai/gpt-5-2025-08-07',
+ name: 'GPT-5 Snapshot',
+ modelType: 'language'
+ },
+ {
+ id: 'google/gemini-2.0-flash',
+ name: 'Gemini 2.0 Flash',
+ modelType: 'language'
+ },
+ {
+ id: 'openai/text-embedding-3-small',
+ name: 'text-embedding-3-small',
+ modelType: 'embedding'
+ }
+ ]
+ })
+ mockCreateGateway.mockReturnValue({
+ getAvailableModels
+ } as any)
+
+ const models = await fetchModels.fetchGatewayModels()
+ expect(models).toEqual([
+ {
+ id: 'openai/gpt-5-mini',
+ name: 'GPT-5 Mini',
+ provider: 'Gateway',
+ providerId: 'gateway'
+ }
+ ])
+ })
+
+ it('filters google models to active gemini chat models', async () => {
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'google'
+ )
+
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: async () => ({
+ models: [
+ {
+ name: 'models/gemini-2.5-pro',
+ displayName: 'Gemini 2.5 Pro',
+ supportedGenerationMethods: ['generateContent']
+ },
+ {
+ name: 'models/gemini-2.5-pro-preview-09-2025',
+ displayName: 'Gemini 2.5 Pro Preview',
+ supportedGenerationMethods: ['generateContent']
+ },
+ {
+ name: 'models/gemini-2.5-flash-image',
+ displayName: 'Gemini 2.5 Flash Image',
+ supportedGenerationMethods: ['generateContent']
+ },
+ {
+ name: 'models/gemini-2.0-flash',
+ displayName: 'Gemini 2.0 Flash',
+ supportedGenerationMethods: ['generateContent']
+ }
+ ]
+ })
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const models = await fetchModels.fetchGoogleModels()
+ expect(models.map(model => model.id)).toEqual(['gemini-2.5-pro'])
+ })
+
+ it('adds think provider options for ollama thinking models', async () => {
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'ollama'
+ )
+ process.env.OLLAMA_BASE_URL = 'http://localhost:11434'
+
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: async () => ({
+ models: [{ name: 'deepseek-r1:8b' }, { name: 'llama3.2:3b' }]
+ })
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const models = await fetchModels.fetchOllamaModels()
+ expect(models).toEqual([
+ {
+ id: 'deepseek-r1:8b',
+ name: 'deepseek-r1:8b',
+ provider: 'Ollama',
+ providerId: 'ollama',
+ providerOptions: {
+ ollama: {
+ think: true
+ }
+ }
+ },
+ {
+ id: 'llama3.2:3b',
+ name: 'llama3.2:3b',
+ provider: 'Ollama',
+ providerId: 'ollama',
+ providerOptions: {
+ ollama: {
+ think: true
+ }
+ }
+ }
+ ])
+ })
+})
diff --git a/lib/models/fetch-models.ts b/lib/models/fetch-models.ts
new file mode 100644
index 00000000..b1623bb0
--- /dev/null
+++ b/lib/models/fetch-models.ts
@@ -0,0 +1,418 @@
+import { createGateway } from '@ai-sdk/gateway'
+
+import { Model } from '@/lib/types/models'
+import { isProviderEnabled } from '@/lib/utils/registry'
+
+export type ModelsByProvider = Record<string, Model[]>
+
+const MODEL_CACHE_TTL_MS = 2 * 60 * 1000
+const DATE_SNAPSHOT_SUFFIX_REGEX = /-\d{4}-\d{2}-\d{2}$/
+const GOOGLE_PREVIEW_SNAPSHOT_REGEX = /preview-\d{2}-\d{2,4}$/i
+const OPENAI_ALLOWED_PREFIXES = ['gpt-5', 'o1', 'o3', 'o4']
+const OPENAI_EXCLUDED_KEYWORDS = [
+ 'embed',
+ 'tts',
+ 'whisper',
+ 'dall-e',
+ 'davinci',
+ 'babbage',
+ 'ft:',
+ 'image',
+ 'audio',
+ 'realtime',
+ 'codex',
+ 'search',
+ 'transcribe',
+ 'deep-research',
+ 'oss',
+ 'instruct',
+ 'chat-latest'
+]
+const ANTHROPIC_ALLOWED_PREFIXES = [
+ 'claude-opus-4',
+ 'claude-sonnet-4',
+ 'claude-haiku-4'
+]
+const GOOGLE_ALLOWED_PREFIXES = ['gemini-2.5', 'gemini-3']
+const GOOGLE_EXCLUDED_KEYWORDS = ['image', 'live', 'native-audio', 'embedding']
+
+let modelsCache:
+ | {
+ expiresAt: number
+ value: ModelsByProvider
+ }
+ | undefined
+
+function sortModels(models: Model[]): Model[] {
+ return [...models].sort((a, b) => a.name.localeCompare(b.name))
+}
+
+function dedupeModels(models: Model[]): Model[] {
+ const seen = new Set<string>()
+ const deduped: Model[] = []
+
+ for (const model of models) {
+ const key = `${model.provider}|${model.providerId}|${model.id}`
+ if (seen.has(key)) {
+ continue
+ }
+
+ seen.add(key)
+ deduped.push(model)
+ }
+
+ return deduped
+}
+
+function groupByProvider(models: Model[]): ModelsByProvider {
+ return models.reduce<ModelsByProvider>((acc, model) => {
+ const key = model.provider
+ if (!acc[key]) {
+ acc[key] = []
+ }
+ acc[key].push(model)
+ return acc
+ }, {})
+}
+
+function hasDateSnapshotSuffix(modelId: string): boolean {
+ return DATE_SNAPSHOT_SUFFIX_REGEX.test(modelId)
+}
+
+function passesOpenAIFilters(id: string): boolean {
+ if (hasDateSnapshotSuffix(id)) {
+ return false
+ }
+
+ if (!OPENAI_ALLOWED_PREFIXES.some(prefix => id.startsWith(prefix))) {
+ return false
+ }
+
+ return !OPENAI_EXCLUDED_KEYWORDS.some(keyword =>
+ id.toLowerCase().includes(keyword)
+ )
+}
+
+function passesAnthropicFilters(id: string): boolean {
+ if (hasDateSnapshotSuffix(id)) {
+ return false
+ }
+
+ return ANTHROPIC_ALLOWED_PREFIXES.some(prefix => id.startsWith(prefix))
+}
+
+function passesGoogleFilters(id: string): boolean {
+ if (hasDateSnapshotSuffix(id)) {
+ return false
+ }
+
+ if (GOOGLE_PREVIEW_SNAPSHOT_REGEX.test(id)) {
+ return false
+ }
+
+ if (!GOOGLE_ALLOWED_PREFIXES.some(prefix => id.startsWith(prefix))) {
+ return false
+ }
+
+ return !GOOGLE_EXCLUDED_KEYWORDS.some(keyword =>
+ id.toLowerCase().includes(keyword)
+ )
+}
+
+function passesGatewayFilters(id: string): boolean {
+ if (hasDateSnapshotSuffix(id)) {
+ return false
+ }
+
+ const separatorIndex = id.indexOf('/')
+ if (separatorIndex <= 0) {
+ return true
+ }
+
+ const provider = id.slice(0, separatorIndex)
+ const modelId = id.slice(separatorIndex + 1)
+ if (!modelId) {
+ return false
+ }
+
+ switch (provider) {
+ case 'openai':
+ return passesOpenAIFilters(modelId)
+ case 'anthropic':
+ return passesAnthropicFilters(modelId)
+ case 'google':
+ return passesGoogleFilters(modelId)
+ default:
+ return true
+ }
+}
+
+async function fetchJson(
+ url: string,
+ headers: HeadersInit
+): Promise<Record<string, any>> {
+ const response = await fetch(url, { headers, method: 'GET' })
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)
+ }
+ return (await response.json()) as Record<string, any>
+}
+
+export async function fetchOpenAIModels(): Promise<Model[]> {
+ if (!isProviderEnabled('openai')) {
+ return []
+ }
+
+ try {
+ const json = await fetchJson('https://api.openai.com/v1/models', {
+ Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
+ })
+
+ const data = Array.isArray(json?.data) ? json.data : []
+ return sortModels(
+ dedupeModels(
+ data
+ .map(item => String(item?.id ?? ''))
+ .filter(Boolean)
+ .filter(passesOpenAIFilters)
+ .map(id => ({
+ id,
+ name: id,
+ provider: 'OpenAI',
+ providerId: 'openai'
+ }))
+ )
+ )
+ } catch (error) {
+ console.warn('[ModelFetch] Failed to fetch OpenAI models:', error)
+ return []
+ }
+}
+
+export async function fetchAnthropicModels(): Promise<Model[]> {
+ if (!isProviderEnabled('anthropic')) {
+ return []
+ }
+
+ try {
+ const models: Model[] = []
+ const baseUrl = 'https://api.anthropic.com/v1/models'
+ let afterId: string | undefined
+ let hasMore = true
+
+ while (hasMore) {
+ const url = new URL(baseUrl)
+ url.searchParams.set('limit', '100')
+ if (afterId) {
+ url.searchParams.set('after_id', afterId)
+ }
+
+ const json = await fetchJson(url.toString(), {
+ 'x-api-key': process.env.ANTHROPIC_API_KEY!,
+ 'anthropic-version': '2023-06-01'
+ })
+
+ const data = Array.isArray(json?.data) ? json.data : []
+ models.push(
+ ...data
+ .map(item => {
+ const id = String(item?.id ?? '')
+ if (!id) return null
+ return {
+ id,
+ name: String(item?.display_name ?? id),
+ provider: 'Anthropic',
+ providerId: 'anthropic'
+ } satisfies Model
+ })
+ .filter((model): model is Model => model !== null)
+ .filter(model => passesAnthropicFilters(model.id))
+ )
+
+ hasMore = Boolean(json?.has_more)
+ afterId = typeof json?.last_id === 'string' ? json.last_id : undefined
+
+ if (!hasMore || !afterId) {
+ break
+ }
+ }
+
+ return sortModels(dedupeModels(models))
+ } catch (error) {
+ console.warn('[ModelFetch] Failed to fetch Anthropic models:', error)
+ return []
+ }
+}
+
+export async function fetchGoogleModels(): Promise<Model[]> {
+ if (!isProviderEnabled('google')) {
+ return []
+ }
+
+ try {
+ const models: Model[] = []
+ const apiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY
+ let nextPageToken: string | undefined
+ while (true) {
+ const url = new URL(
+ 'https://generativelanguage.googleapis.com/v1beta/models'
+ )
+ url.searchParams.set('key', apiKey!)
+ if (nextPageToken) {
+ url.searchParams.set('pageToken', nextPageToken)
+ }
+
+ const json = await fetchJson(url.toString(), {})
+ const data = Array.isArray(json?.models) ? json.models : []
+
+ models.push(
+ ...data
+ .filter(item =>
+ Array.isArray(item?.supportedGenerationMethods)
+ ? item.supportedGenerationMethods.includes('generateContent')
+ : false
+ )
+ .map(item => {
+ const rawName = String(item?.name ?? '')
+ const id = rawName.startsWith('models/')
+ ? rawName.slice('models/'.length)
+ : rawName
+ if (!id) return null
+ return {
+ id,
+ name: String(item?.displayName ?? id),
+ provider: 'Google',
+ providerId: 'google'
+ } satisfies Model
+ })
+ .filter((model): model is Model => model !== null)
+ .filter(model => passesGoogleFilters(model.id))
+ )
+
+ nextPageToken =
+ typeof json?.nextPageToken === 'string' ? json.nextPageToken : undefined
+ if (!nextPageToken) {
+ break
+ }
+ }
+
+ return sortModels(dedupeModels(models))
+ } catch (error) {
+ console.warn('[ModelFetch] Failed to fetch Google models:', error)
+ return []
+ }
+}
+
+export async function fetchOllamaModels(): Promise<Model[]> {
+ if (!isProviderEnabled('ollama')) {
+ return []
+ }
+
+ try {
+ const baseUrl = process.env.OLLAMA_BASE_URL
+ const url = new URL('/api/tags', baseUrl).toString()
+ const json = await fetchJson(url, {})
+ const data = Array.isArray(json?.models) ? json.models : []
+
+ return sortModels(
+ dedupeModels(
+ data
+ .map(item => String(item?.name ?? ''))
+ .filter(Boolean)
+ .filter(name => !name.toLowerCase().includes('embed'))
+ .map(
+ name =>
+ ({
+ id: name,
+ name,
+ provider: 'Ollama',
+ providerId: 'ollama',
+ providerOptions: {
+ ollama: {
+ think: true
+ }
+ }
+ }) satisfies Model
+ )
+ )
+ )
+ } catch (error) {
+ console.warn('[ModelFetch] Failed to fetch Ollama models:', error)
+ return []
+ }
+}
+
+export async function fetchGatewayModels(): Promise<Model[]> {
+ if (!isProviderEnabled('gateway')) {
+ return []
+ }
+
+ try {
+ const gateway = createGateway({
+ apiKey: process.env.AI_GATEWAY_API_KEY
+ })
+
+ const metadata = await gateway.getAvailableModels()
+ const availableModels = metadata.models ?? []
+
+ return sortModels(
+ dedupeModels(
+ availableModels
+ .filter(model => model?.modelType === 'language')
+ .map(model => {
+ const id = String(model?.id ?? '')
+ if (!id) return null
+ return {
+ id,
+ name: String(model?.name ?? id),
+ provider: 'Gateway',
+ providerId: 'gateway'
+ } satisfies Model
+ })
+ .filter((model): model is Model => model !== null)
+ .filter(model => passesGatewayFilters(model.id))
+ )
+ )
+ } catch (error) {
+ console.warn('[ModelFetch] Failed to fetch Gateway models:', error)
+ return []
+ }
+}
+
+export async function fetchAvailableModels(options?: {
+ forceRefresh?: boolean
+}): Promise<ModelsByProvider> {
+ const forceRefresh = options?.forceRefresh === true
+ const now = Date.now()
+
+ if (!forceRefresh && modelsCache && modelsCache.expiresAt > now) {
+ return modelsCache.value
+ }
+
+ const [openai, anthropic, google, ollama, gateway] = await Promise.all([
+ fetchOpenAIModels(),
+ fetchAnthropicModels(),
+ fetchGoogleModels(),
+ fetchOllamaModels(),
+ fetchGatewayModels()
+ ])
+
+ const grouped = groupByProvider(
+ dedupeModels([...openai, ...anthropic, ...google, ...ollama, ...gateway])
+ )
+
+ // Keep stable ordering for each provider list.
+ const normalized = Object.fromEntries(
+ Object.entries(grouped).map(([provider, models]) => [
+ provider,
+ sortModels(models)
+ ])
+ )
+
+ modelsCache = {
+ value: normalized,
+ expiresAt: now + MODEL_CACHE_TTL_MS
+ }
+
+ return normalized
+}
diff --git a/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts b/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts
index 8f3a6aa5..6f51c341 100644
--- a/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts
+++ b/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts
@@ -8,8 +8,7 @@ describe('createEphemeralChatStreamResponse', () => {
messages: [],
model: { providerId: 'openai', id: 'gpt-4o-mini' } as any,
abortSignal: new AbortController().signal,
- searchMode: 'quick',
- modelType: 'speed'
+ searchMode: 'quick'
})
expect(response.status).toBe(400)
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 38c3c628..b7d3eeea 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -46,8 +46,7 @@ export async function createChatStreamResponse(
messageId,
abortSignal,
isNewChat,
- searchMode,
- modelType
+ searchMode
} = config
// Verify that chatId is provided
@@ -126,13 +125,12 @@ export async function createChatStreamResponse(
const messagesToModel = await prepareMessages(context, message)
perfTime('prepareMessages completed (stream)', prepareStart)
- // Get the researcher agent with parent trace ID, search mode, and model type
+ // Get the researcher agent with parent trace ID and search mode.
const researchAgent = researcher({
model: context.modelId,
modelConfig: model,
parentTraceId,
- searchMode,
- modelType
+ searchMode
})
// For OpenAI models, strip reasoning parts from UIMessages before conversion
@@ -222,7 +220,8 @@ export async function createChatStreamResponse(
writer,
messagesForQuestions,
abortSignal,
- parentTraceId
+ parentTraceId,
+ model
)
}
} catch (error) {
diff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.ts
index e04de70c..7dd0434f 100644
--- a/lib/streaming/create-ephemeral-chat-stream-response.ts
+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts
@@ -26,7 +26,7 @@ import { BaseStreamConfig } from './types'
type EphemeralStreamConfig = Pick<
BaseStreamConfig,
- 'model' | 'abortSignal' | 'searchMode' | 'modelType'
+ 'model' | 'abortSignal' | 'searchMode'
> & {
messages: UIMessage[]
chatId?: string
@@ -35,7 +35,7 @@ type EphemeralStreamConfig = Pick<
export async function createEphemeralChatStreamResponse(
config: EphemeralStreamConfig
): Promise<Response> {
- const { messages, model, abortSignal, searchMode, modelType, chatId } = config
+ const { messages, model, abortSignal, searchMode, chatId } = config
if (!messages || messages.length === 0) {
return new Response('messages are required', {
@@ -59,8 +59,7 @@ export async function createEphemeralChatStreamResponse(
chatId,
userId: 'guest',
modelId: `${model.providerId}:${model.id}`,
- trigger: 'submit-message',
- modelType
+ trigger: 'submit-message'
}
})
}
@@ -91,8 +90,7 @@ export async function createEphemeralChatStreamResponse(
model: `${model.providerId}:${model.id}`,
modelConfig: model,
parentTraceId,
- searchMode,
- modelType
+ searchMode
})
const result = await researchAgent.stream({
@@ -127,7 +125,8 @@ export async function createEphemeralChatStreamResponse(
writer,
messagesForQuestions,
abortSignal,
- parentTraceId
+ parentTraceId,
+ model
)
}
} finally {
diff --git a/lib/streaming/helpers/stream-related-questions.ts b/lib/streaming/helpers/stream-related-questions.ts
index 49483407..401b4672 100644
--- a/lib/streaming/helpers/stream-related-questions.ts
+++ b/lib/streaming/helpers/stream-related-questions.ts
@@ -3,6 +3,7 @@ import { ModelMessage, UIMessageStreamWriter } from 'ai'
import { createRelatedQuestionsStream } from '@/lib/agents/generate-related-questions'
import { generateId } from '@/lib/db/schema'
import { relatedSchema } from '@/lib/schema/related'
+import { Model } from '@/lib/types/models'
/**
* Generates and streams related questions if there are tool calls in the response
@@ -11,7 +12,8 @@ export async function streamRelatedQuestions(
writer: UIMessageStreamWriter,
messages: ModelMessage[],
abortSignal?: AbortSignal,
- parentTraceId?: string
+ parentTraceId?: string,
+ localSelectedModel?: Model
): Promise<{
questionPartId?: string
questions?: Array<{ question: string }>
@@ -35,7 +37,8 @@ export async function streamRelatedQuestions(
const relatedQuestionsResult = createRelatedQuestionsStream(
messages,
abortSignal,
- parentTraceId
+ parentTraceId,
+ localSelectedModel
)
const collectedQuestions: Array<{ question: string }> = []
diff --git a/lib/streaming/types.ts b/lib/streaming/types.ts
index 4d479f76..e3361008 100644
--- a/lib/streaming/types.ts
+++ b/lib/streaming/types.ts
@@ -1,6 +1,5 @@
import { UIMessage } from '@ai-sdk/react'
-import { ModelType } from '../types/model-type'
import { Model } from '../types/models'
import { SearchMode } from '../types/search'
@@ -14,5 +13,4 @@ export interface BaseStreamConfig {
abortSignal?: AbortSignal
isNewChat?: boolean
searchMode?: SearchMode
- modelType?: ModelType
}
diff --git a/lib/types/model-selector.ts b/lib/types/model-selector.ts
new file mode 100644
index 00000000..7e7da802
--- /dev/null
+++ b/lib/types/model-selector.ts
@@ -0,0 +1,8 @@
+import { Model } from '@/lib/types/models'
+
+export interface ModelSelectorData {
+ enabled: boolean
+ modelsByProvider: Record<string, Model[]>
+ defaultModel: Model
+ selectedModelKey: string
+}
diff --git a/lib/types/model-type.ts b/lib/types/model-type.ts
deleted file mode 100644
index 4cc6649a..00000000
--- a/lib/types/model-type.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-// Model type definition for speed/quality selection
-export type ModelType = 'speed' | 'quality'
diff --git a/lib/utils/__tests__/model-selection.test.ts b/lib/utils/__tests__/model-selection.test.ts
index b476e685..0cfc5d80 100644
--- a/lib/utils/__tests__/model-selection.test.ts
+++ b/lib/utils/__tests__/model-selection.test.ts
@@ -1,139 +1,196 @@
-import type { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'
-
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import type { ModelType } from '@/lib/types/model-type'
+import { isCloudDeployment } from '@/lib/config/load-models-config'
+import { MODEL_SELECTION_COOKIE } from '@/lib/config/model-selection-cookie'
import type { Model } from '@/lib/types/models'
import type { SearchMode } from '@/lib/types/search'
+vi.mock('@/lib/config/load-models-config')
vi.mock('@/lib/config/model-types')
vi.mock('@/lib/utils/registry')
-import { getModelForModeAndType } from '@/lib/config/model-types'
+import { getModelForMode } from '@/lib/config/model-types'
import { DEFAULT_MODEL, selectModel } from '@/lib/utils/model-selection'
import { isProviderEnabled } from '@/lib/utils/registry'
-const mockGetModelForModeAndType = vi.mocked(getModelForModeAndType)
+const mockIsCloudDeployment = vi.mocked(isCloudDeployment)
+const mockGetModelForMode = vi.mocked(getModelForMode)
const mockIsProviderEnabled = vi.mocked(isProviderEnabled)
-type Matrix = Record<SearchMode, Partial<Record<ModelType, Model>>>
+type Matrix = Partial<Record<SearchMode, Model>>
-const quickSpeedModel: Model = {
- id: 'quick-speed',
- name: 'Quick Speed',
+const quickModel: Model = {
+ id: 'quick',
+ name: 'Quick',
provider: 'Provider A',
providerId: 'provider-a'
}
-const quickQualityModel: Model = {
- id: 'quick-quality',
- name: 'Quick Quality',
+const adaptiveModel: Model = {
+ id: 'adaptive',
+ name: 'Adaptive',
provider: 'Provider B',
providerId: 'provider-b'
}
-const adaptiveQualityModel: Model = {
- id: 'adaptive-quality',
- name: 'Adaptive Quality',
- provider: 'Provider C',
- providerId: 'provider-c'
-}
-
-const adaptiveSpeedModel: Model = {
- id: 'adaptive-speed',
- name: 'Adaptive Speed',
- provider: 'Provider D',
- providerId: 'provider-d'
-}
-
let matrix: Matrix
function setMatrixImplementation() {
- mockGetModelForModeAndType.mockImplementation(
- (mode: SearchMode, type: ModelType) => matrix[mode]?.[type]
- )
+ mockGetModelForMode.mockImplementation((mode: SearchMode) => matrix[mode])
}
-function createCookieStore(modelType?: string): ReadonlyRequestCookies {
+function createCookieStore(value?: string) {
return {
get: (name: string) => {
- if (name === 'modelType' && modelType) {
- return { name, value: modelType } as any
+ if (name === MODEL_SELECTION_COOKIE && value) {
+ return { name, value } as { name: string; value: string }
}
+
return undefined
}
- } as unknown as ReadonlyRequestCookies
+ } as any
}
describe('selectModel', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockIsCloudDeployment.mockReturnValue(true)
matrix = {
- quick: {
- speed: quickSpeedModel,
- quality: quickQualityModel
- },
- adaptive: {
- speed: adaptiveSpeedModel,
- quality: adaptiveQualityModel
- }
+ quick: quickModel,
+ adaptive: adaptiveModel
}
setMatrixImplementation()
mockIsProviderEnabled.mockReturnValue(true)
})
- it('returns the cookie-preferred type for the active mode when available', () => {
- const result = selectModel({
- cookieStore: createCookieStore('quality'),
- searchMode: 'quick'
+ it('returns the cloud model for the active mode when available', async () => {
+ const result = await selectModel({
+ searchMode: 'quick',
+ cookieStore: createCookieStore()
})
-
- expect(result).toEqual(quickQualityModel)
+ expect(result).toEqual(quickModel)
})
- it('falls back to speed model for the mode when cookie is absent', () => {
- const result = selectModel({
- cookieStore: createCookieStore(),
- searchMode: 'adaptive'
+ it('falls back to the next mode when active mode provider is disabled', async () => {
+ mockIsProviderEnabled.mockImplementation(providerId =>
+ providerId === 'provider-a' ? false : true
+ )
+
+ const result = await selectModel({
+ searchMode: 'quick',
+ cookieStore: createCookieStore()
})
- expect(result).toEqual(adaptiveSpeedModel)
+ expect(result).toEqual(adaptiveModel)
})
- it('falls back to the other type within the same mode when preferred provider is disabled', () => {
+ it('falls back to quick mode when search mode is omitted', async () => {
+ const result = await selectModel({ cookieStore: createCookieStore() })
+ expect(result).toEqual(quickModel)
+ })
+
+ it('falls back to DEFAULT_MODEL when cloud models are unavailable', async () => {
+ matrix = {}
+ setMatrixImplementation()
+ const result = await selectModel({
+ searchMode: 'quick',
+ cookieStore: createCookieStore()
+ })
+ expect(result).toEqual(DEFAULT_MODEL)
+ })
+
+ it('falls back to DEFAULT_MODEL when configured providers are disabled', async () => {
mockIsProviderEnabled.mockImplementation(providerId =>
- providerId === 'provider-a' ? false : true
+ providerId === 'provider-a' || providerId === 'provider-b' ? false : true
)
- const result = selectModel({
- cookieStore: createCookieStore('speed'),
- searchMode: 'quick'
+ const result = await selectModel({
+ searchMode: 'quick',
+ cookieStore: createCookieStore()
})
- expect(result).toEqual(quickQualityModel)
+ expect(result).toEqual(DEFAULT_MODEL)
})
- it('falls back to the next mode in priority order when active mode has no enabled models', () => {
+ it('returns cookie-selected model in local/docker mode', async () => {
+ mockIsCloudDeployment.mockReturnValue(false)
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'provider-l'
+ )
+
+ const result = await selectModel({
+ cookieStore: createCookieStore('provider-l:local-model')
+ })
+ expect(result).toEqual({
+ id: 'local-model',
+ name: 'local-model',
+ provider: 'provider-l',
+ providerId: 'provider-l'
+ })
+ })
+
+ it('falls back to DEFAULT_MODEL in local/docker mode when cookie is missing', async () => {
+ mockIsCloudDeployment.mockReturnValue(false)
+
+ const result = await selectModel({ cookieStore: createCookieStore() })
+ expect(result).toEqual(DEFAULT_MODEL)
+ })
+
+ it('falls back to DEFAULT_MODEL when local cookie provider is disabled', async () => {
+ mockIsCloudDeployment.mockReturnValue(false)
mockIsProviderEnabled.mockImplementation(providerId =>
- providerId === 'provider-a' || providerId === 'provider-b' ? false : true
+ providerId === 'provider-l' ? false : true
+ )
+
+ const result = await selectModel({
+ cookieStore: createCookieStore('provider-l:local-model')
+ })
+ expect(result).toEqual(DEFAULT_MODEL)
+ })
+
+ it('sets ollama think provider options for thinking models from cookie', async () => {
+ mockIsCloudDeployment.mockReturnValue(false)
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'ollama'
)
- const result = selectModel({
- cookieStore: createCookieStore('quality'),
- searchMode: 'quick'
+ const result = await selectModel({
+ cookieStore: createCookieStore('ollama:deepseek-r1:8b')
})
- expect(result).toEqual(adaptiveQualityModel)
+ expect(result).toEqual({
+ id: 'deepseek-r1:8b',
+ name: 'deepseek-r1:8b',
+ provider: 'Ollama',
+ providerId: 'ollama',
+ providerOptions: {
+ ollama: {
+ think: true
+ }
+ }
+ })
})
- it('returns DEFAULT_MODEL when no configured providers are enabled', () => {
- mockIsProviderEnabled.mockReturnValue(false)
+ it('sets ollama think provider options for non-thinking models from cookie', async () => {
+ mockIsCloudDeployment.mockReturnValue(false)
+ mockIsProviderEnabled.mockImplementation(
+ providerId => providerId === 'ollama'
+ )
- const result = selectModel({
- cookieStore: createCookieStore(),
- searchMode: 'quick'
+ const result = await selectModel({
+ cookieStore: createCookieStore('ollama:llama3.2:3b')
})
- expect(result).toEqual(DEFAULT_MODEL)
+ expect(result).toEqual({
+ id: 'llama3.2:3b',
+ name: 'llama3.2:3b',
+ provider: 'Ollama',
+ providerId: 'ollama',
+ providerOptions: {
+ ollama: {
+ think: true
+ }
+ }
+ })
})
})
diff --git a/lib/utils/model-selection.ts b/lib/utils/model-selection.ts
index dbe9795e..ef472b13 100644
--- a/lib/utils/model-selection.ts
+++ b/lib/utils/model-selection.ts
@@ -1,45 +1,68 @@
import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'
-import { getModelForModeAndType } from '@/lib/config/model-types'
-import { ModelType } from '@/lib/types/model-type'
+import { DEFAULT_MODEL } from '@/lib/config/default-model'
+import { isCloudDeployment } from '@/lib/config/load-models-config'
+import {
+ MODEL_SELECTION_COOKIE,
+ parseModelSelectionCookie
+} from '@/lib/config/model-selection-cookie'
+import { getModelForMode } from '@/lib/config/model-types'
import { Model } from '@/lib/types/models'
import { SearchMode } from '@/lib/types/search'
import { isProviderEnabled } from '@/lib/utils/registry'
-const DEFAULT_MODEL: Model = {
- id: 'gpt-5-mini',
- name: 'GPT-5 mini',
- provider: 'OpenAI',
- providerId: 'openai',
- providerOptions: {
- openai: {
- reasoningEffort: 'low',
- reasoningSummary: 'auto'
+const MODE_FALLBACK_ORDER: SearchMode[] = ['quick', 'adaptive']
+const PROVIDER_LABELS: Record<string, string> = {
+ openai: 'OpenAI',
+ anthropic: 'Anthropic',
+ google: 'Google',
+ ollama: 'Ollama',
+ gateway: 'Gateway',
+ 'openai-compatible': 'OpenAI Compatible'
+}
+
+function buildProviderOptions(
+ providerId: string,
+ _modelId: string
+): Model['providerOptions'] | undefined {
+ if (providerId === 'ollama') {
+ return {
+ ollama: {
+ think: true
+ }
}
}
-}
-const VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']
-const MODE_FALLBACK_ORDER: SearchMode[] = ['quick', 'adaptive']
+ return undefined
+}
interface ModelSelectionParams {
- cookieStore: ReadonlyRequestCookies
searchMode?: SearchMode
+ cookieStore?: ReadonlyRequestCookies
+}
+
+function buildLocalCookieModel(providerId: string, modelId: string): Model {
+ const providerOptions = buildProviderOptions(providerId, modelId)
+
+ return {
+ id: modelId,
+ name: modelId,
+ provider: PROVIDER_LABELS[providerId] ?? providerId,
+ providerId,
+ ...(providerOptions ? { providerOptions } : {})
+ }
}
-function resolveModelForModeAndType(
- mode: SearchMode,
- type: ModelType
-): Model | undefined {
+function resolveModelForMode(mode: SearchMode): Model | undefined {
try {
- const model = getModelForModeAndType(mode, type)
+ const model = getModelForMode(mode)
if (!model) {
return undefined
}
if (!isProviderEnabled(model.providerId)) {
console.warn(
- `[ModelSelection] Provider "${model.providerId}" is not enabled for mode "${mode}" and model type "${type}"`
+ `[ModelSelection] Provider "${model.providerId}" is not enabled for mode "${mode}"`
)
return undefined
}
@@ -47,7 +70,7 @@ function resolveModelForModeAndType(
return model
} catch (error) {
console.error(
- `[ModelSelection] Failed to load model configuration for mode "${mode}" and type "${type}":`,
+ `[ModelSelection] Failed to load model configuration for mode "${mode}":`,
error
)
return undefined
@@ -55,52 +78,58 @@ function resolveModelForModeAndType(
}
/**
- * Determines which model to use based on the model type preference.
+ * Determines which model to use based on search mode preference.
*
* Priority order:
- * 1. If model type is in cookie -> use corresponding model from config (when enabled)
- * 2. Otherwise -> use default ordering (speed β†’ quality) for the active mode
- * 3. If the active mode has no enabled models, try remaining modes
- * 4. If config loading fails or providers are unavailable -> use DEFAULT_MODEL as fallback
+ * 1. Use cloud mode-specific model for the active mode when enabled
+ * 2. If the active mode has no enabled model, try remaining modes
+ * 3. If cloud config is unavailable or providers are disabled, use DEFAULT_MODEL
*/
-export function selectModel({
- cookieStore,
- searchMode
-}: ModelSelectionParams): Model {
- const modelTypeCookie = cookieStore.get('modelType')?.value as
- | ModelType
- | undefined
+export async function selectModel({
+ searchMode,
+ cookieStore
+}: ModelSelectionParams): Promise<Model> {
+ if (!isCloudDeployment()) {
+ const parsedCookie = parseModelSelectionCookie(
+ cookieStore?.get(MODEL_SELECTION_COOKIE)?.value
+ )
+
+ if (parsedCookie) {
+ try {
+ if (!isProviderEnabled(parsedCookie.providerId)) {
+ console.warn(
+ `[ModelSelection] Saved model provider "${parsedCookie.providerId}" is not enabled. Falling back to DEFAULT_MODEL.`
+ )
+ return DEFAULT_MODEL
+ }
+ return buildLocalCookieModel(
+ parsedCookie.providerId,
+ parsedCookie.modelId
+ )
+ } catch (error) {
+ console.error(
+ '[ModelSelection] Failed to resolve model from cookie:',
+ error
+ )
+ }
+ }
+
+ return DEFAULT_MODEL
+ }
const requestedMode =
searchMode && MODE_FALLBACK_ORDER.includes(searchMode)
? searchMode
: 'quick'
- const typePreferenceOrder: ModelType[] = []
- if (
- modelTypeCookie &&
- VALID_MODEL_TYPES.includes(modelTypeCookie) &&
- !typePreferenceOrder.includes(modelTypeCookie)
- ) {
- typePreferenceOrder.push(modelTypeCookie)
- }
-
- for (const knownType of VALID_MODEL_TYPES) {
- if (!typePreferenceOrder.includes(knownType)) {
- typePreferenceOrder.push(knownType)
- }
- }
-
const modePreferenceOrder: SearchMode[] = Array.from(
new Set<SearchMode>([requestedMode, ...MODE_FALLBACK_ORDER])
)
for (const candidateMode of modePreferenceOrder) {
- for (const candidateType of typePreferenceOrder) {
- const model = resolveModelForModeAndType(candidateMode, candidateType)
- if (model) {
- return model
- }
+ const model = resolveModelForMode(candidateMode)
+ if (model) {
+ return model
}
}
diff --git a/package.json b/package.json
index e3c30398..fcb07393 100644
--- a/package.json
+++ b/package.json
@@ -68,9 +68,9 @@
"langfuse-vercel": "^3.38.4",
"lucide-react": "^0.507.0",
"next": "^16.2.1",
- "next-themes": "^0.3.0",
+ "next-themes": "0.4.6",
"node-html-parser": "^6.1.13",
- "ollama-ai-provider-v2": "^1.5.0",
+ "ollama-ai-provider-v2": "3.5.0",
"postgres": "^3.4.5",
"react": "^19.2.0",
"react-dom": "^19.2.0",
diff --git a/public/providers/logos/anthropic.svg b/public/providers/logos/anthropic.svg
new file mode 100644
index 00000000..e6af4ecf
--- /dev/null
+++ b/public/providers/logos/anthropic.svg
@@ -0,0 +1,4 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M54.8717 28L72.392 71.945H82L64.4796 28H54.8717Z" fill="#181818"/>
+<path d="M34.5457 54.5553L40.5406 39.1118L46.5355 54.5553H34.5457ZM35.5176 28L18 71.945H27.7948L31.3774 62.7165H49.7044L53.2864 71.945H63.0812L45.5636 28H35.5176Z" fill="#181818"/>
+</svg>
diff --git a/public/providers/logos/gateway.svg b/public/providers/logos/gateway.svg
new file mode 100644
index 00000000..6e3bd964
--- /dev/null
+++ b/public/providers/logos/gateway.svg
@@ -0,0 +1,3 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M49.9999 18L85 79H15L49.9999 18Z" fill="black"/>
+</svg>
diff --git a/public/providers/logos/google.svg b/public/providers/logos/google.svg
new file mode 100644
index 00000000..995778fc
--- /dev/null
+++ b/public/providers/logos/google.svg
@@ -0,0 +1,33 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_278_14)">
+<mask id="mask0_278_14" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="19" y="18" width="63" height="64">
+<path d="M80.8182 44.1818H51V56.5455H68.1637C66.5637 64.4 59.8727 68.9091 51 68.9091C40.5273 68.9091 32.0909 60.4727 32.0909 50C32.0909 39.5273 40.5273 31.0909 51 31.0909C55.5091 31.0909 59.5818 32.6909 62.7818 35.3091L72.0909 26C66.4182 21.0545 59.1455 18 51 18C33.2546 18 19 32.2546 19 50C19 67.7455 33.2546 82 51 82C67 82 81.5455 70.3637 81.5455 50C81.5455 48.1091 81.2546 46.0727 80.8182 44.1818Z" fill="white"/>
+</mask>
+<g mask="url(#mask0_278_14)">
+<path d="M16.0909 68.909V31.0908L40.8182 49.9999L16.0909 68.909Z" fill="#FBBC05"/>
+</g>
+<mask id="mask1_278_14" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="19" y="18" width="63" height="64">
+<path d="M80.8182 44.1818H51V56.5455H68.1637C66.5637 64.4 59.8727 68.9091 51 68.9091C40.5273 68.9091 32.0909 60.4727 32.0909 50C32.0909 39.5273 40.5273 31.0909 51 31.0909C55.5091 31.0909 59.5818 32.6909 62.7818 35.3091L72.0909 26C66.4182 21.0545 59.1455 18 51 18C33.2546 18 19 32.2546 19 50C19 67.7455 33.2546 82 51 82C67 82 81.5455 70.3637 81.5455 50C81.5455 48.1091 81.2546 46.0727 80.8182 44.1818Z" fill="white"/>
+</mask>
+<g mask="url(#mask1_278_14)">
+<path d="M16.0909 31.0908L40.8182 49.9999L51 41.1272L85.9091 35.4545V15.0908H16.0909V31.0908Z" fill="#EA4335"/>
+</g>
+<mask id="mask2_278_14" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="19" y="18" width="63" height="64">
+<path d="M80.8182 44.1818H51V56.5455H68.1637C66.5637 64.4 59.8727 68.9091 51 68.9091C40.5273 68.9091 32.0909 60.4727 32.0909 50C32.0909 39.5273 40.5273 31.0909 51 31.0909C55.5091 31.0909 59.5818 32.6909 62.7818 35.3091L72.0909 26C66.4182 21.0545 59.1455 18 51 18C33.2546 18 19 32.2546 19 50C19 67.7455 33.2546 82 51 82C67 82 81.5455 70.3637 81.5455 50C81.5455 48.1091 81.2546 46.0727 80.8182 44.1818Z" fill="white"/>
+</mask>
+<g mask="url(#mask2_278_14)">
+<path d="M16.0909 68.909L59.7273 35.4545L71.2182 36.909L85.9091 15.0908V84.909H16.0909V68.909Z" fill="#34A853"/>
+</g>
+<mask id="mask3_278_14" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="19" y="18" width="63" height="64">
+<path d="M80.8182 44.1818H51V56.5455H68.1637C66.5637 64.4 59.8727 68.9091 51 68.9091C40.5273 68.9091 32.0909 60.4727 32.0909 50C32.0909 39.5273 40.5273 31.0909 51 31.0909C55.5091 31.0909 59.5818 32.6909 62.7818 35.3091L72.0909 26C66.4182 21.0545 59.1455 18 51 18C33.2546 18 19 32.2546 19 50C19 67.7455 33.2546 82 51 82C67 82 81.5455 70.3637 81.5455 50C81.5455 48.1091 81.2546 46.0727 80.8182 44.1818Z" fill="white"/>
+</mask>
+<g mask="url(#mask3_278_14)">
+<path d="M85.9091 84.909L40.8182 49.9999L35 45.6363L85.9091 31.0908V84.909Z" fill="#4285F4"/>
+</g>
+</g>
+<defs>
+<clipPath id="clip0_278_14">
+<rect width="64" height="64" fill="white" transform="translate(18 18)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/public/providers/logos/ollama.svg b/public/providers/logos/ollama.svg
new file mode 100644
index 00000000..18f86024
--- /dev/null
+++ b/public/providers/logos/ollama.svg
@@ -0,0 +1,14 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_278_45)">
+<path d="M36.5389 18.018C35.9417 18.1145 35.2251 18.4268 34.7197 18.8127C33.19 19.975 32.0047 22.442 31.504 25.5154C31.3156 26.6776 31.187 28.2901 31.187 29.5214C31.187 30.973 31.357 32.829 31.6004 34.1107C31.6556 34.3955 31.6831 34.6482 31.6602 34.6666C31.6418 34.685 31.4167 34.8687 31.164 35.0708C30.3003 35.7599 29.3126 36.8212 28.6327 37.7905C27.328 39.6419 26.4827 41.746 26.129 44.0245C25.9912 44.925 25.9544 46.7442 26.0647 47.6446C26.3082 49.7211 26.9329 51.476 28.0033 53.0839L28.3525 53.603L28.2514 53.773C27.5348 54.9766 26.9238 56.7178 26.6389 58.3899C26.4138 59.713 26.3863 60.0667 26.3863 61.84C26.3863 63.6271 26.4092 63.9809 26.6206 65.2166C26.8732 66.6959 27.3878 68.2624 27.962 69.3053C28.1504 69.6452 28.6098 70.3527 28.6649 70.3895C28.6833 70.3986 28.6281 70.5686 28.5408 70.7661C27.8793 72.2133 27.3142 74.1381 27.08 75.7599C26.9146 76.8715 26.8916 77.2299 26.8916 78.4014C26.8916 79.8944 26.9743 80.6203 27.2867 81.8101L27.3326 81.9846H29.2988H31.2697L31.141 81.7412C30.3463 80.2711 30.2728 77.5423 30.9573 74.8181C31.2697 73.5593 31.6234 72.6359 32.2849 71.3633L32.68 70.5916V70.1184C32.68 69.6774 32.6708 69.6269 32.5284 69.3374C32.4182 69.1169 32.2712 68.9286 32.0093 68.6713C31.5637 68.2395 31.2421 67.7847 30.9848 67.2242C29.8547 64.771 29.6342 61.128 30.429 58.0224C30.7597 56.7269 31.3064 55.5738 31.8807 54.9445C32.2712 54.5126 32.4733 54.0303 32.4733 53.5295C32.4733 53.0104 32.2895 52.5832 31.8761 52.1376C30.6908 50.8696 29.9604 49.326 29.6985 47.5298C29.3264 44.9709 30.0017 42.1823 31.5361 39.9727C33.0384 37.8043 35.147 36.4123 37.5037 36.0402C38.032 35.9529 39.0197 35.9667 39.571 36.0678C40.1729 36.1735 40.5495 36.1412 40.9355 35.9575C41.4132 35.7324 41.6521 35.4521 41.9323 34.809C42.1804 34.2348 42.3734 33.9224 42.8925 33.2746C43.5173 32.4983 44.119 31.9699 45.0838 31.3313C46.1864 30.6101 47.4405 30.0864 48.6901 29.8337C49.1448 29.7418 49.3562 29.728 50.2061 29.728C51.056 29.728 51.2673 29.7418 51.7221 29.8337C53.5551 30.2059 55.3743 31.1522 56.826 32.4936C57.1384 32.783 57.8872 33.711 58.1261 34.097C58.218 34.2485 58.3788 34.5702 58.4798 34.809C58.7601 35.4521 58.999 35.7324 59.4767 35.9575C59.8489 36.1367 60.2393 36.1735 60.8182 36.0769C61.7324 35.9208 62.4353 35.9345 63.3311 36.1183C66.3815 36.7339 69.0369 39.2468 70.2129 42.6142C71.2374 45.5681 70.9479 48.6599 69.4227 51.0212C69.1654 51.4209 68.9082 51.7425 68.5361 52.1376C67.7321 52.9966 67.7321 54.0624 68.5315 54.9445C69.8454 56.3824 70.6677 59.9198 70.4196 63.0391C70.2543 65.0972 69.7259 66.9394 69.0001 67.9822C68.8715 68.166 68.605 68.4783 68.4028 68.6713C68.141 68.9286 67.994 69.1169 67.8837 69.3374C67.7413 69.6269 67.7321 69.6774 67.7321 70.1184V70.5916L68.1272 71.3633C68.7888 72.6359 69.1425 73.5593 69.4549 74.8181C70.1302 77.5055 70.0705 80.1792 69.2987 81.6999C69.2344 81.8285 69.1792 81.9479 69.1792 81.9617C69.1792 81.9755 70.0567 81.9846 71.1317 81.9846H73.0796L73.1301 81.7871C73.1577 81.6815 73.2036 81.5207 73.2265 81.4288C73.2771 81.2267 73.3781 80.6295 73.4609 80.0552C73.539 79.4764 73.539 77.3447 73.4609 76.7016C73.1669 74.3678 72.6753 72.5165 71.8714 70.7661C71.7841 70.5686 71.7289 70.3986 71.7473 70.3895C71.7703 70.3757 71.8989 70.1919 72.0367 69.9852C73.0382 68.4692 73.6538 66.5627 73.9662 64.0452C74.0489 63.3514 74.0489 60.3699 73.9662 59.7038C73.7456 57.9857 73.4792 56.8188 73.0382 55.6381C72.8544 55.1466 72.3675 54.1084 72.1608 53.773L72.0597 53.603L72.4088 53.0839C73.4792 51.476 74.104 49.7211 74.3475 47.6446C74.4577 46.7442 74.421 44.925 74.2832 44.0245C73.9248 41.7413 73.0841 39.6465 71.7795 37.7905C71.0995 36.8212 70.1118 35.7599 69.2482 35.0708C68.9955 34.8687 68.7704 34.685 68.752 34.6666C68.7291 34.6482 68.7566 34.3955 68.8117 34.1107C69.3676 31.2119 69.3492 27.5965 68.7658 24.7711C68.2605 22.3088 67.3417 20.3517 66.1564 19.2216C65.21 18.3212 64.2453 17.9353 63.0876 18.0088C60.4323 18.165 58.2915 21.22 57.4462 26.0345C57.3084 26.8109 57.189 27.7205 57.189 27.9686C57.189 28.065 57.1705 28.1431 57.1476 28.1431C57.1246 28.1431 56.9455 28.0512 56.7525 27.9364C54.7036 26.7236 52.425 26.0758 50.2061 26.0758C47.9872 26.0758 45.7086 26.7236 43.6597 27.9364C43.4667 28.0512 43.2876 28.1431 43.2646 28.1431C43.2416 28.1431 43.2232 28.065 43.2232 27.9686C43.2232 27.7113 43.0992 26.7741 42.966 26.0345C42.1987 21.7115 40.4393 18.8495 38.1009 18.1282C37.7794 18.0318 36.8652 17.9674 36.5389 18.018ZM37.32 21.7575C37.9815 22.2812 38.7165 23.7788 39.1392 25.4556C39.2173 25.7588 39.2999 26.108 39.3229 26.2366C39.3413 26.3607 39.3918 26.6409 39.4332 26.8568C39.6124 27.8307 39.695 28.8828 39.7042 30.1645L39.7088 31.4279L39.3918 31.8964L39.0749 32.3696H38.3352C37.4716 32.3696 36.6125 32.4799 35.7901 32.7004C35.4961 32.7739 35.2113 32.8474 35.1562 32.8612C35.0689 32.8796 35.0551 32.852 35.0046 32.4752C34.7335 30.4309 34.7473 28.1661 35.046 26.2825C35.3767 24.1831 36.1485 22.2812 36.9019 21.7207C37.0811 21.5875 37.1132 21.5921 37.32 21.7575ZM63.5149 21.7253C63.9697 22.0607 64.4704 22.9519 64.8425 24.0912C65.5913 26.3698 65.8027 29.4983 65.4076 32.4752C65.3571 32.852 65.3433 32.8796 65.256 32.8612C65.2009 32.8474 64.916 32.7739 64.622 32.7004C63.7997 32.4799 62.9406 32.3696 62.077 32.3696H61.3373L61.0204 31.8964L60.7034 31.4279L60.7079 30.1645C60.7172 28.382 60.8825 26.9901 61.2776 25.4419C61.6957 23.7788 62.4353 22.2812 63.0922 21.7575C63.299 21.5921 63.3311 21.5875 63.5149 21.7253Z" fill="black"/>
+<path d="M49.494 44.8467C48.4971 44.9433 48.2261 44.98 47.7483 45.0765C46.9719 45.2373 45.9336 45.5956 45.2124 45.9494C42.7041 47.1759 40.9768 49.2202 40.4484 51.5861C40.3428 52.0548 40.329 52.2109 40.329 53.0011C40.329 53.7821 40.3428 53.952 40.4439 54.3977C41.1467 57.4894 43.995 59.7727 47.6794 60.1907C48.4787 60.278 51.9334 60.278 52.7328 60.1907C55.6913 59.8553 58.2364 58.252 59.3803 56.0009C59.6834 55.3992 59.8305 55.0086 59.9683 54.3977C60.0694 53.952 60.0832 53.7821 60.0832 53.0011C60.0832 52.2109 60.0694 52.0548 59.9637 51.5861C59.1965 48.1499 55.8613 45.444 51.7726 44.9295C51.2397 44.8652 49.8432 44.81 49.494 44.8467ZM51.2121 47.3459C52.5766 47.4929 53.9502 47.9799 55.0527 48.7149C55.6454 49.11 56.4815 49.9369 56.8398 50.479C57.2808 51.1497 57.5334 51.8342 57.6483 52.6658C57.6988 53.0471 57.6713 53.3365 57.5334 53.952C57.3175 54.8708 56.6468 55.831 55.7418 56.5017C55.3191 56.8095 54.4417 57.2552 53.9042 57.4297C52.8844 57.7559 52.2182 57.8156 49.8385 57.7972C48.2858 57.7834 48.0101 57.7696 47.5645 57.687C46.0439 57.4021 44.8403 56.7957 43.9675 55.8723C43.2599 55.1281 42.9384 54.4482 42.7638 53.3503C42.6857 52.8403 42.8327 51.995 43.1313 51.2829C43.4943 50.4147 44.4314 49.3351 45.3594 48.7149C46.4344 47.9983 47.8494 47.4883 49.1494 47.3505C49.6502 47.2954 50.7114 47.2954 51.2121 47.3459Z" fill="black"/>
+<path d="M48.4512 50.6995C48.1021 50.8879 47.8586 51.3656 47.9321 51.7193C48.0147 52.1007 48.3501 52.4866 48.8738 52.8036C49.1541 52.9736 49.1724 52.9965 49.1862 53.1665C49.1954 53.2676 49.1586 53.557 49.1081 53.8143C49.053 54.0669 49.0116 54.3334 49.0116 54.4069C49.0163 54.6044 49.2 54.926 49.3929 55.0822C49.563 55.22 49.5951 55.2246 50.0729 55.2384C50.5093 55.2522 50.6012 55.2429 50.7757 55.1603C51.226 54.9397 51.3408 54.5355 51.1754 53.7591C51.0376 53.1114 51.0652 53.0103 51.4097 52.8127C51.7726 52.6014 52.1586 52.2293 52.2734 51.9766C52.4939 51.4943 52.2917 50.9476 51.8048 50.6949C51.6854 50.6352 51.5383 50.6077 51.3224 50.6077C50.9871 50.6077 50.7712 50.6858 50.3761 50.9384L50.1509 51.0808L50.0086 50.9935C49.4251 50.649 49.3195 50.6077 48.9657 50.6122C48.713 50.6122 48.5752 50.6352 48.4512 50.6995Z" fill="black"/>
+<path d="M37.297 45.366C36.4839 45.6232 35.8775 46.2204 35.5651 47.0703C35.4135 47.4747 35.34 48.1132 35.4043 48.4577C35.5559 49.2801 36.2312 50.0289 36.9985 50.2356C37.9632 50.4883 38.6844 50.3229 39.323 49.689C39.6951 49.326 39.8973 49.009 40.0994 48.4945C40.2463 48.1316 40.2556 48.0673 40.2556 47.5527L40.2601 47.0015L40.0672 46.6064C39.7594 45.9816 39.2035 45.5176 38.5604 45.3476C38.1974 45.2557 37.614 45.2604 37.297 45.366Z" fill="black"/>
+<path d="M61.8335 45.3524C61.2041 45.5223 60.6436 45.9909 60.345 46.6065L60.1521 47.0016L60.1567 47.5529C60.1567 48.0674 60.1659 48.1317 60.3128 48.4946C60.515 49.0091 60.7172 49.3261 61.0892 49.6891C61.7278 50.323 62.4491 50.4884 63.4139 50.2358C63.9697 50.0887 64.5255 49.6201 64.792 49.0734C65.0217 48.6095 65.0768 48.2741 65.0034 47.7458C64.8334 46.5376 64.1259 45.6601 63.0738 45.3524C62.7661 45.2605 62.1688 45.2605 61.8335 45.3524Z" fill="black"/>
+</g>
+<defs>
+<clipPath id="clip0_278_45">
+<rect width="48.4122" height="64" fill="white" transform="translate(26 18)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/public/providers/logos/openai-compatible.svg b/public/providers/logos/openai-compatible.svg
new file mode 100644
index 00000000..141df123
--- /dev/null
+++ b/public/providers/logos/openai-compatible.svg
@@ -0,0 +1,3 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<circle cx="50" cy="50" r="32" fill="black"/>
+</svg>
diff --git a/public/providers/logos/openai.svg b/public/providers/logos/openai.svg
new file mode 100644
index 00000000..531019d7
--- /dev/null
+++ b/public/providers/logos/openai.svg
@@ -0,0 +1,10 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_278_47)">
+<path d="M77.4119 44.1941C78.8639 39.8361 78.3639 35.0621 76.0419 31.0981C72.5499 25.0181 65.5299 21.8901 58.6739 23.3621C55.6239 19.9261 51.2419 17.9721 46.6479 18.0001C39.6399 17.9841 33.4219 22.4961 31.2659 29.1641C26.7639 30.0861 22.8779 32.9041 20.6039 36.8981C17.0859 42.9621 17.8879 50.6061 22.5879 55.8061C21.1359 60.1641 21.6359 64.9381 23.9579 68.9021C27.4499 74.9821 34.4699 78.1101 41.3259 76.6381C44.3739 80.0741 48.7579 82.0281 53.3519 81.9981C60.3639 82.0161 66.5839 77.5001 68.7399 70.8261C73.2419 69.9041 77.1279 67.0861 79.4019 63.0921C82.9159 57.0281 82.1119 49.3901 77.4139 44.1901L77.4119 44.1941ZM53.3559 77.8161C50.5499 77.8201 47.8319 76.8381 45.6779 75.0401C45.7759 74.9881 45.9459 74.8941 46.0559 74.8261L58.7999 67.4661C59.4519 67.0961 59.8519 66.4021 59.8479 65.6521V47.6861L65.2339 50.7961C65.2919 50.8241 65.3299 50.8801 65.3379 50.9441V65.8221C65.3299 72.4381 59.9719 77.8021 53.3559 77.8161ZM27.5879 66.8101C26.1819 64.3821 25.6759 61.5361 26.1579 58.7741C26.2519 58.8301 26.4179 58.9321 26.5359 59.0001L39.2799 66.3601C39.9259 66.7381 40.7259 66.7381 41.3739 66.3601L56.9319 57.3761V63.5961C56.9359 63.6601 56.9059 63.7221 56.8559 63.7621L43.9739 71.2001C38.2359 74.5041 30.9079 72.5401 27.5899 66.8101H27.5879ZM24.2339 38.9921C25.6339 36.5601 27.8439 34.7001 30.4759 33.7341C30.4759 33.8441 30.4699 34.0381 30.4699 34.1741V48.8961C30.4659 49.6441 30.8659 50.3381 31.5159 50.7081L47.0739 59.6901L41.6879 62.8001C41.6339 62.8361 41.5659 62.8421 41.5059 62.8161L28.6219 55.3721C22.8959 52.0561 20.9319 44.7301 24.2319 38.9941L24.2339 38.9921ZM68.4859 49.2901L52.9279 40.3061L58.3139 37.1981C58.3679 37.1621 58.4359 37.1561 58.4959 37.1821L71.3799 44.6201C77.1159 47.9341 79.0819 55.2721 75.7679 61.0081C74.3659 63.4361 72.1579 65.2961 69.5279 66.2641V51.1021C69.5339 50.3541 69.1359 49.6621 68.4879 49.2901H68.4859ZM73.8459 41.2221C73.7519 41.1641 73.5859 41.0641 73.4679 40.9961L60.7239 33.6361C60.0779 33.2581 59.2779 33.2581 58.6299 33.6361L43.0719 42.6201V36.4001C43.0679 36.3361 43.0979 36.2741 43.1479 36.2341L56.0299 28.8021C61.7679 25.4921 69.1039 27.4621 72.4119 33.2021C73.8099 35.6261 74.3159 38.4641 73.8419 41.2221H73.8459ZM40.1439 52.3081L34.7559 49.1981C34.6979 49.1701 34.6599 49.1141 34.6519 49.0501V34.1721C34.6559 27.5481 40.0299 22.1801 46.6539 22.1841C49.4559 22.1841 52.1679 23.1681 54.3219 24.9601C54.2239 25.0121 54.0559 25.1061 53.9439 25.1741L41.1999 32.5341C40.5479 32.9041 40.1479 33.5961 40.1519 34.3461L40.1439 52.3041V52.3081ZM43.0699 46.0001L49.9999 41.9981L56.9299 45.9981V54.0001L49.9999 58.0001L43.0699 54.0001V46.0001Z" fill="black"/>
+</g>
+<defs>
+<clipPath id="clip0_278_47">
+<rect width="64" height="64" fill="white" transform="translate(18 18)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/scripts/README.md b/scripts/README.md
index d0812d4b..474ededd 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -10,7 +10,6 @@ A command-line interface for testing the chat API without a browser client. This
- Send messages to the chat API via command line
- Real-time Server-Sent Events (SSE) streaming output
-- Support for model types (speed/quality) with automatic model selection
- Configurable search modes (quick/adaptive) or disabled
- Chat session continuity
- Message regeneration support
@@ -36,9 +35,6 @@ bun scripts/chat-cli.ts -m "Hello, how are you?"
# Disable search mode
bun chat -m "Tell me a joke" --no-search
-# Use quality model type for better responses
-bun chat -m "Explain quantum computing" --model-type quality
-
# Use adaptive search mode for complex queries
bun chat -m "Research the latest AI developments" --search-mode adaptive
@@ -60,7 +56,6 @@ bun chat --help
- `-s, --search` - Enable search mode with adaptive strategy (default)
- `--no-search` - Disable search mode
- `--search-mode <type>` - Search strategy: `quick` or `adaptive`
-- `--model-type <type>` - Model type: `speed` (default) or `quality`
- `-t, --trigger <type>` - Trigger type: `submit` (default) or `regenerate`
- `--message-id <id>` - Message ID (required for regenerate trigger)
- `-h, --help` - Show help message
@@ -70,18 +65,12 @@ bun chat --help
The script displays:
- πŸš€ Request details
-- πŸ€– Model type (speed/quality)
- πŸ” Search mode status (quick/adaptive/disabled)
- πŸ’¬ Chat ID for reference
- Real-time AI responses with proper formatting
- πŸ”§ Tool usage (when search mode is enabled)
- βœ… Completion status
-### Model Types
-
-- **speed**: Fast responses using optimized models (default)
-- **quality**: Higher quality responses using advanced models
-
### Search Modes
- **quick**: Fast search with basic results
@@ -133,9 +122,9 @@ If you encounter "User not authenticated" errors:
If you encounter "Selected provider is not enabled" errors:
-1. Check that the model type is correctly configured in your system
-2. Verify the development server supports the requested model type
-3. Try switching between `--model-type speed` and `--model-type quality`
+1. Verify the selected model/provider is enabled in your local configuration
+2. Check the required provider API key is set in `.env.local`
+3. Retry with `--search-mode quick` to isolate search-specific issues
#### General Issues
@@ -150,9 +139,9 @@ If you encounter "Selected provider is not enabled" errors:
# Test basic functionality
bun chat -m "Hello, test message" --no-search
-# Test with quality model and adaptive search
-bun chat -m "Complex analysis task" --model-type quality --search-mode adaptive
+# Test adaptive search
+bun chat -m "Complex analysis task" --search-mode adaptive
# Debug mode
-DEBUG=1 bun chat -m "Debug test" --model-type speed
+DEBUG=1 bun chat -m "Debug test"
```
diff --git a/scripts/chat-cli.ts b/scripts/chat-cli.ts
index e466382f..ab02165d 100755
--- a/scripts/chat-cli.ts
+++ b/scripts/chat-cli.ts
@@ -14,7 +14,6 @@ interface ChatApiConfig {
apiUrl: string
message: string
chatId?: string
- modelType?: 'speed' | 'quality'
searchMode?: 'quick' | 'adaptive' | boolean
trigger?: 'submit-message' | 'regenerate-message'
messageId?: string
@@ -88,7 +87,6 @@ class ChatApiTester {
this.validateUrl(config.apiUrl) || 'http://localhost:3000/api/chat',
message: config.message || DEFAULT_MESSAGE,
chatId: config.chatId || this.generateId(),
- modelType: config.modelType || 'speed',
searchMode: config.searchMode ?? 'adaptive',
trigger: config.trigger || 'submit-message',
messageId: config.messageId
@@ -159,7 +157,6 @@ class ChatApiTester {
console.log('πŸš€ Sending request to:', this.config.apiUrl)
console.log('πŸ“¦ Payload:', JSON.stringify(payload, null, 2))
- console.log('πŸ€– Model Type:', this.config.modelType)
console.log('πŸ” Search Mode:', this.config.searchMode)
console.log('πŸ’¬ Chat ID:', this.config.chatId)
console.log('\n---\n')
@@ -169,9 +166,6 @@ class ChatApiTester {
if (cookies) {
// If cookies from env exist, append our settings to them
cookieString = cookies
- if (!cookieString.includes('modelType=')) {
- cookieString += `; modelType=${this.config.modelType}`
- }
if (!cookieString.includes('searchMode=')) {
const searchModeValue =
this.config.searchMode === false ? 'disabled' : this.config.searchMode
@@ -181,10 +175,7 @@ class ChatApiTester {
// If no cookies from env, just use our settings
const searchModeValue =
this.config.searchMode === false ? 'disabled' : this.config.searchMode
- cookieString = [
- `modelType=${this.config.modelType}`,
- `searchMode=${searchModeValue}`
- ].join('; ')
+ cookieString = [`searchMode=${searchModeValue}`].join('; ')
}
const headers = {
@@ -343,15 +334,6 @@ function parseArgs(): Partial<ChatApiConfig> {
process.exit(1)
}
break
- case '--model-type':
- const modelType = args[++i]
- if (['speed', 'quality'].includes(modelType)) {
- config.modelType = modelType as 'speed' | 'quality'
- } else {
- console.error('❌ Invalid model type. Use: speed or quality')
- process.exit(1)
- }
- break
case '-t':
case '--trigger':
const trigger = args[++i]
@@ -378,7 +360,6 @@ Options:
-s, --search Enable search mode with adaptive strategy (default)
--no-search Disable search mode
--search-mode <type> Search strategy: quick or adaptive
- --model-type <type> Model type: speed (default) or quality
-t, --trigger <type> Trigger type: submit (default) or regenerate
--message-id <id> Message ID (required for regenerate)
-h, --help Show this help message
@@ -390,9 +371,6 @@ Examples:
# Without search mode
bun scripts/chat-cli.ts -m "Tell me a joke" --no-search
- # With quality model type
- bun scripts/chat-cli.ts -m "Tell me a joke" --model-type quality
-
# Continue existing chat
bun scripts/chat-cli.ts -c "chat_123" -m "Tell me more"