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

Ask a question

from valyu import Valyu

valyu = Valyu()  # reads VALYU_API_KEY from env

data = valyu.answer(query="latest developments in quantum computing")
print(data.contents)
import { Valyu } from "valyu-js";

const valyu = new Valyu(); // reads VALYU_API_KEY from env

const data = await valyu.answer({ query: "latest developments in quantum computing" });
console.log(data.contents);
curl -X POST https://api.valyu.ai/v1/answer \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{ "query": "latest developments in quantum computing" }'

Common options

OptionWhat it does
search_typeall (default), web, proprietary, or news
system_instructionsTell the AI how to process and format the answer
structured_outputA JSON schema for a consistent, parseable response
included_sourcesRestrict to datasets, domains, or paths
start_date / end_dateLimit results to a date range (YYYY-MM-DD)
country_codeBias results toward a region (e.g. "US")
fast_modeLower latency, finance and web sources prioritised
data_max_priceCap search data cost (USD, default $1.0)
data = valyu.answer(
    query="climate change research",
    system_instructions="Focus on commercial impact. Summarise key findings as bullet points.",
    included_sources=["valyu/valyu-arxiv", "valyu/valyu-pubmed"],
    start_date="2024-01-01",
    data_max_price=2.0,  # cap search data cost at $2.00 (default is $1.0)
)
print(data.contents)
Search and AI are billed separately - the cost field breaks down both. Use data_max_price to cap search cost and fast_mode for lower latency.

Streaming

Enable streaming to receive the answer progressively. The stream sends search results first, then content chunks, then metadata.
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" and chunk.content:
        print(chunk.content, end="", flush=True)
    elif chunk.type == "metadata":
        print(f"\nCost: ${chunk.cost.total_deduction_dollars:.4f}")
    elif chunk.type == "error":
        print(f"Error: {chunk.error}")
const stream = await valyu.answer("What is machine learning?", { streaming: true });

for await (const chunk of stream) {
  if (chunk.type === "search_results") {
    console.log(`Found ${chunk.search_results?.length} sources`);
  } else if (chunk.type === "content" && chunk.content) {
    process.stdout.write(chunk.content);
  } else if (chunk.type === "metadata") {
    console.log(`\nCost: $${chunk.cost?.total_deduction_dollars.toFixed(4)}`);
  } else if (chunk.type === "error") {
    console.error(`Error: ${chunk.error}`);
  }
}
curl -X POST https://api.valyu.ai/v1/answer \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{ "query": "What is machine learning?", "streaming": true }'
Chunk types: search_results (sources, streamed first), content (partial answer text), metadata (final costs, tokens, full results), done, error.

Structured output

Pass a JSON schema in structured_output to get a parseable object back instead of prose:
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"},
                    },
                    "required": ["name", "revenue"],
                },
            },
            "market_summary": {"type": "string"},
        },
        "required": ["companies", "market_summary"],
    },
)
print(data.contents)  # contents is a structured object matching your schema
Keep schemas shallow, mark essential fields required, add description fields to guide the AI, and use maxItems to bound arrays.

Response format

{
  "success": true,
  "tx_id": "tx_12345678-1234-1234-1234-123456789abc",
  "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 a breakthrough in quantum computing...",
      "source": "web",
      "date": "2024-03-15"
    }
  ],
  "search_metadata": { "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
  }
}
Without structured_output, contents is a string. When you pass a structured_output schema, contents is instead a structured object matching that schema - in Python, check with isinstance(response.contents, dict).
FieldDescription
contentsThe AI-generated answer (string, or a structured object when structured_output is set)
search_resultsSearch results the AI used
search_metadataSearch transaction details
ai_usageToken counts
costCost breakdown (search + AI)

Next steps

API reference

Complete parameter documentation

Python SDK

Python integration

TypeScript SDK

TypeScript integration

Integrations

LangChain, LlamaIndex, and more