An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: Add chat researcher
Yoshiki Miurae10853a18602
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 5e77fe51..f01b25fc 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -1,17 +1,17 @@-import { openai } from '@ai-sdk/openai'+import { chatResearcher } from '@/lib/agents/chat-researcher'import { streamText } from 'ai'-// Allow streaming responses up to 30 secondsexport const maxDuration = 30export async function POST(req: Request) {- const { messages } = await req.json()+ const { messages, model } = await req.json()- const result = streamText({- model: openai('gpt-4-turbo'),- system: 'You are a helpful assistant.',- messages+ const researcherConfig = await chatResearcher({+ messages,+ model})+ const result = streamText(researcherConfig)+return result.toDataStreamResponse()}diff --git a/components/chat.tsx b/components/chat.tsxindex f5e96f14..e05cf36a 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -3,8 +3,16 @@import { useChat } from 'ai/react'import { ChatMessages } from './chat-messages'import { ChatPanel } from './chat-panel'+import { useLocalStorage } from '@/lib/hooks/use-local-storage'+import { models } from '@/lib/types/models'+import { getDefaultModelId } from '@/lib/utils'export function Chat() {+ const [selectedModelId, setSelectedModelId] = useLocalStorage<string>(+ 'selectedModel',+ getDefaultModelId(models)+ )+const {messages,input,@@ -13,7 +21,11 @@ export function Chat() {isLoading,setMessages,stop- } = useChat()+ } = useChat({+ body: {+ model: selectedModelId+ }+ })return (<div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">diff --git a/lib/agents/chat-researcher.ts b/lib/agents/chat-researcher.tsnew file mode 100644index 00000000..9d4b1022--- /dev/null+++ b/lib/agents/chat-researcher.ts@@ -0,0 +1,41 @@+import { CoreMessage, streamText } from 'ai'+import { getModel } from '../utils/registry'+import { searchTool } from './tools/search'++const SYSTEM_PROMPT = `You are a helpful AI assistant with access to real-time web search capabilities.+When asked a question, you should:+1. Search for relevant information using the search tool when needed+2. Analyze the search results and provide accurate, up-to-date information+3. Always cite your sources when using information from search results+4. If search results are not relevant or helpful, rely on your general knowledge+5. Be concise and direct in your responses++Remember to:+- Use search for current events, facts, or when you need to verify information+- Clearly indicate when you're using search results vs. your general knowledge+- Admit if you cannot find relevant information for a query`++type ChatResearcherReturn = Parameters<typeof streamText>[0]++export async function chatResearcher({+ messages,+ model+}: {+ messages: CoreMessage[]+ model: string+}): Promise<ChatResearcherReturn> {+ try {+ const currentDate = new Date().toLocaleString()++ return {+ model: getModel(model),+ system: `${SYSTEM_PROMPT}\nCurrent date and time: ${currentDate}`,+ messages,+ tools: { search: searchTool },+ maxSteps: 5+ }+ } catch (error) {+ console.error('Error in chatResearcher:', error)+ throw error+ }+}diff --git a/lib/agents/tools/search.tsx b/lib/agents/tools/search.tssimilarity index 62%rename from lib/agents/tools/search.tsxrename to lib/agents/tools/search.tsindex e9aaff8d..4f263723 100644--- a/lib/agents/tools/search.tsx+++ b/lib/agents/tools/search.ts@@ -1,9 +1,6 @@import { tool } from 'ai'-import { createStreamableValue } from 'ai/rsc'import Exa from 'exa-js'import { searchSchema } from '@/lib/schema/search'-import { SearchSection } from '@/components/search-section'-import { ToolProps } from '.'import { sanitizeUrl } from '@/lib/utils'import {SearchResultImage,@@ -13,101 +10,81 @@ import {SearXNGResult} from '@/lib/types'-export const searchTool = ({ uiStream, fullResponse }: ToolProps) =>- tool({- description: 'Search the web for information',- parameters: searchSchema,- execute: async ({- query,- max_results,- search_depth,- include_domains,- exclude_domains- }) => {- let hasError = false- // Append the search section- const streamResults = createStreamableValue<string>()- uiStream.append(- <SearchSection- result={streamResults.value}- includeDomains={include_domains}- />- )-- // Tavily API requires a minimum of 5 characters in the query- const filledQuery =- query.length < 5 ? query + ' '.repeat(5 - query.length) : query- let searchResult: SearchResults- const searchAPI =- (process.env.SEARCH_API as 'tavily' | 'exa' | 'searxng') || 'tavily'+export const searchTool = tool({+ description: 'Search the web for information',+ parameters: searchSchema,+ execute: async ({+ query,+ max_results,+ search_depth,+ include_domains,+ exclude_domains+ }) => {+ // Tavily API requires a minimum of 5 characters in the query+ const filledQuery =+ query.length < 5 ? query + ' '.repeat(5 - query.length) : query+ let searchResult: SearchResults+ const searchAPI =+ (process.env.SEARCH_API as 'tavily' | 'exa' | 'searxng') || 'tavily'- const effectiveSearchDepth =- searchAPI === 'searxng' &&- process.env.SEARXNG_DEFAULT_DEPTH === 'advanced'- ? 'advanced'- : search_depth || 'basic'+ const effectiveSearchDepth =+ searchAPI === 'searxng' &&+ process.env.SEARXNG_DEFAULT_DEPTH === 'advanced'+ ? 'advanced'+ : search_depth || 'basic'- console.log(- `Using search API: ${searchAPI}, Search Depth: ${effectiveSearchDepth}`- )+ console.log(+ `Using search API: ${searchAPI}, Search Depth: ${effectiveSearchDepth}`+ )- try {- if (searchAPI === 'searxng' && effectiveSearchDepth === 'advanced') {- // API route for advanced SearXNG search- const baseUrl =- process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'- const response = await fetch(`${baseUrl}/api/advanced-search`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- query: filledQuery,- maxResults: max_results,- searchDepth: effectiveSearchDepth,- includeDomains: include_domains,- excludeDomains: exclude_domains- })+ try {+ if (searchAPI === 'searxng' && effectiveSearchDepth === 'advanced') {+ // API route for advanced SearXNG search+ const baseUrl =+ process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'+ const response = await fetch(`${baseUrl}/api/advanced-search`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ query: filledQuery,+ maxResults: max_results,+ searchDepth: effectiveSearchDepth,+ includeDomains: include_domains,+ excludeDomains: exclude_domains})- if (!response.ok) {- throw new Error(- `Advanced search API error: ${response.status} ${response.statusText}`- )- }- searchResult = await response.json()- } else {- searchResult = await (searchAPI === 'tavily'- ? tavilySearch- : searchAPI === 'exa'- ? exaSearch- : searxngSearch)(- filledQuery,- max_results,- effectiveSearchDepth === 'advanced' ? 'advanced' : 'basic',- include_domains,- exclude_domains+ })+ if (!response.ok) {+ throw new Error(+ `Advanced search API error: ${response.status} ${response.statusText}`)}- } catch (error) {- console.error('Search API error:', error)- hasError = true- searchResult = {- results: [],- query: filledQuery,- images: [],- number_of_results: 0- }+ searchResult = await response.json()+ } else {+ searchResult = await (searchAPI === 'tavily'+ ? tavilySearch+ : searchAPI === 'exa'+ ? exaSearch+ : searxngSearch)(+ filledQuery,+ max_results,+ effectiveSearchDepth === 'advanced' ? 'advanced' : 'basic',+ include_domains,+ exclude_domains+ )}-- if (hasError) {- fullResponse = `An error occurred while searching for "${filledQuery}".`- uiStream.update(null)- streamResults.done()- return searchResult+ } catch (error) {+ console.error('Search API error:', error)+ searchResult = {+ results: [],+ query: filledQuery,+ images: [],+ number_of_results: 0}-- streamResults.done(JSON.stringify(searchResult))- return searchResult}- })++ return searchResult+ }+})async function tavilySearch(query: string,