An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor: simplify todoWrite availability and use qualitative conditions (#784)
Yoshiki Miura42f5d8029c12
diff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex fbe9eaf1..ff1a7b51 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -141,52 +141,18 @@ End with a synthesizing conclusion that ties the main points together into a cle`}-export function getAdaptiveModePrompt({- enableTodo = false-}: { enableTodo?: boolean } = {}): string {- return `-Instructions:--You are a helpful AI assistant with access to real-time web search, content retrieval,${enableTodo ? ' task management,' : ''} and the ability to ask clarifying questions.--**EFFICIENCY GUIDELINES:**-- **Target: Complete research within ~20 tool calls when possible**-- This is a guideline, not a hard limit - use more steps for complex queries if truly needed-- Monitor your progress and stop early when you have comprehensive coverage-- Balance thoroughness with efficiency--**Early Stop Criteria (stop when ANY of these is met):**-1. All todoWrite tasks are completed and you have comprehensive information-2. Multiple search angles converge on consistent findings (~70% agreement)-3. Diminishing returns: additional searches aren't revealing new insights-4. You have strong coverage of all query aspects-5. For simple queries: You have clear answers after 5-10 steps--Language:-- ALWAYS respond in the user's language.--APPROACH STRATEGY:+function getApproachStrategy(): string {+ return `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 (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):**+ - Most queries: Direct search and respond. Do NOT use todoWrite.+ - Exceptionally complex queries: Use todoWrite ONLY when the query requires investigating multiple independent research topics that cannot be addressed in a single search flow.+ * Examples that DO need todoWrite: "Compare the economic policies, healthcare systems, and education approaches of 5 different countries"+ * Examples that do NOT need todoWrite: "Why is Nvidia growing so rapidly?", "Compare React vs Vue", "Explain quantum computing"++2. **When using todoWrite (rare, only for exceptionally complex queries):**- Create it as your FIRST action - do NOT write plans in text output- - Break down into specific, measurable tasks like:- * "Search for [specific aspect]"- * "Fetch detailed content from top 3 sources"- * "Compare perspectives from different sources"- * "Synthesize findings into comprehensive answer"+ - Break down into specific, measurable tasks- Update task status as you progress (provides transparency)- - **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)@@ -195,7 +161,7 @@ APPROACH STRATEGY:- Multiple searches with different angles for comprehensive coverageMandatory search for questions:-- If the user's message contains a URL, use appropriate todoWrite planning (for complex queries) then fetch the provided URL - do NOT search first+- If the user's message contains a URL, fetch the provided URL - do NOT search first- If the user's message is a question or asks for information (excluding casual greetings like "hello"), you MUST perform at least one search before answering- Do NOT answer informational questions based only on internal knowledge; verify with current sources and include citations- Prioritize recency when relevant and reference dates@@ -206,7 +172,7 @@ Mandatory search for questions:Tool preamble (adaptive):- For queries with URLs: Start with fetch tool (skip search entirely)- For simple queries without URLs: Start directly with search tool without text preamble-- For medium/complex queries without URLs: Use todoWrite as your FIRST action to create a plan+- For exceptionally complex queries without URLs: Use todoWrite as your FIRST action to create a plan- Do NOT write plans or goals in text output - use appropriate tools insteadRule precedence:@@ -218,7 +184,32 @@ Rule precedence:6. If results are not relevant or helpful, you may rely on your general knowledge ONLY AFTER at least one search attempt (do not add citations for general knowledge)-7. Provide comprehensive and detailed responses based on search results, ensuring thorough coverage of the user's question+7. Provide comprehensive and detailed responses based on search results, ensuring thorough coverage of the user's question`+}++export function getAdaptiveModePrompt(): string {+ return `+Instructions:++You are a helpful AI assistant with access to real-time web search, content retrieval, task management, and the ability to ask clarifying questions.++**EFFICIENCY GUIDELINES:**+- **Target: Complete research within ~20 tool calls when possible**+- This is a guideline, not a hard limit - use more steps for complex queries if truly needed+- Monitor your progress and stop early when you have comprehensive coverage+- Balance thoroughness with efficiency++**Early Stop Criteria (stop when ANY of these is met):**+1. All todoWrite tasks are completed and you have comprehensive information+2. Multiple search angles converge on consistent findings (~70% agreement)+3. Diminishing returns: additional searches aren't revealing new insights+4. You have strong coverage of all query aspects+5. For simple queries: You have clear answers after 5-10 steps++Language:+- ALWAYS respond in the user's language.++${getApproachStrategy()}TOOL USAGE GUIDELINES:@@ -272,42 +263,21 @@ IMPORTANT: Citations must appear INLINE within your response text, not separatelExample: "The company reported record revenue. [1](#toolu_abc123) Analysts predict continued growth. [2](#toolu_abc123)"Example with multiple searches: "Initial data shows positive trends. [1](#toolu_abc123) Recent updates indicate acceleration. [1](#toolu_def456)"-${- enableTodo- ? `TASK MANAGEMENT (todoWrite tool):+TASK MANAGEMENT (todoWrite tool):**When to use todoWrite:**-- 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 and organized execution+- ONLY for exceptionally complex queries that require investigating multiple independent research topics+- Most queries do NOT need todoWrite - search directly instead+- If in doubt, do NOT use todoWrite-**How to use todoWrite effectively:**+**How to use todoWrite effectively (when used):**- 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**--**Task completion verification (CRITICAL):**-- While working on a task: set its status to in_progress-- When a task is complete: set it to completed via todoWrite after each meaningful step-- Keep task statuses current throughout execution-- **IMPORTANT: When updating tasks with todoWrite, ALWAYS include ALL tasks (both completed and pending)**- - Never remove completed tasks from the list- - Always preserve the full task history with updated statuses- - This provides transparency and shows the complete progress-- **Before composing the final answer: verify that the todoWrite response shows completedCount equals totalCount**-- If not all tasks are completed: continue executing remaining tasks or adjust the plan with todoWrite-- Only proceed to write the final answer after confirming all tasks are completed (check completedCount in the todoWrite response)--Example task patterns:-- "Research [topic] from multiple sources"-- "Compare different perspectives on [topic]"-- "Fetch detailed content from top sources"-- "Synthesize findings into comprehensive answer"`- : ''-}+- **IMPORTANT: When updating tasks, ALWAYS include ALL tasks (both completed and pending)**++**Task completion verification:**+- Before composing the final answer: verify completedCount equals totalCount+- If not all tasks are completed: continue executing remaining tasks+- Only proceed to write the final answer after all tasks are completedOUTPUT FORMAT (MANDATORY):- You MUST always format responses as Markdown.diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex b40e4adf..1b02833a 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -1,9 +1,4 @@-import {- stepCountIs,- tool,- ToolLoopAgent,- type UIMessageStreamWriter-} from 'ai'+import { stepCountIs, tool, ToolLoopAgent } from 'ai'import type { ResearcherTools } from '@/lib/types/agent'import { type ModelType } from '@/lib/types/model-type'@@ -73,14 +68,12 @@ function wrapSearchToolForQuickMode<export function createResearcher({model,modelConfig,- writer,parentTraceId,searchMode = 'adaptive',modelType}: {model: stringmodelConfig?: Model- writer?: UIMessageStreamWriterparentTraceId?: stringsearchMode?: SearchModemodelType?: ModelType@@ -91,7 +84,7 @@ export function createResearcher({// Create model-specific tools with proper typingconst originalSearchTool = createSearchTool(model)const askQuestionTool = createQuestionTool(model)- const todoTools = writer ? createTodoTools() : {}+ const todoTools = createTodoTools()let systemPrompt: stringlet activeToolsList: (keyof ResearcherTools)[] = []@@ -112,15 +105,8 @@ export function createResearcher({case 'adaptive':default:- {- const enableTodo =- writer && 'todoWrite' in todoTools && modelType === 'quality'- systemPrompt = getAdaptiveModePrompt({ enableTodo: !!enableTodo })- activeToolsList = ['search', 'fetch']- if (enableTodo) {- activeToolsList.push('todoWrite')- }- }+ systemPrompt = getAdaptiveModePrompt()+ activeToolsList = ['search', 'fetch', 'todoWrite']console.log(`[Researcher] Adaptive mode: maxSteps=50, modelType=${modelType}, tools=[${activeToolsList.join(', ')}]`)diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex a3e08997..38c3c628 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -130,7 +130,6 @@ export async function createChatStreamResponse(const researchAgent = researcher({model: context.modelId,modelConfig: model,- writer,parentTraceId,searchMode,modelTypediff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.tsindex 3c9dde94..e04de70c 100644--- a/lib/streaming/create-ephemeral-chat-stream-response.ts+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts@@ -90,7 +90,6 @@ export async function createEphemeralChatStreamResponse(const researchAgent = researcher({model: `${model.providerId}:${model.id}`,modelConfig: model,- writer,parentTraceId,searchMode,modelType