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.
The Answer API combines intelligent search with AI processing to generate comprehensive, factual answers to questions. It automatically searches relevant sources and uses advanced AI to synthesize accurate responses.
The API supports both streaming and non-streaming modes. By default, streaming is disabled for backward compatibility.
Basic Usage
from valyu import Valyu
valyu = Valyu()
# Non-streaming (default) - waits for complete response
response = valyu.answer(
"What are the latest developments in quantum computing?"
)
if response.success:
print("Answer:", response.contents)
print("Sources used:", response.search_metadata.number_of_results)
Streaming Mode
Enable streaming to receive the answer progressively as it’s generated:
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":
# Print content as it streams in
if chunk.content:
print(chunk.content, end="", flush=True)
elif chunk.type == "metadata":
print(f"\nCost: ${chunk.cost.total_deduction_dollars:.4f}")
print(f"Tokens: {chunk.ai_usage.input_tokens} in, {chunk.ai_usage.output_tokens} out")
elif chunk.type == "done":
print("\n[Complete]")
elif chunk.type == "error":
print(f"Error: {chunk.error}")
Stream Chunk Types
| Type | Description |
|---|
search_results | Search sources found (streamed first, before answer generation) |
content | Partial answer text chunk |
metadata | Final metadata with costs, token usage, and full search results |
done | Stream completed successfully |
error | An error occurred |
Parameters
Query (Required)
| Parameter | Type | Description |
|---|
query | str | The question or query to answer |
Options (Optional)
| Parameter | Type | Description | Default |
|---|
structured_output | dict | JSON schema for structured response format | None |
system_instructions | str | Custom AI instructions (max 2000 characters) | None |
search_type | "web" | "proprietary" | "all" | "news" | Search type before generating answer | "all" |
data_max_price | float | Maximum cost in USD for data retrieval (search costs only) | 1.0 |
country_code | str | 2-letter ISO country code to bias results | None |
included_sources | List[str] | Sources to search within | None |
excluded_sources | List[str] | Sources to exclude | None |
start_date | str | Start date for filtering (YYYY-MM-DD) | None |
end_date | str | End date for filtering (YYYY-MM-DD) | None |
fast_mode | bool | Enable fast mode for reduced latency | False |
streaming | bool | Enable streaming mode to receive chunks as they’re generated | False |
# Union type - either success or error response
AnswerResponse = Union[AnswerSuccessResponse, AnswerErrorResponse]
class AnswerSuccessResponse:
success: bool = True
tx_id: str
original_query: str
contents: Union[str, Dict[str, Any]] # string or structured object
data_type: str # "unstructured" | "structured"
search_results: List[SearchResult]
search_metadata: SearchMetadata
ai_usage: AIUsage
cost: Cost
class AnswerErrorResponse:
success: bool = False
error: str
Parameter Examples
Basic Question Answering
Get a comprehensive answer to any question:
response = valyu.answer(
"How do neural networks learn?"
)
if response.success:
print(response.contents)
System Instructions
Customize the AI’s response style and focus:
response = valyu.answer(
"Explain quantum computing",
system_instructions="You are a computer science professor. Explain concepts clearly with practical examples and avoid overly technical jargon."
)
Structured Output Response
Get answers in a specific JSON format:
response = valyu.answer(
"What is the impact of AI on software development?",
structured_output={
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "Brief summary of AI's impact"
},
"key_impacts": {
"type": "array",
"items": {"type": "string"},
"description": "List of key impacts"
},
"benefits": {
"type": "array",
"items": {"type": "string"},
"maxItems": 5
},
"challenges": {
"type": "array",
"items": {"type": "string"},
"maxItems": 5
},
"future_outlook": {
"type": "string",
"description": "Future implications and trends"
}
},
"required": ["summary", "key_impacts", "future_outlook"]
}
)
if response.success and response.data_type == "structured":
structured_answer = response.contents
print("Summary:", structured_answer["summary"])
print("Key impacts:", structured_answer["key_impacts"])
Source Filtering
Get answers from specific, authoritative sources:
response = valyu.answer(
"What are the best practices for React performance optimization?",
search_type="web",
included_sources=[
"react.dev",
"developer.mozilla.org",
"web.dev"
],
system_instructions="Focus on official recommendations and proven techniques"
)
Geographic Filtering
Get location-specific information:
response = valyu.answer(
"What are the current renewable energy policies and incentives?",
country_code="US",
start_date="2024-01-01",
system_instructions="Focus on federal and state-level policies with specific program details"
)
Date Range Filtering
Get answers about recent events or developments:
response = valyu.answer(
"What are the latest breakthroughs in AI model architectures?",
start_date="2024-06-01",
end_date="2024-12-01",
search_type="proprietary",
included_sources=["valyu/valyu-arxiv"],
system_instructions="Focus on novel architectures and their performance improvements"
)
Fast Mode
For time-sensitive applications, enable fast mode for quicker responses:
response = valyu.answer(
"What's the current status of the stock market?",
fast_mode=True
)
Use Case Examples
Financial Analysis
Build an AI-powered financial research assistant that provides comprehensive market analysis:
response = valyu.answer(
"How has Tesla's stock performance compared to other EV companies in 2024?",
search_type="proprietary",
included_sources=["valyu/valyu-stocks"],
structured_output={
"type": "object",
"properties": {
"tesla_performance": {
"type": "object",
"properties": {
"ytd_return": {"type": "string"},
"current_price": {"type": "string"},
"key_events": {
"type": "array",
"items": {"type": "string"}
}
}
},
"competitor_comparison": {
"type": "array",
"items": {
"type": "object",
"properties": {
"company": {"type": "string"},
"ytd_return": {"type": "string"},
"relative_performance": {"type": "string"}
}
}
},
"market_analysis": {"type": "string"}
}
},
system_instructions="Provide detailed financial analysis with specific metrics, key events, and market context. Include percentage changes and dollar values where applicable."
)
if response.success and response.data_type == "structured":
analysis = response.contents
# Display Tesla performance
print("Tesla Performance:")
print(f"YTD Return: {analysis['tesla_performance']['ytd_return']}")
print(f"Current Price: {analysis['tesla_performance']['current_price']}")
# Compare with competitors
print("\nCompetitor Analysis:")
for comp in analysis['competitor_comparison']:
print(f"{comp['company']}: {comp['ytd_return']} ({comp['relative_performance']})")
print(f"\nMarket Analysis: {analysis['market_analysis']}")
Technical Documentation Assistant
Create an AI assistant that provides comprehensive technical guidance with implementation details:
def get_technical_guide(topic: str):
response = valyu.answer(
f"How do I implement {topic} in a Node.js application?",
system_instructions="Provide step-by-step implementation guidance with code examples, security best practices, and common pitfalls to avoid. Structure the response as a comprehensive tutorial.",
included_sources=[
"nodejs.org",
"developer.mozilla.org",
"github.com"
],
structured_output={
"type": "object",
"properties": {
"overview": {
"type": "string",
"description": "Brief overview of the implementation"
},
"prerequisites": {
"type": "array",
"items": {"type": "string"},
"description": "Required dependencies and setup"
},
"implementation_steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"step": {"type": "string"},
"description": {"type": "string"},
"code_example": {"type": "string"}
}
}
},
"security_considerations": {
"type": "array",
"items": {"type": "string"}
},
"common_pitfalls": {
"type": "array",
"items": {"type": "string"}
},
"additional_resources": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["overview", "implementation_steps", "security_considerations"]
}
)
if response.success and response.data_type == "structured":
guide = response.contents
print("=== Technical Implementation Guide ===")
print(f"\nOverview: {guide['overview']}")
print("\nPrerequisites:")
for i, req in enumerate(guide.get('prerequisites', []), 1):
print(f"{i}. {req}")
print("\nImplementation Steps:")
for i, step in enumerate(guide['implementation_steps'], 1):
print(f"\n{i}. {step['step']}")
print(f" {step['description']}")
if step.get('code_example'):
print(f" Code: {step['code_example']}")
return guide
return None
# Usage example
oauth_guide = get_technical_guide("OAuth 2.0 authentication")
Build a decision-making assistant that provides structured comparisons of different options:
def compare_options(topic: str, options: List[str]):
response = valyu.answer(
f"Compare the pros and cons of {', '.join(options)} for {topic}",
system_instructions="Provide a comprehensive comparison with objective analysis. Include specific examples, metrics, and real-world considerations for each option.",
structured_output={
"type": "object",
"properties": {
"comparison_summary": {
"type": "string",
"description": "Brief overview of the comparison"
},
"options": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"pros": {
"type": "array",
"items": {"type": "string"}
},
"cons": {
"type": "array",
"items": {"type": "string"}
},
"best_for": {"type": "string"},
"learning_curve": {"type": "string"},
"market_adoption": {"type": "string"},
"performance_rating": {"type": "string"}
}
}
},
"decision_matrix": {
"type": "object",
"properties": {
"criteria": {
"type": "array",
"items": {"type": "string"}
},
"scores": {
"type": "object",
"description": "Scores for each option on each criteria"
}
}
},
"recommendation": {
"type": "string",
"description": "Final recommendation with reasoning"
}
},
"required": ["comparison_summary", "options", "recommendation"]
}
)
if response.success and response.data_type == "structured":
comparison = response.contents
print("=== Comparative Analysis ===")
print(f"\n{comparison['comparison_summary']}")
print("\n=== Option Analysis ===")
for option in comparison['options']:
print(f"\n{option['name'].upper()}")
print(f"Best for: {option['best_for']}")
print(f"Learning curve: {option['learning_curve']}")
print(f"Market adoption: {option['market_adoption']}")
print("Pros:")
for pro in option['pros']:
print(f" ✓ {pro}")
print("Cons:")
for con in option['cons']:
print(f" ✗ {con}")
print(f"\n=== Final Recommendation ===")
print(comparison['recommendation'])
return comparison
return None
# Usage examples
framework_comparison = compare_options(
"enterprise web applications",
["React", "Vue", "Angular"]
)
database_comparison = compare_options(
"scalable microservices architecture",
["PostgreSQL", "MongoDB", "Cassandra"]
)
Error Handling
response = valyu.answer(query, **options)
if not response.success:
print("Answer generation failed:", response.error)
# Handle specific error cases
if "insufficient credits" in response.error:
print("Please add more credits to your account")
elif "invalid" in response.error:
print("Check your query and options")
return
# Process successful response
print(f"Transaction ID: {response.tx_id}")
print(f"Data type: {response.data_type}")
print(f"Sources processed: {response.search_metadata.number_of_results}")
print(f"Answer: {response.contents}")
Best Practices
Improve Answer Quality
response = valyu.answer(
query,
system_instructions="Provide detailed, evidence-based answers with specific examples",
search_type="proprietary", # Use high-quality academic/professional sources
included_sources=["authoritative-domain.com"],
start_date="2024-01-01" # Focus on recent information
)
Handle Structured Responses
response = valyu.answer(query, structured_output=schema)
if response.success:
if response.data_type == "structured":
structured_data = response.contents # Dict[str, Any]
# Process structured data
else:
text_answer = response.contents # str
# Process text answer