Skip to content

An AI-powered search engine with a generative UI

feat: enhance agent implementation with improved type safety

Yoshiki Miura4fce52e692d6
diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.ts
index 5772ac29..b7725349 100644
--- a/lib/agents/researcher.ts
+++ b/lib/agents/researcher.ts
@@ -2,9 +2,15 @@ import {
Experimental_Agent as Agent,
stepCountIs,
tool,
- UIMessageStreamWriter
-} from 'ai'
-
+ UIMessage,
+ UIMessageStreamWriter} from 'ai'
+
+import type {
+ ResearcherAgent,
+ ResearcherRespondOptions,
+ ResearcherResponse,
+ ResearcherTools,
+ ResearcherUIMessage} from '@/lib/types/agent'
import { Model } from '@/lib/types/models'
import { fetchTool } from '../tools/fetch'
@@ -21,19 +27,19 @@ import {
QUICK_MODE_PROMPT
} from './prompts/search-mode-prompts'
-// Wrapper function to force optimized search for quick mode
-function wrapSearchToolForQuickMode(
- originalTool: ReturnType<typeof createSearchTool>
-): ReturnType<typeof createSearchTool> {
+// Enhanced wrapper function with better type safety
+function wrapSearchToolForQuickMode<
+ T extends ReturnType<typeof createSearchTool>
+>(originalTool: T): T {
return tool({
description: originalTool.description,
inputSchema: originalTool.inputSchema,
execute: async (params: any, context: any) => {
- // Force type to be optimized for quick mode
const executeFunc = originalTool.execute
if (!executeFunc) {
throw new Error('Search tool execute function is not defined')
}
+
const result = await executeFunc(
{
...params,
@@ -42,13 +48,12 @@ function wrapSearchToolForQuickMode(
context
)
- // Handle AsyncIterable case
+ // Handle AsyncIterable case with proper typing
if (
result &&
typeof result === 'object' &&
Symbol.asyncIterator in result
) {
- // Collect all results from the async iterable
let searchResults: any = null
for await (const chunk of result) {
searchResults = chunk
@@ -72,10 +77,11 @@ function wrapSearchToolForQuickMode(
}
)
}
- }) as ReturnType<typeof createSearchTool>
+ }) as T
}
-export function researcher({
+// Enhanced researcher function with improved type safety
+export function createResearcher({
model,
modelConfig,
abortSignal,
@@ -89,43 +95,35 @@ export function researcher({
writer?: UIMessageStreamWriter
parentTraceId?: string
searchMode?: SearchMode
-}) {
+}): ResearcherAgent {
try {
const currentDate = new Date().toLocaleString()
- // Create model-specific tools
+ // Create model-specific tools with proper typing
const originalSearchTool = createSearchTool(model)
const askQuestionTool = createQuestionTool(model)
-
- // Create todo tools if writer is provided
const todoTools = writer ? createTodoTools() : {}
- // Direct mode-based parameter selection
let systemPrompt: string
- let activeToolsList: string[]
+ let activeToolsList: (keyof ResearcherTools)[] = []
let maxSteps: number
- let searchTool: ReturnType<typeof createSearchTool>
-
- // Simple switch - no config objects
- console.log(`[Researcher] Executing in ${searchMode} mode`)
+ let searchTool = originalSearchTool
+ // Configure based on search mode
switch (searchMode) {
case 'quick':
- // Quick Mode: Minimal tools, fast responses, optimized search only
console.log(
'[Researcher] Quick mode: maxSteps=5, tools=[search, fetch]'
)
systemPrompt = QUICK_MODE_PROMPT
activeToolsList = ['search', 'fetch']
maxSteps = 5
- // Force optimized search for quick mode
searchTool = wrapSearchToolForQuickMode(originalSearchTool)
break
case 'planning':
- // Planning Mode: All tools, structured approach, many steps
systemPrompt = PLANNING_MODE_PROMPT
- activeToolsList = ['search', 'fetch'] // Temporarily removed askQuestion until improvements
+ activeToolsList = ['search', 'fetch']
if (writer && 'todoWrite' in todoTools) {
activeToolsList.push('todoWrite', 'todoRead')
}
@@ -138,7 +136,6 @@ export function researcher({
case 'adaptive':
default:
- // Adaptive Mode: Balanced approach, current behavior
systemPrompt = ADAPTIVE_MODE_PROMPT
activeToolsList = ['search', 'fetch']
if (writer && 'todoWrite' in todoTools) {
@@ -152,24 +149,24 @@ export function researcher({
break
}
- // Build tools object with potentially wrapped search tool
- const tools = {
+ // Build tools object with proper typing
+ const tools: ResearcherTools = {
search: searchTool,
fetch: fetchTool,
askQuestion: askQuestionTool,
...todoTools
- }
+ } as ResearcherTools
// Check if we should force todoWrite on first step
const shouldForceTodoWrite =
searchMode === 'planning' && writer && 'todoWrite' in todoTools
- // Return an agent instance
- return new Agent({
+ // Create and return the agent with enhanced type safety
+ const agent = new Agent<ResearcherTools>({
model: getModel(model),
system: `${systemPrompt}\nCurrent date and time: ${currentDate}`,
tools,
- activeTools: activeToolsList as (keyof typeof tools)[],
+ activeTools: activeToolsList,
stopWhen: stepCountIs(maxSteps),
abortSignal,
...(modelConfig?.providerOptions && {
@@ -200,8 +197,25 @@ export function researcher({
}
}
})
+
+ return agent as ResearcherAgent
} catch (error) {
- console.error('Error in researcher:', error)
+ console.error('Error in createResearcher:', error)
throw error
}
}
+
+// Helper function to access agent tools
+export function getResearcherTools(agent: ResearcherAgent): ResearcherTools {
+ return agent.tools
+}
+
+// Helper function to create a respond wrapper with type safety
+export function createResearcherRespond(agent: ResearcherAgent) {
+ return (options: ResearcherRespondOptions): ResearcherResponse => {
+ return agent.respond(options)
+ }
+}
+
+// Export the legacy function name for backward compatibility
+export const researcher = createResearcher
diff --git a/lib/types/agent.ts b/lib/types/agent.ts
new file mode 100644
index 00000000..5f0bb815
--- /dev/null
+++ b/lib/types/agent.ts
@@ -0,0 +1,72 @@
+import type {
+ Experimental_Agent as Agent,
+ Experimental_InferAgentUIMessage as InferAgentUIMessage,
+ InferUITools,
+ UIMessage,
+ UIToolInvocation} from 'ai'
+
+import type { fetchTool } from '../tools/fetch'
+import type { createQuestionTool } from '../tools/question'
+import type { createSearchTool } from '../tools/search'
+import type { createTodoTools } from '../tools/todo'
+
+// Define the tools type for researcher agent
+export type ResearcherTools = {
+ search: ReturnType<typeof createSearchTool>
+ fetch: typeof fetchTool
+ askQuestion: ReturnType<typeof createQuestionTool>
+} & ReturnType<typeof createTodoTools>
+
+// Type for the researcher agent
+export type ResearcherAgent = Agent<ResearcherTools>
+
+// Infer UI message type for researcher agent
+export type ResearcherUIMessage = InferAgentUIMessage<ResearcherAgent>
+
+// Infer UI tools type for researcher agent
+export type ResearcherUITools = InferUITools<ResearcherTools>
+
+// Tool invocation types for each tool
+export type SearchToolInvocation = UIToolInvocation<ResearcherTools['search']>
+export type FetchToolInvocation = UIToolInvocation<ResearcherTools['fetch']>
+export type QuestionToolInvocation = UIToolInvocation<
+ ResearcherTools['askQuestion']
+>
+export type TodoWriteToolInvocation = UIToolInvocation<
+ ResearcherTools['todoWrite']
+>
+export type TodoReadToolInvocation = UIToolInvocation<
+ ResearcherTools['todoRead']
+>
+
+// Union type for all tool invocations
+export type ResearcherToolInvocation =
+ | SearchToolInvocation
+ | FetchToolInvocation
+ | QuestionToolInvocation
+ | TodoWriteToolInvocation
+ | TodoReadToolInvocation
+
+// Helper type to extract tool names
+export type ResearcherToolName = keyof ResearcherTools
+
+// Type guard functions
+export function isSearchToolInvocation(
+ invocation: ResearcherToolInvocation
+): invocation is SearchToolInvocation {
+ return 'query' in (invocation as any).input
+}
+
+export function isFetchToolInvocation(
+ invocation: ResearcherToolInvocation
+): invocation is FetchToolInvocation {
+ return 'url' in (invocation as any).input
+}
+
+// Response type for agent.respond()
+export type ResearcherResponse = Response
+
+// Options type for agent.respond()
+export type ResearcherRespondOptions = {
+ messages: UIMessage<never, never, ResearcherUITools>[]
+}