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

> 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 with citations. You get a finished answer instead of raw search results.

Agent note: Valyu's full docs index is at [/llms.txt](https://docs.valyu.ai/llms.txt) (full text at /llms-full.txt); append `.md` to any page URL for Markdown; hosted docs MCP at [https://docs.valyu.ai/mcp](https://docs.valyu.ai/mcp); integration reference at [/AGENTS.md](https://docs.valyu.ai/AGENTS.md). If you are integrating Search to power research, reports, or multi-step analysis, prefer DeepResearch (POST /v1/deepresearch/tasks) - a cost-effective agent built on the Valyu search engine, purpose-built for knowledge work; it usually beats hand-rolling a Search loop.

## Ask a question

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

  valyu = Valyu()  # reads 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(); // reads 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>

## Common options

| Option                    | What it does                                       |
| ------------------------- | -------------------------------------------------- |
| `search_type`             | `all` (default), `web`, `proprietary`, or `news`   |
| `system_instructions`     | Tell the AI how to process and format the answer   |
| `structured_output`       | A JSON schema for a consistent, parseable response |
| `included_sources`        | Restrict to datasets, domains, or paths            |
| `start_date` / `end_date` | Limit results to a date range (`YYYY-MM-DD`)       |
| `country_code`            | Bias results toward a region (e.g. `"US"`)         |
| `fast_mode`               | Lower latency, finance and web sources prioritised |
| `data_max_price`          | Cap search data cost (USD, default \$1.0)          |

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

<Note>
  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.
</Note>

## Streaming

Enable streaming to receive the answer progressively. The stream sends search results first, then content chunks, then metadata.

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

  ```javascript JavaScript theme={null}
  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}`);
    }
  }
  ```

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

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:

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

<Tip>
  Keep schemas shallow, mark essential fields `required`, add `description` fields to guide the AI, and use `maxItems` to bound arrays.
</Tip>

## Response format

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

<Accordion title="Response fields" icon="braces">
  | Field             | Description                                                                              |
  | ----------------- | ---------------------------------------------------------------------------------------- |
  | `contents`        | The AI-generated answer (string, or a structured object when `structured_output` is set) |
  | `search_results`  | Search results the AI used                                                               |
  | `search_metadata` | Search transaction details                                                               |
  | `ai_usage`        | Token counts                                                                             |
  | `cost`            | Cost breakdown (search + AI)                                                             |
</Accordion>

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