import { z } from "zod";
import { tool } from "ai";
import { Valyu, SearchType as ValyuSearchSDKType } from "valyu-js"; // Ensure ValyuSearchSDKType is the correct export for search types
export const valyuDeepSearchTool = tool({
description:
"Search Valyu for real-time academic papers, web content, market data, etc. Use for specific, up-to-date information across various domains.",
parameters: z.object({
query: z
.string()
.describe(
'Detailed search query (e.g., "latest advancements in AI for healthcare" or "current price of Bitcoin").'
),
searchType: z
.enum(["all", "web", "market", "academic", "proprietary"])
.describe(
'Search domain: "academic", "web", "market", "all", or "proprietary" for specific Valyu datasets.'
),
}),
execute: async ({ query, searchType }) => {
const VALYU_API_KEY = process.env.VALYU_API_KEY;
if (!VALYU_API_KEY) {
console.error("VALYU_API_KEY is not set.");
return JSON.stringify({
success: false,
error: "Valyu API key not configured.",
results: [],
});
}
const valyu = new Valyu(VALYU_API_KEY);
const searchTypeMap: { [key: string]: ValyuSearchSDKType } = {
all: "all",
web: "web",
market: "all",
academic: "proprietary",
proprietary: "proprietary",
};
const mappedSearchType: ValyuSearchSDKType =
searchTypeMap[searchType] || "all";
try {
console.log(
`[ValyuDeepSearchTool] Query: "${query}", LLM Type: ${searchType}, Valyu Type: ${mappedSearchType}`
);
const response = await valyu.search(
query,
{
searchType: mappedSearchType,
maxNumResults: 5,
maxPrice: 50.0,
relevanceThreshold: 0.5,
...(searchType === "academic"
? { includedSources: ["valyu/valyu-arxiv"] }
: {}),
}
);
if (!response.success) {
console.error("[ValyuDeepSearchTool] API Error:", response.error);
return JSON.stringify({
success: false,
error: response.error || "Valyu API request failed.",
query,
results: [],
});
}
console.log(
`[ValyuDeepSearchTool] Success. Results: ${response.results?.length}, TX_ID: ${response.tx_id}`
);
return JSON.stringify({
success: true,
query,
results: response.results || [],
tx_id: response.tx_id,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error.";
console.error("[ValyuDeepSearchTool] Exception:", errorMessage);
return JSON.stringify({
success: false,
error: errorMessage,
query,
results: [],
});
}
},
});