search.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { tool, generateText } from "ai";
  2. import { gateway } from "@ai-sdk/gateway";
  3. import { z } from "zod";
  4. /**
  5. * Web search tool using Perplexity Sonar via AI Gateway.
  6. *
  7. * Perplexity Sonar models have built-in internet access and return
  8. * synthesized answers with citations. This is wrapped as a regular tool
  9. * (with an `execute` function) so that ToolLoopAgent can loop: it calls
  10. * the model, gets results, and feeds them back for the next step.
  11. */
  12. export const webSearch = tool({
  13. description:
  14. "Search the web for current information on any topic. Use this when the user asks about something not covered by the specialized tools (weather, crypto, GitHub, Hacker News). Returns a synthesized answer based on real-time web data.",
  15. inputSchema: z.object({
  16. query: z
  17. .string()
  18. .describe(
  19. "The search query — be specific and include relevant context for better results",
  20. ),
  21. }),
  22. execute: async ({ query }) => {
  23. try {
  24. const { text } = await generateText({
  25. model: gateway("perplexity/sonar"),
  26. prompt: query,
  27. });
  28. return { content: text };
  29. } catch (error) {
  30. return {
  31. error: `Search failed: ${error instanceof Error ? error.message : "Unknown error"}`,
  32. };
  33. }
  34. },
  35. });