Skip to main content
You can easily integrate Valyu’s DeepSearch API into your Vercel AI SDK apps. Ground your AI with real-time, authoritative information from the web and proprietary sources by allowing your AI SDK agents to search for information they need.
1

Get API Key & Install

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)

The Valyu DeepSearch Tool

Here’s the complete tool definition for DeepSearch. This allows your Vercel AI app to call Valyu and retrieve real-time results.
import { z } from "zod";
import { tool } from "ai";
import { Valyu } from "valyu-js";

export const valyuDeepSearchTool = tool({
  description:
    "Valyu DeepSearch surfaces real-time web content, research, financial data, and proprietary datasets; use it for specific, up-to-date search across domains.",
  parameters: z.object({
    query: z
      .string()
      .describe(
        'Detailed search query (e.g., "latest advancements in AI for healthcare" or "current price of Bitcoin").'
      ),
    fastMode: z
      .boolean()
      .default(false)
      .describe(
        "Enable for faster, lower-cost lookups (fewer deep results, slightly lower recall)."
      ),
  }),
  execute: async ({ query, fastMode }) => {
    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);

    try {
      console.log(
        `[ValyuDeepSearchTool] Query: "${query}", Fast Mode: ${fastMode}`
      );
      const response = await valyu.search(query, {
        fastMode,
        // Fast mode trades depth and richer context for lower latency and cost.
      });

      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:
  • valyuDeepSearchTool accepts a detailed query plus an optional fastMode flag.
  • fastMode defaults to false—flip it on for lower latency when you can tolerate shallower recall.
  • It securely uses VALYU_API_KEY.
  • Returns a JSON string for the Vercel AI SDK.
3

Additional Tools (Contents API)

Transform URLs with the Contents API

Allow your users to provide context by providng links. The Contents API delivers cleaned markdown (or structured JSON) for a single URL and passes it to your agents.
import { z } from "zod";
import { tool } from "ai";
import { Valyu } from "valyu-js";

export const valyuContentsTool = tool({
  description:
    "Fetch cleaned page content for a URL using Valyu's Contents API.",
  parameters: z.object({
    url: z
      .string()
      .url()
      .describe("HTTPS URL to extract. Must be publicly reachable."),
    responseLength: z
      .enum(["short", "medium", "large"])
      .default("medium")
      .describe("How much of the page to return."),
    summary: z
      .boolean()
      .default(true)
      .describe("Generate an AI summary alongside the full content."),
  }),
  execute: async ({ url, responseLength, summary }) => {
    const VALYU_API_KEY = process.env.VALYU_API_KEY;
    if (!VALYU_API_KEY) {
      console.error("VALYU_API_KEY is not set for contents.");
      return JSON.stringify({
        success: false,
        error: "Valyu API key not configured.",
        url,
      });
    }

    const valyu = new Valyu(VALYU_API_KEY);

    try {
      const response = await valyu.contents({
        urls: [url],
        responseLength,
        summary,
        extractEffort: "auto",
        maxPriceDollars: 0.25,
      });

      const result = response.results?.[0];
      if (!response.success || !result) {
        return JSON.stringify({
          success: false,
          error: response.error || "Valyu Contents API request failed.",
          url,
        });
      }

      return JSON.stringify({
        success: true,
        url,
        content: result.content,
        summary: result.summary,
        metadata: result.metadata,
      });
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error.";
      console.error("[ValyuContentsTool] Exception:", errorMessage);
      return JSON.stringify({
        success: false,
        error: errorMessage,
        url,
      });
    }
  },
});
When to use it
  • DeepSearch: “Find me sources about…”
  • Contents: “Here’s a URL, give me cleaned content and a summary.”
4

Plug Tools In & Configure

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 { valyuContentsTool } 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-5"),
    messages: aiMessages,
    system: `You are a helpful AI. Valyu DeepSearch surfaces real-time academic papers, web content, market data, and proprietary datasets. Use it for specific, up-to-date research across domains. Call valyuDeepSearchTool for research queries (toggle fastMode when speed matters) and valyuContentsTool when the user provides a URL. Always cite sources: [Title](URL).`,
    tools: {
      valyuDeepSearch: valyuDeepSearchTool, // For comprehensive or quick search
      valyuContents: valyuContentsTool, // For turning URLs into clean content
      // Add other tools as needed
    },
    toolChoice: "auto",
  });

  return result.toAIStreamResponse();
}

Basic Prompting

Instruct your LLM to use the appropriate tool:
System Prompt:

You are an AI assistant.
- Valyu DeepSearch surfaces real-time web content, research, financial data, and proprietary datasets; use it for specific, up-to-date search across domains.
- Call "valyuDeepSearchTool" with a "query"; set "fastMode: true" when you need lower latency and can accept shallower recall.
- When a user gives you a URL, call "valyuContentsTool" with that "url" to fetch cleaned content and summaries.
- **Always cite information from search results using Markdown links: [Source Title](URL_from_result).**

Important Notes

  • API Key Security: Always use environment variables for VALYU_API_KEY.
  • Fast Mode Trade-off: Fast mode reduces latency and spend but may skip deeper sources—leave it false for comprehensive research.
That’s it! Your Vercel AI application can now leverage Valyu’s DeepSearch.
I