> ## 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.

# Answer Endpoint Guide

> Get AI-powered answers with real-time search

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

## What You Can Do

* **Get AI-generated answers** - Not just search results, but actual responses
* **Access real-time data** - Information from web and proprietary sources
* **Get structured outputs** - Define a JSON schema for consistent, parseable responses
* **Control sources** - Include or exclude specific domains and datasets

## Features

<CardGroup cols={2}>
  <Card title="AI-Enhanced Search" icon="brain">
    Search results processed by AI into coherent answers.
  </Card>

  <Card title="Fast Mode" icon="bolt">
    Lower latency with finance and web sources prioritised.
  </Card>

  <Card title="Structured Responses" icon="code">
    Define JSON schemas for consistent output formats.
  </Card>

  <Card title="Source Filtering" icon="filter">
    Include or exclude specific domains, URLs, and datasets.
  </Card>

  <Card title="Date Filtering" icon="calendar-days">
    Filter search results by date range.
  </Card>
</CardGroup>

## Getting Started

### Basic Query

Ask a question and get an AI-generated answer:

<CodeGroup>
  ```python Python theme={null}
  from valyu import Valyu

  valyu = Valyu() # Uses VALYU_API_KEY from env

  data = valyu.answer(
      query="latest developments in quantum computing",
  )
  print(data["contents"])

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

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

  const data = await valyu.answer({
    query: "latest developments in quantum computing",
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  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"
    }'
  ```
</CodeGroup>

### Fast Mode

Use fast mode for quicker responses. Good for general queries:

<CodeGroup>
  ```python Python theme={null}
  from valyu import Valyu

  valyu = Valyu()

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

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  const data = await valyu.answer({
    query: "current market trends in tech stocks",
    fastMode: true,
    dataMaxPrice: 30.0
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.valyu.ai/v1/answer \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "query": "current market trends in tech stocks",
      "fast_mode": true,
      "data_max_price": 30.0
    }'
  ```
</CodeGroup>

### Search Types

| **Type**      | **What it searches**                  | **Use for**                    |
| ------------- | ------------------------------------- | ------------------------------ |
| `all`         | Web and proprietary sources (default) | Comprehensive coverage         |
| `web`         | Web only                              | Current events, general topics |
| `proprietary` | Academic, financial, premium sources  | Research, technical analysis   |
| `news`        | News articles only                    | Recent news and current events |

### Custom Instructions

Tell the AI how to process and format the answer:

<CodeGroup>
  ```python Python theme={null}
  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"])

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  const data = await valyu.answer({
    query: "climate change research",
    systemInstructions: "Focus on practical applications and commercial impact. Summarise key findings as bullet points.",
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.valyu.ai/v1/answer \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "query": "climate change research",
      "system_instructions": "Focus on practical applications and commercial impact. Summarise key findings as bullet points.",
      "data_max_price": 40.0
    }'
  ```
</CodeGroup>

## Streaming

Enable streaming to receive the answer progressively as it's generated. The stream sends search results first, then content chunks, then metadata.

<CodeGroup>
  ```python Python theme={null}
  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":
          if chunk.content:
              print(chunk.content, end="", flush=True)
      elif chunk.type == "metadata":
          print(f"\nCost: ${chunk.cost.total_deduction_dollars:.4f}")
      elif chunk.type == "done":
          print("\n[Complete]")
      elif chunk.type == "error":
          print(f"Error: {chunk.error}")
  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  // Streaming mode - returns async generator
  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") {
      if (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 === "done") {
      console.log("\n[Complete]");
    } else if (chunk.type === "error") {
      console.error(`Error: ${chunk.error}`);
    }
  }
  ```

  ```bash cURL theme={null}
  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
    }'
  ```
</CodeGroup>

### 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                                               |

## Advanced Features

### Source Filtering

Choose which sources to include or exclude:

<CodeGroup>
  ```python Python theme={null}
  from valyu import Valyu

  valyu = Valyu()

  data = valyu.answer(
      query="artificial intelligence research trends",
      included_sources=[
          "valyu/valyu-arxiv",
          "valyu/valyu-pubmed",
          "valyu/valyu-biorxiv",
      ]
  )
  print(data["contents"])

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  const data = await valyu.answer({
    query: "artificial intelligence research trends",
    includedSources: [
      "valyu/valyu-arxiv",
      "valyu/valyu-pubmed",
      "valyu/valyu-biorxiv",
    ]
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.valyu.ai/v1/answer \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "query": "artificial intelligence research trends",
      "included_sources": [
        "valyu/valyu-arxiv",
        "valyu/valyu-pubmed",
        "valyu/valyu-biorxiv"
      ]
    }'
  ```
</CodeGroup>

**How to specify sources:**

* **Domains**: `"example.com"` includes/excludes the whole domain
* **Paths**: `"https://example.com/blog"` targets a specific section
* **Datasets**: `"valyu/valyu-arxiv"` uses Valyu's proprietary datasets

### Structured Output

Get responses in a specific JSON format:

<CodeGroup>
  ```python Python theme={null}
  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"])

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  const data = await valyu.answer({
    query: "top tech companies financial performance 2024",
    structuredOutput: {
      "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"]
    },
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.valyu.ai/v1/answer \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "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"]
      }
    }'
  ```
</CodeGroup>

### Date Filtering

Limit results to specific time periods:

<CodeGroup>
  ```python Python theme={null}
  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"])

  ```

  ```javascript JavaScript theme={null}
  import { Valyu } from "valyu-js";

  const valyu = new Valyu();

  const data = await valyu.answer({
    query: "cryptocurrency market analysis",
    startDate: "2024-01-01",
    endDate: "2024-12-31",
    countryCode: "US",
  });
  console.log(data.contents);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.valyu.ai/v1/answer \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "query": "cryptocurrency market analysis",
      "start_date": "2024-01-01",
      "end_date": "2024-12-31",
      "country_code": "US"
    }'
  ```
</CodeGroup>

## Response Format

### Text Response (Default)

```json theme={null}
{
  "success": true,
  "tx_id": "tx_12345678-1234-1234-1234-123456789abc",
  "data_type": "unstructured",
  "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 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 theme={null}
{
  "success": true,
  "tx_id": "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.",
    "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
  }
}
```

### Response Fields

| **Field**         | **Description**                                  |
| ----------------- | ------------------------------------------------ |
| `contents`        | The AI-generated answer (text or JSON object)    |
| `data_type`       | `"unstructured"` (text) or `"structured"` (JSON) |
| `search_results`  | Search results the AI used                       |
| `search_metadata` | Search transaction details                       |
| `ai_usage`        | Token counts                                     |
| `cost`            | Cost breakdown (search + AI)                     |

## Examples

### Research Assistant

```json theme={null}
{
  "query": "machine learning interpretability methods 2024",
  "system_instructions": "Provide a technical overview of recent 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

```json theme={null}
{
  "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
}
```

### Technical Docs

```json theme={null}
{
  "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. Include code examples.",
  "data_max_price": 20.0
}
```

### News

```json theme={null}
{
  "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 impact on tech companies.",
  "data_max_price": 25.0
}
```

## Best Practices

### Writing Queries

1. **Be specific** - Detailed queries get better results
2. **Set price limits** - Balance cost with quality
3. **Filter sources** - Focus on authoritative sources for your domain
4. **Use custom instructions** - Guide the AI for your use case

### Designing Schemas

1. **Keep it simple** - Avoid deeply nested structures
2. **Mark required fields** - Ensure you get essential data
3. **Add descriptions** - Help the AI understand what you want
4. **Limit arrays** - Use `maxItems` to control length

### Managing Costs

1. **Track both costs** - Search and AI are billed separately
2. **Set `data_max_price`** - Control search data costs
3. **Filter sources** - Exclude irrelevant ones
4. **Use date filters** - Narrow the search scope

### Error Handling

```python theme={null}
from valyu import Valyu

valyu = Valyu()

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

<Card title="Try the Answer API" icon="rocket" href="/api-reference/endpoint/answer">
  Full API reference with interactive examples
</Card>

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/endpoint/answer">
    Complete parameter documentation
  </Card>

  <Card title="Python SDK" icon="python" href="/sdk/python-sdk">
    Python integration
  </Card>

  <Card title="TypeScript SDK" icon="js" href="/sdk/typescript-sdk">
    TypeScript integration
  </Card>

  <Card title="Integrations" icon="plug" href="/integrations/langchain">
    LangChain, LlamaIndex, and more
  </Card>
</CardGroup>
