An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor: remove planning search mode and integrate into adaptive mode
Yoshiki Miurac849f02563f3
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 5d26b18e..331385bf 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -75,8 +75,7 @@ export async function POST(req: Request) {// Get search mode from cookieconst searchModeCookie = cookieStore.get('searchMode')?.valueconst searchMode: SearchMode =- searchModeCookie &&- ['quick', 'planning', 'adaptive'].includes(searchModeCookie)+ searchModeCookie && ['quick', 'adaptive'].includes(searchModeCookie)? (searchModeCookie as SearchMode): 'quick'diff --git a/components/search-mode-selector.tsx b/components/search-mode-selector.tsxindex 563ea46c..5f6e24b4 100644--- a/components/search-mode-selector.tsx+++ b/components/search-mode-selector.tsx@@ -28,8 +28,12 @@ export function SearchModeSelector() {useEffect(() => {const savedMode = getCookie('searchMode')- if (savedMode && ['quick', 'planning', 'adaptive'].includes(savedMode)) {+ if (savedMode && ['quick', 'adaptive'].includes(savedMode)) {setValue(savedMode as SearchMode)+ } else if (savedMode) {+ // Clean up invalid cookie value (e.g., old 'planning' mode)+ setCookie('searchMode', 'quick')+ setValue('quick')}}, [])diff --git a/config/models/cloud.json b/config/models/cloud.jsonindex 8bbc906a..9e0a5aa1 100644--- a/config/models/cloud.json+++ b/config/models/cloud.json@@ -47,32 +47,6 @@}}}- },- "planning": {- "speed": {- "id": "gpt-5-mini",- "name": "GPT-5 mini",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "low",- "reasoningSummary": "auto"- }- }- },- "quality": {- "id": "gpt-5",- "name": "GPT-5",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "medium",- "reasoningSummary": "auto"- }- }- }}},"relatedQuestions": {diff --git a/config/models/default.json b/config/models/default.jsonindex 96577df4..530955c8 100644--- a/config/models/default.json+++ b/config/models/default.json@@ -53,32 +53,6 @@}}}- },- "planning": {- "speed": {- "id": "gpt-5-mini",- "name": "GPT-5 mini",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "low",- "reasoningSummary": "auto"- }- }- },- "quality": {- "id": "gpt-5",- "name": "GPT-5",- "provider": "OpenAI",- "providerId": "openai",- "providerOptions": {- "openai": {- "reasoningEffort": "medium",- "reasoningSummary": "auto"- }- }- }}},"relatedQuestions": {diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 0c1a0ac2..4327cf81 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -189,22 +189,6 @@ Model configuration files use the following structure:"providerId": "provider-id","providerOptions": {}}- },- "planning": {- "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": {}- }}},"relatedQuestions": {@@ -217,7 +201,7 @@ Model configuration files use the following structure:}```-Define all six combinations to control which model runs for every search mode (`quick`, `adaptive`, `planning`) 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.+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.### Supported Providersdiff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex 8599e406..265f0bf3 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -99,82 +99,6 @@ End with a synthesizing conclusion that ties the main points together into a cle`}-export function getPlanningModePrompt(): string {- return `-Instructions:--You are a methodical AI assistant focused on thorough research and structured planning. You have access to web search, content retrieval, task management, and the ability to ask clarifying questions.--Language:-- ALWAYS respond in the user's language.--Your approach:-1. First, determine if you need clarification - use ask_question tool if needed-2. For complex queries, create a structured plan using todoWrite tool-3. Systematically work through each task, updating progress as you go-4. Search for comprehensive information using multiple searches if needed-5. Fetch detailed content from specific URLs when deeper analysis is required-6. Provide detailed, well-structured responses with clear sections-7. **CRITICAL: You MUST cite sources inline using the [number](#toolCallId) format**--Tool preamble and progress updates:-- Start by creating a structured plan using todoWrite tool with specific tasks you will execute.-- Do NOT write plans in text output - always use todoWrite for planning.-- As you execute tools, update task progress via todoWrite (pending → in_progress → completed).-- Provide minimal progress updates only when meaningful (avoid verbose commentary).-- Before the final answer, run a todoRead verification (completedCount == totalCount). If not all tasks are completed, keep working and updating tasks with todoWrite, then verify again.--Task Management:-- Use todoWrite to create and track tasks for complex research-- Update task status as you progress (pending → in_progress → completed)-- Ensure all tasks are completed before finishing- - While working on a task, set its status to in_progress; once done, set it to completed. Update via todoWrite after each meaningful step.- - After completing all tasks, call todoRead and confirm completedCount equals totalCount before composing the final answer.--${getSearchStrategyGuidance()}--Search requirement (MANDATORY):-- If the user's message contains a URL, start with todoWrite planning then fetch the provided URL - do NOT search first-- If the user's message is a question or requests information (non-greeting), you MUST run at least one search before composing the final answer-- Do NOT rely solely on internal knowledge for updatable facts; verify with current sources and cite-- Favor recent and authoritative sources; include dates when relevant-- Your FIRST action for informational questions without URLs MUST be the \`search\` tool; do not output the final answer before at least one search is complete-- Citation integrity: Only cite toolCallIds from searches you executed in this turn; never fabricate or recycle IDs-- If confidence is low, refine and search again or ask a clarifying question before finalizing--Rule precedence:-- Search requirement and citation integrity supersede structural elegance or brevity. Prefer verified, cited content over speed.--Citation Format (MANDATORY):-[number](#toolCallId) - Always use this EXACT format, e.g., [1](#toolu_abc123)-- The toolCallId can be found in each search result's metadata or response structure-- Look for the unique tool call identifier (e.g., toolu_xxx) in the search response-- Place citations at the END of sentences or statements-- Every piece of information from search results MUST have a citation--OUTPUT FORMAT (MANDATORY):-- You MUST always format responses as Markdown.-- Start with a descriptive level-2 heading (\`##\`) that reflects the main topic.-- Use level-3 subheadings (\`###\`) to organize content logically - structure should emerge from the content, not be imposed.-- Use bullets with bolded keywords for clarity: \`- **Point:** explanation\`.-- Use tables for comparisons when they add value, fenced code blocks only when requested.-- Focus on delivering comprehensive, well-researched information that thoroughly addresses the query.-- Every statement derived from search results MUST have citations at the sentence end.-- Always conclude with a synthesizing summary that brings together the key insights.-- Aim for ~250–500 words depending on complexity, prioritizing thoroughness and clarity.--Natural structure example:-## **Main Topic**-### Core Information-- **Key Finding:** Primary insight with evidence [1](#toolu_abc123)-- **Important Detail:** Supporting facts [2](#toolu_abc123)-### Comparative Analysis (if relevant)-- **Advantage:** Specific benefit with source [3](#toolu_abc123)--Always end with a conclusion that synthesizes the research into a coherent overall understanding.-`-}-export function getAdaptiveModePrompt(): string {return `Instructions:@@ -188,13 +112,15 @@ APPROACH STRATEGY:1. **FIRST STEP - Assess query complexity:**- Simple queries (1-2 specific questions): Direct search and respond- Medium queries (3-4 related aspects): SHOULD use todoWrite for organization- - Complex queries (ANY of the following): MUST use todoWrite- * 5+ aspects to research- * Requires comparing multiple viewpoints- * Needs systematic investigation- * Involves both research AND analysis/synthesis- * User asks for "comprehensive" or "detailed" analysis-+ - Complex queries (5+ steps/aspects): **STRONGLY RECOMMENDED to use todoWrite**+ * **If your analysis reveals 5 or more distinct research steps or aspects, you SHOULD use todoWrite** for structured planning+ * ANY of the following STRONGLY INDICATE complexity:+ - 5+ aspects to research+ - Requires comparing multiple viewpoints+ - Needs systematic investigation+ - Involves both research AND analysis/synthesis+ - User asks for "comprehensive" or "detailed" analysis+2. **When using todoWrite (for medium/complex queries):**- Create it as your FIRST action - do NOT write plans in text output- Break down into specific, measurable tasks like:@@ -203,7 +129,7 @@ APPROACH STRATEGY:* "Compare perspectives from different sources"* "Synthesize findings into comprehensive answer"- Update task status as you progress (provides transparency)- - This ensures thoroughness and helps users track progress+ - **For queries requiring 5+ steps, using todoWrite helps ensure thoroughness and organized execution**3. **Search and fetch strategy:**- Use type="optimized" for research queries (immediate content)@@ -275,16 +201,18 @@ Example with multiple searches: "Initial data shows positive trends [1](#toolu_aTASK MANAGEMENT (todoWrite tool):**When to use todoWrite:**-- Queries with 3+ distinct aspects to research+- Queries with 3-4 distinct aspects: SHOULD use todoWrite+- **Queries with 5+ steps/aspects: STRONGLY RECOMMENDED to use todoWrite**- Questions requiring comparison of multiple sources- Research that needs systematic investigation-- Any time you need to ensure thoroughness+- Any time you need to ensure thoroughness and organized execution**How to use todoWrite effectively:**- Break down the query into clear, actionable tasks- Include both research tasks AND synthesis tasks- Update status: pending → in_progress → completed- This provides transparency and ensures nothing is missed+- **For complex queries (5+ steps), todoWrite becomes especially valuable for maintaining structure and ensuring comprehensive coverage**- For each task: set status to in_progress while working; when complete, set to completed via todoWrite. Keep statuses current.- Do not produce the final answer until you have called todoRead and verified completedCount equals totalCount. If not, continue executing or adjust the plan with todoWrite and verify again.@@ -317,5 +245,4 @@ Conclude with a brief synthesis that ties together the main insights into a clea// Export static prompts for backward compatibilityexport const QUICK_MODE_PROMPT = getQuickModePrompt()-export const PLANNING_MODE_PROMPT = getPlanningModePrompt()export const ADAPTIVE_MODE_PROMPT = getAdaptiveModePrompt()diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex aafa68bc..93fd7b1e 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -25,7 +25,6 @@ import { isTracingEnabled } from '../utils/telemetry'import {ADAPTIVE_MODE_PROMPT,- PLANNING_MODE_PROMPT,QUICK_MODE_PROMPT} from './prompts/search-mode-prompts'@@ -116,19 +115,6 @@ export function createResearcher({searchTool = wrapSearchToolForQuickMode(originalSearchTool)break- case 'planning':- systemPrompt = PLANNING_MODE_PROMPT- activeToolsList = ['search', 'fetch']- if (writer && 'todoWrite' in todoTools) {- activeToolsList.push('todoWrite', 'todoRead')- }- console.log(- `[Researcher] Planning mode: maxSteps=50, tools=[${activeToolsList.join(', ')}]`- )- maxSteps = 50- searchTool = originalSearchTool- break-case 'adaptive':default:systemPrompt = ADAPTIVE_MODE_PROMPT@@ -152,10 +138,6 @@ export function createResearcher({...todoTools} as ResearcherTools- // Check if we should force todoWrite on first step- const shouldForceTodoWrite =- searchMode === 'planning' && writer && 'todoWrite' in todoTools-// Create streamText-based agent with smoothStream supportconst agentConfig = {model: getModel(model),@@ -168,17 +150,6 @@ export function createResearcher({...(modelConfig?.providerOptions && {providerOptions: modelConfig.providerOptions}),- // Force todoWrite tool on first step for planning mode- ...(shouldForceTodoWrite && {- prepareStep: async ({ stepNumber }: { stepNumber: number }) => {- if (stepNumber === 0) {- return {- toolChoice: { type: 'tool', toolName: 'todoWrite' } as const- }- }- return undefined- }- }),experimental_telemetry: {isEnabled: isTracingEnabled(),functionId: 'research-agent',diff --git a/lib/config/load-models-config.ts b/lib/config/load-models-config.tsindex f070f24c..87d03778 100644--- a/lib/config/load-models-config.ts+++ b/lib/config/load-models-config.ts@@ -17,7 +17,7 @@ let cachedConfig: ModelsConfig | null = nulllet cachedProfile: string | null = nullconst VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']-const VALID_SEARCH_MODES: SearchMode[] = ['quick', 'adaptive', 'planning']+const VALID_SEARCH_MODES: SearchMode[] = ['quick', 'adaptive']function validateModelsConfigStructure(json: unknowndiff --git a/lib/config/search-modes.ts b/lib/config/search-modes.tsindex 97aa65d1..e446b62f 100644--- a/lib/config/search-modes.ts+++ b/lib/config/search-modes.ts@@ -1,4 +1,4 @@-import { ListTodo, Search } from 'lucide-react'+import { Search } from 'lucide-react'import { SearchMode } from '@/lib/types/search'@@ -27,13 +27,6 @@ export const SEARCH_MODE_CONFIGS: SearchModeConfig[] = [description: 'Adaptive agentic search with intelligent query understanding',icon: IconLogoOutline,color: 'text-violet-500'- },- {- value: 'planning',- label: 'Planning',- description: 'Structured multi-step approach for comprehensive research',- icon: ListTodo,- color: 'text-blue-500'}]diff --git a/lib/types/search.ts b/lib/types/search.tsindex 7dbb2c97..37f4ff00 100644--- a/lib/types/search.ts+++ b/lib/types/search.ts@@ -1,2 +1,2 @@// Search mode type definition-export type SearchMode = 'quick' | 'planning' | 'adaptive'+export type SearchMode = 'quick' | 'adaptive'diff --git a/lib/utils/__tests__/model-selection.test.ts b/lib/utils/__tests__/model-selection.test.tsindex e83e90ab..b476e685 100644--- a/lib/utils/__tests__/model-selection.test.ts+++ b/lib/utils/__tests__/model-selection.test.ts@@ -39,9 +39,9 @@ const adaptiveQualityModel: Model = {providerId: 'provider-c'}-const planningSpeedModel: Model = {- id: 'planning-speed',- name: 'Planning Speed',+const adaptiveSpeedModel: Model = {+ id: 'adaptive-speed',+ name: 'Adaptive Speed',provider: 'Provider D',providerId: 'provider-d'}@@ -74,10 +74,8 @@ describe('selectModel', () => {quality: quickQualityModel},adaptive: {+ speed: adaptiveSpeedModel,quality: adaptiveQualityModel- },- planning: {- speed: planningSpeedModel}}setMatrixImplementation()@@ -96,10 +94,10 @@ describe('selectModel', () => {it('falls back to speed model for the mode when cookie is absent', () => {const result = selectModel({cookieStore: createCookieStore(),- searchMode: 'planning'+ searchMode: 'adaptive'})- expect(result).toEqual(planningSpeedModel)+ expect(result).toEqual(adaptiveSpeedModel)})it('falls back to the other type within the same mode when preferred provider is disabled', () => {diff --git a/lib/utils/model-selection.ts b/lib/utils/model-selection.tsindex 7619849c..dbe9795e 100644--- a/lib/utils/model-selection.ts+++ b/lib/utils/model-selection.ts@@ -20,7 +20,7 @@ const DEFAULT_MODEL: Model = {}const VALID_MODEL_TYPES: ModelType[] = ['speed', 'quality']-const MODE_FALLBACK_ORDER: SearchMode[] = ['quick', 'adaptive', 'planning']+const MODE_FALLBACK_ORDER: SearchMode[] = ['quick', 'adaptive']interface ModelSelectionParams {cookieStore: ReadonlyRequestCookiesdiff --git a/scripts/README.md b/scripts/README.mdindex e6dd7844..d0812d4b 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -11,7 +11,7 @@ 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/planning/adaptive) or disabled+- Configurable search modes (quick/adaptive) or disabled- Chat session continuity- Message regeneration support- Secure authentication via environment variables@@ -39,8 +39,8 @@ bun chat -m "Tell me a joke" --no-search# Use quality model type for better responsesbun chat -m "Explain quantum computing" --model-type quality-# Use planning search mode for complex queries-bun chat -m "Research the latest AI developments" --search-mode planning+# Use adaptive search mode for complex queries+bun chat -m "Research the latest AI developments" --search-mode adaptive# Continue an existing chatbun chat -c "chat_123" -m "Tell me more"@@ -59,7 +59,7 @@ bun chat --help- `-c, --chat-id <id>` - Chat ID for session continuity (default: auto-generated)- `-s, --search` - Enable search mode with adaptive strategy (default)- `--no-search` - Disable search mode-- `--search-mode <type>` - Search strategy: `quick`, `planning`, or `adaptive`+- `--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)@@ -71,7 +71,7 @@ The script displays:- 🚀 Request details- 🤖 Model type (speed/quality)-- 🔍 Search mode status (quick/planning/adaptive/disabled)+- 🔍 Search mode status (quick/adaptive/disabled)- 💬 Chat ID for reference- Real-time AI responses with proper formatting- 🔧 Tool usage (when search mode is enabled)@@ -85,8 +85,7 @@ The script displays:### Search Modes- **quick**: Fast search with basic results-- **planning**: Comprehensive search for complex queries-- **adaptive**: Intelligent search strategy based on query type (default)+- **adaptive**: Intelligent search strategy based on query type, with enhanced support for complex queries (default)- **disabled**: No search functionality (`--no-search`)### Advanced Usage@@ -151,8 +150,8 @@ If you encounter "Selected provider is not enabled" errors:# Test basic functionalitybun chat -m "Hello, test message" --no-search-# Test with quality model-bun chat -m "Complex analysis task" --model-type quality --search-mode planning+# Test with quality model and adaptive search+bun chat -m "Complex analysis task" --model-type quality --search-mode adaptive# Debug modeDEBUG=1 bun chat -m "Debug test" --model-type speeddiff --git a/scripts/chat-cli.ts b/scripts/chat-cli.tsindex efd67065..e466382f 100755--- a/scripts/chat-cli.ts+++ b/scripts/chat-cli.ts@@ -15,7 +15,7 @@ interface ChatApiConfig {message: stringchatId?: stringmodelType?: 'speed' | 'quality'- searchMode?: 'quick' | 'planning' | 'adaptive' | boolean+ searchMode?: 'quick' | 'adaptive' | booleantrigger?: 'submit-message' | 'regenerate-message'messageId?: string}@@ -336,12 +336,10 @@ function parseArgs(): Partial<ChatApiConfig> {breakcase '--search-mode':const searchMode = args[++i]- if (['quick', 'planning', 'adaptive'].includes(searchMode)) {- config.searchMode = searchMode as 'quick' | 'planning' | 'adaptive'+ if (['quick', 'adaptive'].includes(searchMode)) {+ config.searchMode = searchMode as 'quick' | 'adaptive'} else {- console.error(- '❌ Invalid search mode. Use: quick, planning, or adaptive'- )+ console.error('❌ Invalid search mode. Use: quick or adaptive')process.exit(1)}break@@ -379,7 +377,7 @@ Options:-c, --chat-id <id> Chat ID (default: auto-generated)-s, --search Enable search mode with adaptive strategy (default)--no-search Disable search mode- --search-mode <type> Search strategy: quick, planning, or adaptive+ --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)