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.

Basic Usage

from valyu import Valyu

valyu = Valyu()

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)

Parameters

Query (Required)

ParameterTypeDescription
querystrThe question or query to answer

Options (Optional)

ParameterTypeDescriptionDefault
structured_outputdictJSON schema for structured response formatNone
system_instructionsstrCustom instructions for AI processing (max 2000 characters)None
search_type"web" | "proprietary" | "all"Type of search to perform before generating answer"all"
data_max_pricefloatMaximum cost in USD for data retrieval (search costs only)30.0
country_codestr2-letter ISO country code to bias search resultsNone
included_sourcesList[str]List of specific sources to search withinNone
excluded_sourcesList[str]List of sources to exclude from searchNone
start_datestrStart date for time filtering (YYYY-MM-DD format)None
end_datestrEnd date for time filtering (YYYY-MM-DD format)None
fast_modeboolEnable fast mode for reduced latencyFalse

Response Format

# Union type - either success or error response
AnswerResponse = Union[AnswerSuccessResponse, AnswerErrorResponse]

class AnswerSuccessResponse:
    success: bool = True
    ai_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-US"],
    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")

Comparative Analysis Tool

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"AI Transaction ID: {response.ai_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