Spaces:
Sleeping
Sleeping
File size: 9,092 Bytes
05c5ed5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | import { tool as createTool } from "ai";
import { JSONSchema7 } from "json-schema";
import { jsonSchemaToZod } from "lib/json-schema-to-zod";
import { safe } from "ts-safe";
// Exa API Types
export interface ExaSearchRequest {
query: string;
type: string;
category?: string;
includeDomains?: string[];
excludeDomains?: string[];
startPublishedDate?: string;
endPublishedDate?: string;
numResults: number;
contents: {
text:
| {
maxCharacters?: number;
}
| boolean;
livecrawl?: "always" | "fallback" | "preferred";
subpages?: number;
subpageTarget?: string[];
};
}
export interface ExaSearchResult {
id: string;
title: string;
url: string;
publishedDate: string;
author: string;
text: string;
image?: string;
favicon?: string;
score?: number;
}
export interface ExaSearchResponse {
requestId: string;
autopromptString: string;
resolvedSearchType: string;
results: ExaSearchResult[];
}
export interface ExaContentsRequest {
ids: string[];
contents: {
text:
| {
maxCharacters?: number;
}
| boolean;
livecrawl?: "always" | "fallback" | "preferred";
};
}
export const exaSearchSchema: JSONSchema7 = {
type: "object",
properties: {
query: {
type: "string",
description: "Search query",
},
numResults: {
type: "number",
description: "Number of search results to return",
default: 5,
minimum: 1,
maximum: 20,
},
type: {
type: "string",
enum: ["auto", "keyword", "neural"],
description:
"Search type - auto lets Exa decide, keyword for exact matches, neural for semantic search",
default: "auto",
},
category: {
type: "string",
enum: [
"company",
"research paper",
"news",
"linkedin profile",
"github",
"tweet",
"movie",
"song",
"personal site",
"pdf",
],
description: "Category to focus the search on",
},
includeDomains: {
type: "array",
items: { type: "string" },
description: "List of domains to specifically include in search results",
default: [],
},
excludeDomains: {
type: "array",
items: { type: "string" },
description:
"List of domains to specifically exclude from search results",
default: [],
},
startPublishedDate: {
type: "string",
description: "Start date for published content (YYYY-MM-DD format)",
},
endPublishedDate: {
type: "string",
description: "End date for published content (YYYY-MM-DD format)",
},
maxCharacters: {
type: "number",
description: "Maximum characters to extract from each result",
default: 3000,
minimum: 100,
maximum: 10000,
},
},
required: ["query"],
};
export const exaContentsSchema: JSONSchema7 = {
type: "object",
properties: {
urls: {
type: "array",
items: { type: "string" },
description: "List of URLs to extract content from",
},
maxCharacters: {
type: "number",
description: "Maximum characters to extract from each URL",
default: 3000,
minimum: 100,
maximum: 10000,
},
livecrawl: {
type: "string",
enum: ["always", "fallback", "preferred"],
description:
"Live crawling preference - always forces live crawl, fallback uses cache first, preferred tries live first",
default: "preferred",
},
},
required: ["urls"],
};
const API_KEY = process.env.EXA_API_KEY;
const BASE_URL = "https://api.exa.ai";
const fetchExa = async (endpoint: string, body: any): Promise<any> => {
if (!API_KEY) {
throw new Error("EXA_API_KEY is not configured");
}
const response = await fetch(`${BASE_URL}${endpoint}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": API_KEY,
},
body: JSON.stringify(body),
});
if (response.status === 401) {
throw new Error("Invalid EXA API key");
}
if (response.status === 429) {
throw new Error("Exa API usage limit exceeded");
}
if (!response.ok) {
throw new Error(`Exa API error: ${response.status} ${response.statusText}`);
}
return await response.json();
};
export const exaSearchToolForWorkflow = createTool({
description:
"Search the web using Exa AI - performs real-time web searches with semantic and neural search capabilities. Returns high-quality, relevant results with full content extraction.",
inputSchema: jsonSchemaToZod(exaSearchSchema),
execute: async (params) => {
const searchRequest: ExaSearchRequest = {
query: params.query,
type: params.type || "auto",
numResults: params.numResults || 5,
contents: {
text: {
maxCharacters: params.maxCharacters || 3000,
},
livecrawl: "preferred",
},
};
// Add optional parameters if provided
if (params.category) searchRequest.category = params.category;
if (params.includeDomains?.length)
searchRequest.includeDomains = params.includeDomains;
if (params.excludeDomains?.length)
searchRequest.excludeDomains = params.excludeDomains;
if (params.startPublishedDate)
searchRequest.startPublishedDate = params.startPublishedDate;
if (params.endPublishedDate)
searchRequest.endPublishedDate = params.endPublishedDate;
return fetchExa("/search", searchRequest);
},
});
export const exaContentsToolForWorkflow = createTool({
description:
"Extract detailed content from specific URLs using Exa AI - retrieves full text content, metadata, and structured information from web pages with live crawling capabilities.",
inputSchema: jsonSchemaToZod(exaContentsSchema),
execute: async (params) => {
const contentsRequest: ExaContentsRequest = {
ids: params.urls,
contents: {
text: {
maxCharacters: params.maxCharacters || 3000,
},
livecrawl: params.livecrawl || "preferred",
},
};
return fetchExa("/contents", contentsRequest);
},
});
export const exaSearchTool = createTool({
description:
"Search the web using Exa AI - performs real-time web searches with semantic and neural search capabilities. Returns high-quality, relevant results with full content extraction.",
inputSchema: jsonSchemaToZod(exaSearchSchema),
execute: (params) => {
return safe(async () => {
const searchRequest: ExaSearchRequest = {
query: params.query,
type: params.type || "auto",
numResults: params.numResults || 5,
contents: {
text: {
maxCharacters: params.maxCharacters || 3000,
},
livecrawl: "preferred",
},
};
// Add optional parameters if provided
if (params.category) searchRequest.category = params.category;
if (params.includeDomains?.length)
searchRequest.includeDomains = params.includeDomains;
if (params.excludeDomains?.length)
searchRequest.excludeDomains = params.excludeDomains;
if (params.startPublishedDate)
searchRequest.startPublishedDate = params.startPublishedDate;
if (params.endPublishedDate)
searchRequest.endPublishedDate = params.endPublishedDate;
const result = await fetchExa("/search", searchRequest);
return {
...result,
guide: `Use the search results to answer the user's question. Summarize the content and ask if they have any additional questions about the topic.`,
};
})
.ifFail((e) => {
return {
isError: true,
error: e.message,
solution:
"A web search error occurred. First, explain to the user what caused this specific error and how they can resolve it. Then provide helpful information based on your existing knowledge to answer their question.",
};
})
.unwrap();
},
});
export const exaContentsTool = createTool({
description:
"Extract detailed content from specific URLs using Exa AI - retrieves full text content, metadata, and structured information from web pages with live crawling capabilities.",
inputSchema: jsonSchemaToZod(exaContentsSchema),
execute: async (params) => {
return safe(async () => {
const contentsRequest: ExaContentsRequest = {
ids: params.urls,
contents: {
text: {
maxCharacters: params.maxCharacters || 3000,
},
livecrawl: params.livecrawl || "preferred",
},
};
return await fetchExa("/contents", contentsRequest);
})
.ifFail((e) => {
return {
isError: true,
error: e.message,
solution:
"A web content extraction error occurred. First, explain to the user what caused this specific error and how they can resolve it. Then provide helpful information based on your existing knowledge to answer their question.",
};
})
.unwrap();
},
});
|