Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3import { PerplexitySearchClient } from './client'
4import type { PerplexitySearchClientConfig } from './client'
5
6const searchRecency = z.enum(['hour', 'day', 'week', 'month', 'year'])
7
8const inputSchema = z.object({
9 query: z.string().min(1).describe('The search query string.'),
10 max_results: z
11 .number()
12 .int()
13 .min(1)
14 .max(20)
15 .optional()
16 .describe(
17 'Maximum number of results to return. Defaults to defaultMaxResults when configured, otherwise the API default (10).',
18 ),
19 search_domain_filter: z
20 .array(z.string())
21 .max(20)
22 .optional()
23 .describe(
24 'Restrict results by domain (max 20). Use bare hostnames to allowlist (e.g. ["nytimes.com"]) or "-domain.com" to denylist. Allow and deny entries must NOT be mixed.',
25 ),
26 search_recency_filter: searchRecency
27 .optional()
28 .describe('Only include results from the given recency window.'),
29 search_after_date_filter: z
30 .string()
31 .optional()
32 .describe(
33 'Only include results published on or after this date (m/d/yyyy).',
34 ),
35 search_before_date_filter: z
36 .string()
37 .optional()
38 .describe(
39 'Only include results published on or before this date (m/d/yyyy).',
40 ),
41})
42
43const outputSchema = z.object({
44 results: z.array(
45 z.object({
46 title: z.string(),
47 url: z.string(),
48 snippet: z.string(),
49 date: z.string().optional(),
50 last_updated: z.string().optional(),
51 }),
52 ),
53})
54
55/**
56 * Build a TanStack AI tool that performs real-time web search via Perplexity.
57 *
58 * Returns `{ results: Array<{ title, url, snippet, date?, last_updated? }> }`
59 * for citation/grounding in an LLM agent loop.
60 *
61 * @example
62 * ```ts
63 * import { chat } from '@tanstack/ai'
64 * import { openaiText } from '@tanstack/ai-openai'
65 * import { perplexitySearchTool } from '@tanstack/ai-perplexity'
66 *
67 * const search = perplexitySearchTool({ defaultMaxResults: 5 })
68 * chat({ adapter: openaiText('gpt-5.2'), tools: [search], messages })
69 * ```
70 */
71export function perplexitySearchTool(
72 config: PerplexitySearchClientConfig & {
73 /** Override the tool name (defaults to `perplexity_search`). */
74 name?: string
75 /** Override the tool description shown to the model. */
76 description?: string
77 /** Default max_results applied when the model does not provide one. */
78 defaultMaxResults?: number
79 } = {},
80) {
81 const { name, description, defaultMaxResults, ...clientConfig } = config
82 if (
83 defaultMaxResults !== undefined &&
84 (!Number.isInteger(defaultMaxResults) ||
85 defaultMaxResults < 1 ||
86 defaultMaxResults > 20)
87 ) {
88 throw new Error('defaultMaxResults must be an integer between 1 and 20.')
89 }
90
91 // Lazily construct the client so missing API keys don't blow up at import
92 // time (e.g. on bundlers that statically evaluate module top-level).
93 let client: PerplexitySearchClient | null = null
94 const getClient = () => {
95 if (!client) client = new PerplexitySearchClient(clientConfig)
96 return client
97 }
98
99 return toolDefinition({
100 name: name ?? 'perplexity_search',
101 description:
102 description ??
103 'Search the web for up-to-date information using the Perplexity Search API. Returns a ranked list of web results with titles, URLs, snippets, and optional publication dates.',
104 inputSchema,
105 outputSchema,
106 }).server(async (args, ctx) => {
107 const response = await getClient().search(
108 {
109 query: args.query,
110 max_results: args.max_results ?? defaultMaxResults,
111 search_domain_filter: args.search_domain_filter,
112 search_recency_filter: args.search_recency_filter,
113 search_after_date_filter: args.search_after_date_filter,
114 search_before_date_filter: args.search_before_date_filter,
115 },
116 { signal: ctx?.abortSignal },
117 )
118
119 return {
120 results: response.results.map((result) => ({
121 title: result.title,
122 url: result.url,
123 snippet: result.snippet,
124 ...(result.date ? { date: result.date } : {}),
125 ...(result.last_updated ? { last_updated: result.last_updated } : {}),
126 })),
127 }
128 })
129}