> ## Documentation Index
> Fetch the complete documentation index at: https://docs.valyu.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Vercel AI SDK

> AI SDK tools for Valyu search API, built for Vercel AI SDK v5.

AI SDK tools for Valyu search API, built for Vercel AI SDK v5.

<Info>
  **Want to try without writing any code?** Test our search tools and see results in our [AI SDK Playground](https://ai-sdk.valyu.ai).
</Info>

<Steps>
  <Step title="Installation">
    ## Installation

    Install the Valyu AI SDK package:

    ```bash theme={null}
    npm install @valyu/ai-sdk
    ```

    Get your free API key from [Valyu Platform](https://platform.valyu.ai) - **\$10 in free credits** when you sign up!

    Add it to your `.env` file:

    ```bash theme={null}
    VALYU_API_KEY=your-api-key-here
    ```

    The package reads it automatically.
  </Step>

  <Step title="Quick Start">
    ## Quick Start

    Get started with web search in seconds:

    ```typescript theme={null}
    import { generateText } from "ai";
    import { webSearch } from "@valyu/ai-sdk";
    // Available specialised search tools: financeSearch, paperSearch,
    // bioSearch, patentSearch, secSearch, economicsSearch, companyResearch
    // Discovery tools: datasources, datasourcesCategories
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Latest data center projects for AI inference workloads?',
      tools: {
        webSearch: webSearch(),
      },
    });

    console.log(text);
    ```

    Your AI agent now has access to real-time web search.
  </Step>

  <Step title="Available Search Tools">
    ## Available Search Tools

    Beyond general web search, Valyu provides domain-specific tools for specialized research:

    * **financeSearch** - Stock prices, earnings, insider transactions, dividends, balance sheets, income statements, and more
    * **paperSearch** - Full-text search of PubMed, arXiv, bioRxiv, medRxiv, and other scholarly articles
    * **bioSearch** - Clinical trials, FDA drug labels, ChEMBL compounds, PubChem, DrugBank, Open Targets, NPI registry, WHO ICD codes, PubMed, medRxiv, bioRxiv
    * **patentSearch** - USPTO full-text patent search and related intellectual property
    * **secSearch** - SEC filings (10-K, 10-Q, 8-K) and insider transactions (Form 4)
    * **economicsSearch** - Economic indicators from BLS, FRED, World Bank, USAspending, and more
    * **companyResearch** - Comprehensive company research and intelligence reports

    ### webSearch

    Search the web for current information, news, articles, and general content.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { webSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Latest data center projects for AI inference workloads?',
      tools: {
        webSearch: webSearch(),
      },
      stopWhen: stepCountIs(3),
    });
    ```

    **Best for**: Real-time information, news, current events, general web content

    ### financeSearch

    Search financial data including stock prices, market data, earnings reports, and financial metrics.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { financeSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'What was the stock price of Apple from the beginning of 2020 to 14th feb?',
      tools: {
        financeSearch: financeSearch(),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: Stock prices, earnings reports, financial statements, market data, economic indicators

    ### paperSearch

    Search academic research papers, scholarly articles, and textbooks across all disciplines.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { paperSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Psilocybin effects on cellular lifespan and longevity in mice?',
      tools: {
        paperSearch: paperSearch(),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: Academic research, scientific papers, scholarly articles, arXiv papers

    ### bioSearch

    Search biomedical and healthcare data including PubMed, clinical trials, FDA drug labels, ChEMBL compounds, PubChem, DrugBank, Open Targets, NPI registry, and WHO ICD codes.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { bioSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Summarise top completed Phase 3 metastatic melanoma trial comparing nivolumab+ipilimumab vs monotherapy',
      tools: {
        bioSearch: bioSearch(),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: Medical research, clinical trials, drug information, disease studies, FDA labels, drug targets, healthcare providers, ICD codes

    ### patentSearch

    Search patent databases for inventions, innovations, and intellectual property.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { patentSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Find patents published in 2025 for high energy laser weapon systems',
      tools: {
        patentSearch: patentSearch({ maxNumResults: 2 }),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: Patent information, prior art, inventions, intellectual property

    ### secSearch

    Search SEC filings (10-K, 10-Q, 8-K) and insider transactions (Form 4 structured data).

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { secSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: "Summarise MD&A section of Tesla's latest 10-k filling",
      tools: {
        secSearch: secSearch(),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: SEC filings (10-K, 10-Q, 8-K), insider transactions (Form 4)

    ### economicsSearch

    Search economic data including labor statistics, Federal Reserve data, World Bank indicators, and US federal spending.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { economicsSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'What is CPI vs unemployment since 2020 in the US?',
      tools: {
        economicsSearch: economicsSearch(),
      },
      stopWhen: stepCountIs(10),
    });
    ```

    **Best for**: Labor statistics (BLS), Federal Reserve economic data (FRED), World Bank indicators, unemployment rates, GDP, inflation, government spending

    ### companyResearch

    Generate comprehensive company intelligence reports with business overview, financials, SEC filings, news, insider activity, and citations.

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { companyResearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Research the company nia AI',
      tools: {
        companyResearch: companyResearch(),
      },
      stopWhen: stepCountIs(5),
    });
    ```

    **Best for**: In-depth company research, due diligence, competitive intelligence, investment research. Automatically gathers data in parallel from multiple sources and synthesizes into a structured markdown report. Supports optional section filtering (summary, leadership, products, funding, competitors, filings, financials, news, insiders).

    **Note:** This tool automatically detects whether the company is public or private. For public companies, it returns information from SEC filings, financial statements, and other disclosures. For private companies, it pulls available data from news, funding, and other public sources.
  </Step>

  <Step title="Datasources Discovery">
    ## Datasources Discovery Tools

    Before searching, your AI agent can discover what data sources are available in the Valyu network. This is a tool manifest for AI agents to dynamically discover 36+ integrated data sources across research, finance, healthcare, legal, and more.

    ### datasources

    List available data sources with metadata, schemas, and pricing information.

    ```typescript theme={null}
    import { generateText } from "ai";
    import { datasources } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'What data sources are available for financial research?',
      tools: {
        datasources: datasources(),
      },
    });
    ```

    Filter by category to narrow results:

    ```typescript theme={null}
    import { generateText } from "ai";
    import { datasources } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Show me all biomedical data sources',
      tools: {
        datasources: datasources(),  // Agent can filter by category: 'biomedical'
      },
    });
    ```

    **Best for**: Discovering available data sources before searching, understanding source coverage, checking pricing and schemas

    ### datasourcesCategories

    List all available categories with dataset counts.

    ```typescript theme={null}
    import { generateText } from "ai";
    import { datasourcesCategories } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'What categories of data are available?',
      tools: {
        datasourcesCategories: datasourcesCategories(),
      },
    });
    ```

    **Best for**: Understanding the breadth of available data, finding relevant categories before using datasources tool

    ### Combining Discovery with Search

    Use discovery tools alongside search tools for smarter research workflows:

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { datasources, datasourcesCategories, webSearch, paperSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      messages: [
        {
          role: 'system',
          content: `You are a research assistant. Before searching:
          1. Use datasourcesCategories to understand available data categories
          2. Use datasources to find relevant sources for the query
          3. Then use appropriate search tools with targeted sources`
        },
        { role: 'user', content: 'Research quantum computing breakthroughs' }
      ],
      tools: {
        categories: datasourcesCategories(),
        sources: datasources(),
        papers: paperSearch(),
        web: webSearch(),
      },
      stopWhen: stepCountIs(5),
    });
    ```
  </Step>

  <Step title="Multi-Tool Search">
    ## Combine Multiple Search Tools

    Use multiple search tools together for comprehensive research across domains:

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { paperSearch, bioSearch, financeSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Research the commercialization of CRISPR technology',
      tools: {
        papers: paperSearch({ maxNumResults: 3 }),
        medical: bioSearch({ maxNumResults: 3 }),
        finance: financeSearch({ maxNumResults: 3 }),
      },
      stopWhen: stepCountIs(3),
    });
    ```

    Your AI agent can now intelligently choose which search tool to use based on the query.
  </Step>

  <Step title="Configuration Options">
    ## Configuration Options

    All search tools support these configuration options:

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { webSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const { text } = await generateText({
      model: openai('gpt-5'),
      prompt: 'Find high-quality analysis of the latest AI trends',
      tools: {
        webSearch: webSearch({
          // API key (defaults to process.env.VALYU_API_KEY)
          apiKey: "your-api-key",

          // Search type: "proprietary" (premium sources) or "web" (default: "proprietary")
          searchType: "proprietary",

          // Maximum number of results (default: 10)
          maxNumResults: 10,

          // Relevance threshold (0-1) to filter results by quality
          relevanceThreshold: 0.8,

          // Maximum price per query in CPM (cost per thousand retrievals)
          maxPrice: 0.01,

          // Category to focus the search on
          category: "technology",

          // Specific sources to include (dataset identifiers)
          includedSources: ["arxiv", "pubmed"],

          // Flag for agentic integration (default: true)
          isToolCall: true,

          // Enable fast mode for quicker responses with shorter content (webSearch only)
          // Ideal for general-purpose queries where speed is preferred over detail
          fastMode: false,
        }),
      },
      stopWhen: stepCountIs(3),
    });
    ```
  </Step>

  <Step title="Streaming Results">
    ## Streaming Results

    Use with `streamText` for real-time responses:

    ```typescript theme={null}
    import { streamText, stepCountIs } from "ai";
    import { paperSearch } from "@valyu/ai-sdk";
    import { anthropic } from "@ai-sdk/anthropic";

    const result = streamText({
      model: anthropic('claude-3-5-sonnet-20241022'),
      prompt: 'Summarize recent quantum computing research',
      tools: {
        papers: paperSearch(),
      },
      stopWhen: stepCountIs(3),
    });

    for await (const chunk of result.textStream) {
      process.stdout.write(chunk);
    }
    ```
  </Step>

  <Step title="Create Your Own Tool">
    ## Create Your Own Tool

    Want to build a custom search tool? Use the Valyu Search API directly with the Vercel AI SDK `tool()` function:

    ```typescript theme={null}
    import { tool } from "ai";
    import { z } from "zod";

    export function myCustomSearch(config = {}) {
      const apiKey = config.apiKey || process.env.VALYU_API_KEY;

      return tool({
        description: "Search for [your specific domain/use case]",
        inputSchema: z.object({
          query: z.string().describe("The search query"),
        }),
        execute: async ({ query }) => {
          const response = await fetch("https://api.valyu.ai/v1/search", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "x-api-key": apiKey,
            },
            body: JSON.stringify({
              query,
              max_num_results: 5,
              search_type: "all", // or "web", "proprietary"
              included_sources: ["your-custom-sources"], // optional
              // Add more parameters as needed
            }),
          });

          // Optionally filter api response

          const data = await response.json();
          return data;
        },
      });
    }
    ```

    Check out the [Valyu API Documentation](https://docs.valyu.ai) for all available parameters and data sources.
  </Step>

  <Step title="Best Practices">
    ## Best Practices

    ### System Prompting

    Guide your LLM to use search tools effectively:

    ```typescript theme={null}
    import { generateText, stepCountIs } from "ai";
    import { webSearch, paperSearch, financeSearch, bioSearch } from "@valyu/ai-sdk";
    import { openai } from "@ai-sdk/openai";

    const result = await generateText({
      model: openai('gpt-5'),
      messages: [
        {
          role: 'system',
          content: `You are an AI research assistant with access to specialized search tools.

          - Use webSearch for current events and general web content
          - Use paperSearch for academic research and scientific papers
          - Use financeSearch for stock prices, earnings, and market data
          - Use bioSearch for medical research, clinical trials, drug data, and healthcare providers
          - Do not use search operators (e.g., site:, OR, AND, quotes). Use natural keyword queries instead.
          - Always cite sources using Markdown links: [Title](URL)
          - Combine multiple tools when researching complex topics`
        },
        // ... user messages
      ],
      tools: {
        web: webSearch(),
        papers: paperSearch(),
        finance: financeSearch(),
        bio: bioSearch(),
      },
      stopWhen: stepCountIs(3),
    });
    ```

    <Tip>
      For complete query writing guidelines, see the [Prompting Guide](/search/prompting).
    </Tip>

    ### Cost Control

    Control costs with configuration options:

    ```typescript theme={null}
    webSearch({
      maxPrice: 0.01,              // Maximum cost per query
      maxNumResults: 5,            // Limit number of results
      relevanceThreshold: 0.8,     // Only high-quality results
    })
    ```

    Valyu uses a CPM (cost per thousand retrievals) pricing model, making it easy to predict and control costs.

    ### API Key Security

    * Always use environment variables for `VALYU_API_KEY`
    * Never commit API keys to version control
    * Use `.env.local` files for local development
  </Step>
</Steps>

## TypeScript Support

Full TypeScript types are included:

```typescript theme={null}
import {
  webSearch,
  ValyuWebSearchConfig,
  ValyuSearchResult,
  ValyuApiResponse
} from "@valyu/ai-sdk";

const config: ValyuWebSearchConfig = {
  maxNumResults: 10,
  searchType: "proprietary",
  relevanceThreshold: 0.7,
};

const search = webSearch(config);
```

### Available Types

* `ValyuBaseConfig` - Base configuration for all tools
* `ValyuWebSearchConfig` - Web search configuration
* `ValyuFinanceSearchConfig` - Finance search configuration
* `ValyuPaperSearchConfig` - Research paper search configuration
* `ValyuBioSearchConfig` - Biomedical search configuration
* `ValyuPatentSearchConfig` - Patent search configuration
* `ValyuSecSearchConfig` - SEC filings search configuration
* `ValyuEconomicsSearchConfig` - Economics search configuration
* `ValyuCompanyResearchConfig` - Company research configuration
* `ValyuDatasourcesConfig` - Datasources discovery configuration
* `ValyuSearchResult` - Individual search result
* `ValyuApiResponse` - API response structure

## Next Steps

* [Valyu Platform](https://platform.valyu.ai) - Get your API keys
* [Valyu Documentation](https://docs.valyu.ai) - Full API documentation
* [Valyu Website](https://valyu.ai) - Learn more about Valyu
* [GitHub Repository](https://github.com/valyu/valyu-ai-sdk) - View source code
