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

# Python SDK

> Install the Valyu Python SDK (pip install valyu), authenticate and call Search, Contents and DeepResearch from Python. Free monthly credits, no card with a work email.

The Valyu Python SDK gives you search, content extraction and DeepResearch through one API.

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

## Install

```bash theme={null}
pip install valyu
```

## Authenticate

Get your API key from the [Valyu Platform](https://platform.valyu.ai). Accounts get 2,000 free credits a month with a work email (1,000 with a personal email; add a card after your first month to keep them coming). The SDK reads `VALYU_API_KEY` from the environment automatically:

```bash theme={null}
export VALYU_API_KEY="your-api-key-here"
```

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

valyu = Valyu()                    # reads VALYU_API_KEY
valyu = Valyu("your-api-key-here") # or pass it directly
```

## First call

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

valyu = Valyu()

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

if not response.success:
    raise RuntimeError(response.error)

for result in response.results:
    print(result.title, "-", result.url)
```

Check `success` before reading Search results. Other methods have endpoint-specific response types; streaming methods return chunks, and wait helpers may raise errors.

## APIs

> [card] [Search](https://docs.valyu.ai/sdk/python-sdk/search.md)
>
> Search web and specialist sources

> [card] [Contents](https://docs.valyu.ai/sdk/python-sdk/contents.md)
>
> Extract and process web content

> [card] [DeepResearch](https://docs.valyu.ai/sdk/python-sdk/deepresearch.md)
>
> Autonomous async research reports

For source discovery, see [Datasources](https://docs.valyu.ai/sdk/python-sdk/datasources.md). For research workflows, see [batch tasks](https://docs.valyu.ai/sdk/python-sdk/deepresearch-batch.md) and [review checkpoints](https://docs.valyu.ai/sdk/python-sdk/deepresearch-hitl.md).

> [!TIP]
>
> For multi-step synthesis or cited reports, reach for [DeepResearch](https://docs.valyu.ai/sdk/python-sdk/deepresearch.md). Use Search when your application should own query planning and synthesis.

## Async client

`AsyncValyu` is the `async`/`await` counterpart to `Valyu`: same arguments, same response objects, same validation. Every method is a coroutine you `await`. Reach for it when a single request fans out several Valyu calls (research agents, multi-source lookups) or runs inside an async web service. For one-off scripts and notebooks, the synchronous client is simpler.

```python theme={null}
import asyncio
from valyu import AsyncValyu

async def main():
    async with AsyncValyu() as valyu:
        responses = await asyncio.gather(
            valyu.search("DCF terminal value assumptions"),
            valyu.search("GARCH volatility forecasting"),
        )
        for r in responses:
            print(r.query, len(r.results))

asyncio.run(main())
```

> [accordion] Bounded fan-out and streaming results
>
> Cap how many requests are in flight with a semaphore (keep it aligned with `max_connections`):
>
> ```python theme={null}
> import asyncio
> from valyu import AsyncValyu
>
> queries = [...]  # hundreds of queries
>
> async def search_one(valyu, sem, query):
>     async with sem:
>         return await valyu.search(query, max_num_results=10)
>
> async def main():
>     async with AsyncValyu(max_connections=20) as valyu:
>         sem = asyncio.Semaphore(20)
>         await asyncio.gather(*[search_one(valyu, sem, q) for q in queries])
>
> asyncio.run(main())
> ```
>
> Use `asyncio.as_completed` to process each result the moment it's ready instead of waiting for the whole batch.

> [accordion] FastAPI lifecycle
>
> Instantiate the client once at startup and share it - don't create a fresh `AsyncValyu` per request, or you throw away the connection pool every time.
>
> ```python theme={null}
> from contextlib import asynccontextmanager
> from fastapi import FastAPI
> from valyu import AsyncValyu
>
> @asynccontextmanager
> async def lifespan(app: FastAPI):
>     app.state.valyu = AsyncValyu()
>     try:
>         yield
>     finally:
>         await app.state.valyu.aclose()
>
> app = FastAPI(lifespan=lifespan)
>
> @app.get("/search")
> async def search(q: str):
>     response = await app.state.valyu.search(q)
>     return {"results": [r.model_dump() for r in response.results]}
> ```
>
> Prefer `async with` for scripts so the pool is released deterministically. For long-lived services, call `aclose()` on shutdown (it's idempotent).

> [accordion] Constructor options
>
> | Parameter | Type | Description | Default |
> | - | - | - | - |
> | `api_key` | `Optional[str]` | API key. Falls back to `VALYU_API_KEY`. | `None` |
> | `base_url` | `str` | Base URL of the Valyu API. | `https://api.valyu.ai/v1` |
> | `max_connections` | `int` | Max simultaneous HTTP connections. Match it to your expected peak concurrency. | `100` |
> | `max_keepalive_connections` | `Optional[int]` | Idle connections kept warm for reuse. | `max(20, max_connections // 5)` |
> | `timeout` | `float` | Per-request timeout in seconds. | `600.0` |
> | `http_client` | `Optional[httpx.AsyncClient]` | Pre-configured client to use instead of the default. Ownership stays with the caller. | `None` |

> [!NOTE]
>
> `AsyncValyu` currently exposes `search`, `contents`, `get_contents_job`, and `wait_for_contents_job`. Use the synchronous `Valyu` client for `deepresearch` and `datasources`.

## Support

* **Discord**: [Join our community](https://discord.gg/umtmSsppRY)
* **GitHub**: [valyuAI/valyu-py](https://github.com/valyuAI/valyu-py)
* **Email**: [contact@valyu.ai](mailto:contact@valyu.ai)


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