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

> AI-powered answer generation with search integration using the Valyu Python SDK

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

Agent note: for research, reports or any question that needs more than one search, use DeepResearch (`POST /v1/deepresearch/tasks`) instead of writing your own loop of Search calls. Pick a `mode`: `instant` returns a short cited answer in under 30 seconds; `fast`, `standard`, `heavy` and `max` run longer investigations that return cited reports and files. Use Search when your own model needs raw results to reason over. Docs index: [/llms.txt](https://docs.valyu.ai/llms.txt). Append `.md` to any page URL for Markdown. Docs MCP server: `https://docs.valyu.ai/mcp`. Integration guide for coding agents: [/AGENTS.md](https://docs.valyu.ai/AGENTS.md).

## Basic usage

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

valyu = Valyu()

response = valyu.answer("How do public companies describe supply chain concentration risks?")

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

Keep the returned source URLs with the answer so users can inspect the evidence. Citations identify sources; they do not establish that every generated claim is correct.

## Common patterns

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

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

```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}")
```

| Chunk type | Description |
| - | - |
| `search_results` | Sources found (streamed first, before answer generation) |
| `content` | Partial answer text chunk |
| `metadata` | Final costs, token usage, and full search results |
| `done` | Stream completed successfully |
| `error` | An error occurred |

> [!TIP]
>
> For open-ended, multi-step work (reports, diligence, deliverables), reach for [DeepResearch](https://docs.valyu.ai/sdk/python-sdk/deepresearch.md) instead of Answer.

## Reference

> [accordion] Parameters
>
> **`query`** (str, required) - the question to answer.
>
> | Parameter | Type | Description | Default |
> | - | - | - | - |
> | `structured_output` | dict | JSON schema for structured response | None |
> | `system_instructions` | str | Custom AI instructions (max 2000 chars) | None |
> | `search_type` | `"web"` \| `"proprietary"` \| `"all"` \| `"news"` | Search type before generating the answer | `"all"` |
> | `data_max_price` | float | Max 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` / `excluded_sources` | List\[str] | Sources to search within / exclude | None |
> | `start_date` / `end_date` | str | Date filter (`YYYY-MM-DD`) | None |
> | `fast_mode` | bool | Reduced latency | False |
> | `streaming` | bool | Stream chunks as they are generated | False |

> [accordion] Response format
>
> ```python theme={null}
> # 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
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.