|
| 1 | +import { tool } from "ai"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { getContext } from "./smart-search.mjs"; |
| 4 | + |
| 5 | +export const smartSearchTool = tool({ |
| 6 | + description: |
| 7 | + "Search for information about Faust using WP Engine Smart Search. Use this to answer questions about Faust, its features, capabilities, and more when the information is not already known.", |
| 8 | + parameters: z.object({ |
| 9 | + query: z |
| 10 | + .string() |
| 11 | + .describe( |
| 12 | + "The search query to find relevant Faust information based on the user's question.", |
| 13 | + ), |
| 14 | + }), |
| 15 | + execute: async ({ query }) => { |
| 16 | + console.log(`[Tool Execution] Searching with query: "${query}"`); |
| 17 | + try { |
| 18 | + const context = await getContext(query); |
| 19 | + |
| 20 | + if (context.errors && context.errors.length > 0) { |
| 21 | + console.error( |
| 22 | + "[Tool Execution] Error fetching context:", |
| 23 | + context.errors, |
| 24 | + ); |
| 25 | + // Return a structured error message that the LLM can understand |
| 26 | + return { |
| 27 | + error: `Error fetching context: ${context.errors[0].message}`, |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + if (context?.data?.similarity?.docs?.length === 0) { |
| 32 | + console.log("[Tool Execution] No documents found for query:", query); |
| 33 | + return { |
| 34 | + searchResults: "No relevant information found for your query.", |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + const formattedResults = context.data.similarity.docs.map((doc) => { |
| 39 | + if (!doc) { |
| 40 | + return {}; |
| 41 | + } |
| 42 | + |
| 43 | + return { |
| 44 | + id: doc.id, |
| 45 | + title: doc.data.post_title, |
| 46 | + content: doc.data.post_content, |
| 47 | + url: doc.data.post_url, |
| 48 | + categories: doc.data.categories.map((category) => category.name), |
| 49 | + searchScore: doc.score, |
| 50 | + }; |
| 51 | + }); |
| 52 | + |
| 53 | + // console.log("[Tool Execution] Search results:", formattedResults); |
| 54 | + |
| 55 | + return { searchResults: formattedResults }; // Return the formatted string |
| 56 | + } catch (error) { |
| 57 | + console.error("[Tool Execution] Exception:", error); |
| 58 | + return { error: `An error occurred while searching: ${error.message}` }; |
| 59 | + } |
| 60 | + }, |
| 61 | +}); |
0 commit comments