An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: add search mode toggle with persistent state
Yoshiki Miura7d8948a92d4a
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex a0549f39..1d75397e 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -22,9 +22,9 @@ export async function POST(req: Request) {const cookieStore = await cookies()const modelFromCookie = cookieStore.get('selected-model')?.value+ const searchMode = cookieStore.get('search-mode')?.value === 'true'const model = modelFromCookie || DEFAULT_MODELconst provider = model.split(':')[0]-if (!isProviderEnabled(provider)) {return new Response(`Selected provider is not enabled ${provider}`, {status: 404,@@ -38,12 +38,14 @@ export async function POST(req: Request) {? createToolCallingStreamResponse({messages,model,- chatId+ chatId,+ searchMode}): createManualToolStreamResponse({messages,model,- chatId+ chatId,+ searchMode})} catch (error) {console.error('API route error:', error)diff --git a/bun.lockb b/bun.lockbindex 18653501..c09aac26 100755Binary files a/bun.lockb and b/bun.lockb differdiff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 4c470dc5..5d711f0b 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -8,6 +8,7 @@ import { useEffect, useRef, useState } from 'react'import Textarea from 'react-textarea-autosize'import { EmptyScreen } from './empty-screen'import { ModelSelector } from './model-selector'+import { SearchModeToggle } from './search-mode-toggle'import { Button } from './ui/button'import { IconLogo } from './ui/icons'@@ -130,6 +131,7 @@ export function ChatPanel({<div className="flex items-center justify-between p-3"><div className="flex items-center gap-2"><ModelSelector />+ <SearchModeToggle /></div><div className="flex items-center gap-2">{messages.length > 0 && (diff --git a/components/search-mode-toggle.tsx b/components/search-mode-toggle.tsxnew file mode 100644index 00000000..8d9e7f21--- /dev/null+++ b/components/search-mode-toggle.tsx@@ -0,0 +1,41 @@+'use client'++import { cn } from '@/lib/utils'+import { getCookie, setCookie } from '@/lib/utils/cookies'+import { Globe } from 'lucide-react'+import { useEffect, useState } from 'react'+import { Toggle } from './ui/toggle'++export function SearchModeToggle() {+ const [isSearchMode, setIsSearchMode] = useState(true)++ useEffect(() => {+ const savedMode = getCookie('search-mode')+ if (savedMode !== null) {+ setIsSearchMode(savedMode === 'true')+ }+ }, [])++ const handleSearchModeChange = (pressed: boolean) => {+ setIsSearchMode(pressed)+ setCookie('search-mode', pressed.toString())+ }++ return (+ <Toggle+ aria-label="Toggle search mode"+ pressed={isSearchMode}+ onPressedChange={handleSearchModeChange}+ variant="outline"+ className={cn(+ 'gap-1 px-3 border border-input text-muted-foreground',+ 'data-[state=on]:bg-blue-50 data-[state=on]:text-blue-500 data-[state=on]:border-blue-100',+ 'dark:data-[state=on]:bg-blue-950 dark:data-[state=on]:text-blue-400 dark:data-[state=on]:border-blue-900',+ 'hover:bg-accent hover:text-accent-foreground rounded-full'+ )}+ >+ <Globe className="size-4" />+ <span className="text-xs">Search</span>+ </Toggle>+ )+}diff --git a/components/ui/toggle.tsx b/components/ui/toggle.tsxnew file mode 100644index 00000000..dbd978cc--- /dev/null+++ b/components/ui/toggle.tsx@@ -0,0 +1,46 @@+'use client'++import * as TogglePrimitive from '@radix-ui/react-toggle'+import { cva, type VariantProps } from 'class-variance-authority'+import * as React from 'react'++import { cn } from '@/lib/utils'++const toggleVariants = cva(+ 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2',+ {+ variants: {+ variant: {+ default:+ 'bg-transparent data-[state=on]:bg-accent data-[state=on]:text-accent-foreground',+ outline:+ 'border border-input hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground'+ },+ size: {+ default: 'h-10 px-3 min-w-10',+ sm: 'h-9 px-2.5 min-w-9',+ lg: 'h-11 px-5 min-w-11'+ }+ },+ defaultVariants: {+ variant: 'default',+ size: 'default'+ }+ }+)++const Toggle = React.forwardRef<+ React.ElementRef<typeof TogglePrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &+ VariantProps<typeof toggleVariants>+>(({ className, variant, size, ...props }, ref) => (+ <TogglePrimitive.Root+ ref={ref}+ className={cn(toggleVariants({ variant, size, className }))}+ {...props}+ />+))++Toggle.displayName = TogglePrimitive.Root.displayName++export { Toggle, toggleVariants }diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex e88edd2b..f42996b4 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -27,10 +27,12 @@ type ResearcherReturn = Parameters<typeof streamText>[0]export function researcher({messages,- model+ model,+ searchMode}: {messages: CoreMessage[]model: string+ searchMode: boolean}): ResearcherReturn {try {const currentDate = new Date().toLocaleString()@@ -44,7 +46,10 @@ export function researcher({retrieve: retrieveTool,videoSearch: videoSearchTool},- maxSteps: 5,+ experimental_activeTools: searchMode+ ? ['search', 'retrieve', 'videoSearch']+ : [],+ maxSteps: searchMode ? 5 : 1,experimental_transform: smoothStream({ chunking: 'word' })}} catch (error) {diff --git a/lib/streaming/create-manual-tool-stream.ts b/lib/streaming/create-manual-tool-stream.tsindex f4649216..a3269fdc 100644--- a/lib/streaming/create-manual-tool-stream.ts+++ b/lib/streaming/create-manual-tool-stream.ts@@ -15,7 +15,7 @@ import { BaseStreamConfig } from './types'export function createManualToolStreamResponse(config: BaseStreamConfig) {return createDataStreamResponse({execute: async (dataStream: DataStreamWriter) => {- const { messages, model, chatId } = config+ const { messages, model, chatId, searchMode } = configtry {const coreMessages = convertToCoreMessages(messages)const truncatedMessages = truncateMessages(@@ -24,7 +24,12 @@ export function createManualToolStreamResponse(config: BaseStreamConfig) {)const { toolCallDataAnnotation, toolCallMessages } =- await executeToolCall(truncatedMessages, dataStream, model)+ await executeToolCall(+ truncatedMessages,+ dataStream,+ model,+ searchMode+ )const researcherConfig = manualResearcher({messages: [...truncatedMessages, ...toolCallMessages],diff --git a/lib/streaming/create-tool-calling-stream.ts b/lib/streaming/create-tool-calling-stream.tsindex 80bb8547..a7411e52 100644--- a/lib/streaming/create-tool-calling-stream.ts+++ b/lib/streaming/create-tool-calling-stream.ts@@ -12,7 +12,7 @@ import { BaseStreamConfig } from './types'export function createToolCallingStreamResponse(config: BaseStreamConfig) {return createDataStreamResponse({execute: async (dataStream: DataStreamWriter) => {- const { messages, model, chatId } = config+ const { messages, model, chatId, searchMode } = configtry {const coreMessages = convertToCoreMessages(messages)@@ -23,7 +23,8 @@ export function createToolCallingStreamResponse(config: BaseStreamConfig) {let researcherConfig = await researcher({messages: truncatedMessages,- model+ model,+ searchMode})const result = streamText({diff --git a/lib/streaming/tool-execution.ts b/lib/streaming/tool-execution.tsindex 87d3e790..8947f349 100644--- a/lib/streaming/tool-execution.ts+++ b/lib/streaming/tool-execution.ts@@ -20,8 +20,14 @@ interface ToolExecutionResult {export async function executeToolCall(coreMessages: CoreMessage[],dataStream: DataStreamWriter,- model?: string+ model: string,+ searchMode: boolean): Promise<ToolExecutionResult> {+ // If search mode is disabled, return empty tool call+ if (!searchMode) {+ return { toolCallDataAnnotation: null, toolCallMessages: [] }+ }+const toolCallModel = getToolCallModel(model)// Convert Zod schema to string representationconst searchSchemaString = Object.entries(searchSchema.shape)diff --git a/lib/streaming/types.ts b/lib/streaming/types.tsindex dfd5f29f..7825f31b 100644--- a/lib/streaming/types.ts+++ b/lib/streaming/types.ts@@ -4,4 +4,5 @@ export interface BaseStreamConfig {messages: Message[]model: stringchatId: string+ searchMode: boolean}diff --git a/package.json b/package.jsonindex d5e1f7f8..65cc2a2b 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"@radix-ui/react-slider": "^1.1.2","@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3",+ "@radix-ui/react-toggle": "^1.1.1","@radix-ui/react-tooltip": "^1.0.7","@tailwindcss/typography": "^0.5.12","@upstash/redis": "^1.34.0",