Give your Vercel AI SDK apps the context they need. With Valyu’s DeepSearch API, you can plug in real-time, authoritative information from academic papers, market data, web content, and more—no fuss, just answers your users can trust.

1. Get API Key & Install

  • Get your Valyu API Key: Head to Valyu Platform to grab your key (you get $10 free credits!). Store it as an environment variable: VALYU_API_KEY="your_actual_api_key".
  • Install Packages:
    npm install valyu-js ai @ai-sdk/openai zod
    # or yarn, pnpm

2. The Valyu DeepSearch Tool (Copy & Paste)

Here’s the complete tool definition for DeepSearch. This allows your Vercel AI app to call Valyu for various search types.

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: [],
      });
    }
  },
});

Explanation:

  • This tool, valyuDeepSearchTool, is flexible and takes a searchType.
  • It securely uses VALYU_API_KEY.
  • Returns a JSON string for the Vercel AI SDK.

3. Integrate Web Search (Copy & Paste)

For simple, dedicated web search, use this specialized tool:

import { z as zodWeb } from "zod"; // Use a different alias for Zod if imported again in the same scope
import { tool as toolWeb } from "ai";
import {
  Valyu as ValyuWeb,
  SearchType as ValyuWebSearchSDKType,
} from "valyu-js";

export const valyuWebSearchTool = toolWeb({
  description:
    "Perform a web search using Valyu for up-to-date information from the internet.",
  parameters: zodWeb.object({
    query: zodWeb.string().describe("The search query for the web."),
  }),
  execute: async ({ query }) => {
    const VALYU_API_KEY = process.env.VALYU_API_KEY;
    if (!VALYU_API_KEY) {
      console.error("VALYU_API_KEY is not set for web search.");
      return JSON.stringify({
        success: false,
        error: "Valyu API key not configured.",
        results: [],
      });
    }
    const valyu = new ValyuWeb(VALYU_API_KEY);
    try {
      console.log(`[ValyuWebSearchTool] Web Query: "${query}"`);
      const response = await valyu.search(
        query,
        {
          searchType: "web" as ValyuWebSearchSDKType, // Fixed to web search
          maxNumResults: 5,
          maxPrice: 10.0, // Adjust maxPrice for web search if needed
          relevanceThreshold: 0.5,
        }
      );
      if (!response.success) {
        console.error("[ValyuWebSearchTool] API Error:", response.error);
        return JSON.stringify({
          success: false,
          error: response.error || "Valyu Web API request failed.",
          query,
          results: [],
        });
      }
      console.log(
        `[ValyuWebSearchTool] 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("[ValyuWebSearchTool] Exception:", errorMessage);
      return JSON.stringify({
        success: false,
        error: errorMessage,
        query,
        results: [],
      });
    }
  },
});

Explanation:

  • valyuWebSearchTool is specifically for web searches (searchType: 'web').
  • It only requires a query parameter.

4. Plug Tools In

Add one or both tools to your Vercel AI SDK’s streamText or generateText call:

import { streamText, CoreMessage } from "ai";
import { openai } from "@ai-sdk/openai";
// Import your tools (ensure paths are correct)
// import { valyuDeepSearchTool } from './path-to-your-tools-file';
// import { valyuWebSearchTool } from './path-to-your-tools-file';

async function POST(req: Request) {
  const aiMessages: CoreMessage[] = []; // Placeholder for your actual messages

  const result = await streamText({
    model: openai("gpt-4o"),
    messages: aiMessages,
    system: `You are a helpful AI. Use valyuDeepSearchTool for varied searches or valyuWebSearchTool for web info. Cite sources: [Title](URL).`,
    tools: {
      valyuDeepSearch: valyuDeepSearchTool, // For comprehensive search
      valyuWebSearch: valyuWebSearchTool, // For dedicated web search
      // Add other tools as needed
    },
    toolChoice: "auto",
  });

  return result.toAIStreamResponse();
}

5. Basic Prompting

Instruct your LLM to use the appropriate tool:

System Prompt:

You are an AI assistant.
- For general web searches, use "valyuWebSearchTool" with a "query".
- For specific research (academic, market data), use "valyuDeepSearchTool" with a "query" and relevant "searchType" ('academic', 'market', 'all', 'proprietary').
- **Always cite information from search results using Markdown links: [Source Title](URL_from_result).**

6. Important Notes

  • API Key Security: Always use environment variables for VALYU_API_KEY.
  • Valyu SDK Type: Ensure ValyuSearchSDKType (and ValyuWebSearchSDKType) correctly refers to the search type enum/type exported by your valyu-js package.
  • Zod Aliases: If defining both tools in the same file/scope, you might need to alias Zod imports (e.g., import { z as zodWeb } from 'zod';) to avoid naming conflicts if you haven’t already.

That’s it! Your Vercel AI application can now leverage Valyu’s DeepSearch.