Skip to main content
The Answer API searches across web, academic, and financial sources, then uses AI to generate a readable response. You get an answer instead of raw search results.

What You Can Do

  • Get AI-generated answers - Not just search results, but actual responses
  • Access real-time data - Information from web and proprietary sources
  • Get structured outputs - Define a JSON schema for consistent, parseable responses
  • Control sources - Include or exclude specific domains and datasets

Features

AI-Enhanced Search

Search results processed by AI into coherent answers.

Fast Mode

Lower latency with finance and web sources prioritised.

Structured Responses

Define JSON schemas for consistent output formats.

Source Filtering

Include or exclude specific domains, URLs, and datasets.

Date Filtering

Filter search results by date range.

Getting Started

Basic Query

Ask a question and get an AI-generated answer:
from valyu import Valyu

valyu = Valyu() # Uses VALYU_API_KEY from env

data = valyu.answer(
    query="latest developments in quantum computing",
)
print(data["contents"])

Fast Mode

Use fast mode for quicker responses. Good for general queries:
from valyu import Valyu

valyu = Valyu()

data = valyu.answer(
    query="current market trends in tech stocks",
    fast_mode=True,
    data_max_price=30.0
)
print(data["contents"])

Search Types

TypeWhat it searchesUse for
allWeb and proprietary sources (default)Comprehensive coverage
webWeb onlyCurrent events, general topics
proprietaryAcademic, financial, premium sourcesResearch, technical analysis
newsNews articles onlyRecent news and current events

Custom Instructions

Tell the AI how to process and format the answer:
from valyu import Valyu

valyu = Valyu()

data = valyu.answer(
    query="climate change research",
    system_instructions="Focus on practical applications and commercial impact. Summarise key findings as bullet points.",
)
print(data["contents"])

Streaming

Enable streaming to receive the answer progressively as it’s generated. The stream sends search results first, then content chunks, then metadata.
from valyu import Valyu

valyu = Valyu()

# Streaming mode - returns generator yielding chunks
for chunk in valyu.answer("What is machine learning?", streaming=True):
    if chunk.type == "search_results":
        print(f"Found {len(chunk.search_results)} sources")
    elif chunk.type == "content":
        if chunk.content:
            print(chunk.content, end="", flush=True)
    elif chunk.type == "metadata":
        print(f"\nCost: ${chunk.cost.total_deduction_dollars:.4f}")
    elif chunk.type == "done":
        print("\n[Complete]")
    elif chunk.type == "error":
        print(f"Error: {chunk.error}")

Stream Chunk Types

TypeDescription
search_resultsSearch sources found (streamed first, before answer generation)
contentPartial answer text chunk
metadataFinal metadata with costs, token usage, and full search results
doneStream completed successfully
errorAn error occurred

Advanced Features

Source Filtering

Choose which sources to include or exclude:
from valyu import Valyu

valyu = Valyu()

data = valyu.answer(
    query="artificial intelligence research trends",
    included_sources=[
        "valyu/valyu-arxiv",
        "nature.com",
        "valyu/valyu-pubmed",
    ]
)
print(data["contents"])

How to specify sources:
  • Domains: "example.com" includes/excludes the whole domain
  • Paths: "https://example.com/blog" targets a specific section
  • Datasets: "valyu/valyu-arxiv" uses Valyu’s proprietary datasets

Structured Output

Get responses in a specific JSON format:
from valyu import Valyu

valyu = Valyu()

data = valyu.answer(
    query="top tech companies financial performance 2024",
    structured_output={
        "type": "object",
        "properties": {
            "companies": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "revenue": {"type": "string"},
                        "growth_rate": {"type": "string"},
                        "key_metrics": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["name", "revenue"],
                },
            },
            "market_summary": {"type": "string"},
            "analysis_date": {"type": "string"},
        },
        "required": ["companies", "market_summary"],
    },
)
print(data["contents"])

Date Filtering

Limit results to specific time periods:
from valyu import Valyu

valyu = Valyu()

data = valyu.answer(
    query="cryptocurrency market analysis",
    start_date="2024-01-01",
    end_date="2024-12-31",
    country_code="US",
)
print(data["contents"])

Response Format

Text Response (Default)

{
  "success": true,
  "ai_tx_id": "ai_tx_12345678-1234-1234-1234-123456789abc",
  "data_type": "unstructured",
  "original_query": "latest developments in quantum computing",
  "contents": "Based on the latest research, quantum computing made significant progress in 2024...",
  "search_results": [
    {
      "title": "IBM Unveils 1000-Qubit Quantum Processor",
      "url": "https://example.com/ibm-quantum",
      "snippet": "IBM announced breakthrough in quantum computing...",
      "source": "web",
      "date": "2024-03-15",
      "length": 2500
    }
  ],
  "search_metadata": {
    "tx_ids": ["search_tx_67890"],
    "number_of_results": 8,
    "total_characters": 45000
  },
  "ai_usage": {
    "input_tokens": 1250,
    "output_tokens": 420
  },
  "cost": {
    "total_deduction_dollars": 0.027,
    "search_deduction_dollars": 0.015,
    "ai_deduction_dollars": 0.012
  }
}

Structured Response

{
  "success": true,
  "ai_tx_id": "ai_tx_54321-dcba-hgfe",
  "data_type": "structured",
  "original_query": "top tech companies financial performance 2024",
  "contents": {
    "companies": [
      {
        "name": "Apple Inc.",
        "revenue": "$394.3 billion",
        "growth_rate": "+2.8%",
        "key_metrics": [
          "iPhone sales up 6%",
          "Services revenue $85.2B",
          "Record quarterly profit"
        ]
      },
      {
        "name": "Microsoft Corporation",
        "revenue": "$245.1 billion",
        "growth_rate": "+15.7%",
        "key_metrics": [
          "Azure growth 29%",
          "Office 365 users 400M",
          "AI integration boost"
        ]
      }
    ],
    "market_summary": "The tech sector showed resilience in 2024 with cloud computing and AI driving growth.",
    "analysis_date": "2024-12-01"
  },
  "search_results": [],
  "search_metadata": {
    "tx_ids": ["search_tx_98765"],
    "number_of_results": 6,
    "total_characters": 38000
  },
  "ai_usage": {
    "input_tokens": 1350,
    "output_tokens": 280
  },
  "cost": {
    "total_deduction_dollars": 0.033,
    "search_deduction_dollars": 0.018,
    "ai_deduction_dollars": 0.015
  }
}

Response Fields

FieldDescription
contentsThe AI-generated answer (text or JSON object)
data_type"unstructured" (text) or "structured" (JSON)
search_resultsSearch results the AI used
search_metadataSearch transaction details
ai_usageToken counts
costCost breakdown (search + AI)

Examples

Research Assistant

{
  "query": "machine learning interpretability methods 2024",
  "system_instructions": "Provide a technical overview of recent advances. Include key papers and practical applications.",
  "search_type": "proprietary",
  "included_sources": ["valyu/valyu-arxiv", "valyu/valyu-pubmed"],
  "data_max_price": 40.0
}

Market Analysis

{
  "query": "renewable energy sector investment trends Q4 2024",
  "structured_output": {
    "type": "object",
    "properties": {
      "total_investment": { "type": "string" },
      "top_sectors": {
        "type": "array",
        "items": { "type": "string" }
      },
      "regional_breakdown": {
        "type": "object",
        "properties": {
          "north_america": { "type": "string" },
          "europe": { "type": "string" },
          "asia_pacific": { "type": "string" }
        }
      },
      "key_trends": {
        "type": "array",
        "items": { "type": "string" }
      }
    },
    "required": ["total_investment", "key_trends"]
  },
  "search_type": "all",
  "data_max_price": 35.0
}

Technical Docs

{
  "query": "Next.js app router best practices for large applications",
  "included_sources": [
    "https://nextjs.org/docs",
    "https://github.com/vercel/next.js",
    "vercel.com/blog"
  ],
  "system_instructions": "Focus on official recommendations. Include code examples.",
  "data_max_price": 20.0
}

News

{
  "query": "AI regulation developments European Union",
  "start_date": "2024-10-01",
  "end_date": "2024-12-31",
  "search_type": "web",
  "system_instructions": "Summarise recent policy changes and their impact on tech companies.",
  "data_max_price": 25.0
}

Best Practices

Writing Queries

  1. Be specific - Detailed queries get better results
  2. Set price limits - Balance cost with quality
  3. Filter sources - Focus on authoritative sources for your domain
  4. Use custom instructions - Guide the AI for your use case

Designing Schemas

  1. Keep it simple - Avoid deeply nested structures
  2. Mark required fields - Ensure you get essential data
  3. Add descriptions - Help the AI understand what you want
  4. Limit arrays - Use maxItems to control length

Managing Costs

  1. Track both costs - Search and AI are billed separately
  2. Set data_max_price - Control search data costs
  3. Filter sources - Exclude irrelevant ones
  4. Use date filters - Narrow the search scope

Error Handling

from valyu import Valyu

valyu = Valyu()

try:
    data = valyu.answer(
        query="quantum computing applications",
    )
    if data.get("success"):
        print(data["contents"])
    else:
        print(f"Failed: {data.get('error', 'Unknown error')}")
except Exception as e:
    print(f"Request failed: {e}")

Try the Answer API

Full API reference with interactive examples

Next Steps