Skip to main content
The Answer API searches relevant sources and synthesizes a cited, factual answer in one call. It supports streaming and non-streaming modes (non-streaming by default).

Wire up Valyu Answer (search-grounded answers) with the Python SDK.

Open in Cursor

Basic usage

from valyu import Valyu

valyu = Valyu()

response = valyu.answer("What are the latest developments in quantum computing?")

if response.success:
    print(response.contents)
    print("Sources used:", response.search_metadata.number_of_results)

Common patterns

# Steer tone and format
valyu.answer("Explain quantum computing", system_instructions="Explain clearly with practical examples, no jargon.")

# Restrict to authoritative sources
valyu.answer(
    "React performance best practices",
    search_type="web",
    included_sources=["react.dev", "developer.mozilla.org"],
)

# Recent, location-specific answers
valyu.answer("Current renewable energy incentives", country_code="US", start_date="2024-01-01")

# Lower latency
valyu.answer("Current status of the stock market", fast_mode=True)

Structured output

Pass a JSON schema to structured_output and response.contents comes back as a structured object (a dict) instead of a string. Detect it with isinstance(response.contents, dict):
response = valyu.answer(
    "What is the impact of AI on software development?",
    structured_output={
        "type": "object",
        "properties": {
            "summary": {"type": "string"},
            "key_impacts": {"type": "array", "items": {"type": "string"}},
            "future_outlook": {"type": "string"},
        },
        "required": ["summary", "key_impacts"],
    },
)

if response.success and isinstance(response.contents, dict):
    print(response.contents["summary"])
    print(response.contents["key_impacts"])

Streaming

Set streaming=True to receive the answer progressively. The method returns a generator yielding typed 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" 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}")
Chunk typeDescription
search_resultsSources found (streamed first, before answer generation)
contentPartial answer text chunk
metadataFinal costs, token usage, and full search results
doneStream completed successfully
errorAn error occurred
For open-ended, multi-step work (reports, diligence, deliverables), reach for DeepResearch instead of Answer.

Reference

query (str, required) - the question to answer.
ParameterTypeDescriptionDefault
structured_outputdictJSON schema for structured responseNone
system_instructionsstrCustom AI instructions (max 2000 chars)None
search_type"web" | "proprietary" | "all" | "news"Search type before generating the answer"all"
data_max_pricefloatMax cost in USD for data retrieval (search costs only)1.0
country_codestr2-letter ISO country code to bias resultsNone
included_sources / excluded_sourcesList[str]Sources to search within / excludeNone
start_date / end_datestrDate filter (YYYY-MM-DD)None
fast_modeboolReduced latencyFalse
streamingboolStream chunks as they are generatedFalse
# Union type - either success or error
AnswerResponse = Union[AnswerSuccessResponse, AnswerErrorResponse]

class AnswerSuccessResponse:
    success: bool = True
    tx_id: str
    original_query: str
    contents: Union[str, Dict[str, Any]]  # str, or a dict when structured_output is passed
    search_results: List[SearchResult]
    search_metadata: SearchMetadata
    ai_usage: AIUsage
    cost: Cost

class AnswerErrorResponse:
    success: bool = False
    error: str