Get AI-powered answers that combine real-time search with advanced reasoning. The Answer API searches across web, academic, and financial data sources, then processes the results with AI to deliver readable, contextual responses.

Why Use the Answer API

The Answer API provides responses powered by real-time search that enable:
  • πŸ€– LLM-Native Responses - Get AI-generated answers instead of raw search results
  • πŸ” Real-Time Knowledge - Access up-to-date information from web and proprietary sources
  • πŸ“Š Structured Outputs - Define JSON schemas for consistent, parseable responses
  • 🎯 Source Control - Include or exclude specific domains and datasets

Key Answer API Features

AI-Enhanced Search

Intelligent Processing Combine search results with AI reasoning for comprehensive answers.

Fast Mode

Optimized Speed Reduced latency with Finance + Web sources prioritization while maintaining AI quality.

Structured Responses

JSON Schema Support Define structured output formats for consistent, parseable responses.

Source Filtering

Granular Control Include or exclude specific domains, URLs, and datasets from search.

Date Filtering

Date Filtering Filter search results by date range.

Getting Started

Basic AI-Powered Query

Ask any question and get an intelligent response powered by real-time search:
from valyu import Valyu

valyu = Valyu() # Uses VALYU_API_KEY from env

data = valyu.answer(
query="latest developments in quantum computing",
)
print(data["contents"]) # AI-processed response

Fast Mode for Faster Responses

Enable fast mode for reduced latency but shorter results. Best for general purpose queries:
from valyu import Valyu

valyu = Valyu()

# Fast mode for reduced response time

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

This returns an AI-processed response based on the most relevant search results.

Search Type Options

Control which data sources to search:
TypeDescriptionBest For
allSearch web and proprietary sources (default)Comprehensive coverage
webWeb search onlyCurrent events, general topics
proprietaryAcademic, financial, and premium sources onlyResearch, technical analysis

Custom AI Instructions

Guide the AI processing with custom system instructions:
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"])

Advanced Features

Source Filtering

Control exactly 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"])

Source Filtering Rules:
  • Domains: Use "example.com" to include/exclude entire domains
  • Specific Paths: Use "https://example.com/blog" for specific sections
  • Datasets: Use dataset names like "valyu/valyu-arxiv" for proprietary sources

Structured Output with JSON Schema

Get responses in a consistent, structured 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 Range Filtering

Focus on 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

Unstructured 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 findings, quantum computing has made significant breakthroughs in 2024. Key developments include:\n\n**Hardware Advances**: IBM's new 1000-qubit processor demonstrates improved error correction rates, while Google's quantum supremacy claims continue to be validated through practical applications...\n\n**Commercial Applications**: Financial institutions are beginning to deploy quantum algorithms for risk analysis and portfolio optimisation, with early results showing 15-20% improvements in processing speed...",
  "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 (JSON Schema)

{
  "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 despite economic headwinds.",
    "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
  }
}

Key Response Fields

FieldDescription
contentsAI-generated response (string or structured object)
data_type"unstructured" (text) or "structured" (JSON)
search_resultsSimplified search results metadata used by AI
search_metadataCost breakdown and search transaction details
ai_usageToken usage information
costDetailed cost breakdown

Common Use Cases

Research Assistant

Get comprehensive research summaries with citations:
{
  "query": "machine learning interpretability methods 2024",
  "system_instructions": "Provide a technical overview focusing on recent methodological 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

Extract structured financial insights:
{
  "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
}
Find specific technical information with focused sources:
{
  "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 and provide code examples where relevant.",
  "data_max_price": 20.0
}

News and Current Events

Get recent updates with time filtering:
{
  "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 potential impact on tech companies.",
  "data_max_price": 25.0
}

Best Practices

Optimise Your Queries

  1. Be Specific: Use detailed queries for better search results
  2. Set Appropriate Price Limits: Balance cost with data quality needs
  3. Use Source Filtering: Focus on authoritative sources for your domain
  4. Custom System Instructions: Guide AI processing for your specific use case

Structured Output Design

  1. Keep Schemas Simple: Avoid overly complex nested structures
  2. Use Required Fields: Mark essential fields as required
  3. Provide Descriptions: Help AI understand expected content
  4. Limit Array Sizes: Use maxItems to control response length

Cost Management

  1. Monitor Both Costs: Track search data and AI processing costs separately
  2. Adjust Price Limits: Use data_max_price to control search data costs
  3. Optimise Sources: Exclude irrelevant sources to reduce data costs
  4. Use Date Filters: Limit search scope to recent content when appropriate

Error Handling

from valyu import Valyu

valyu = Valyu()

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

Try the Answer API

Explore the complete API reference with interactive examples and detailed parameter documentation.

Next Steps