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

# Extract content from URLs

> Extract clean text, summaries or JSON fields from any URL with the Valyu Contents API. Batch up to 50 URLs, run async jobs and pay only for pages that succeed.

Already have a URL? Contents returns its readable text, an optional summary or fields extracted into JSON. Use [Search](https://docs.valyu.ai/search/quickstart.md) first when you need to find the pages. You only pay for URLs that succeed.

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

## Extract a page

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

valyu = Valyu()  # reads VALYU_API_KEY from env

data = valyu.contents(
    urls=["https://en.wikipedia.org/wiki/Artificial_intelligence"],
    response_length="medium",
    extract_effort="auto",
)
for result in data.results:
    if result.status == "success":
        print(str(result.content)[:500])
    else:
        print(result.url, result.error)
```

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

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

const data = await valyu.contents(["https://en.wikipedia.org/wiki/Artificial_intelligence"], {
  responseLength: "medium",
  extractEffort: "auto",
});
if ("results" in data) {
  for (const result of data.results) {
    console.log(result.url, result.status === "success" ? result.content : result.error);
  }
}
```

```bash cURL theme={null}
curl -X POST https://api.valyu.ai/v1/contents \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "urls": ["https://en.wikipedia.org/wiki/Artificial_intelligence"],
    "response_length": "medium",
    "extract_effort": "auto"
  }'
```

Returns clean markdown for each URL. Pass up to 10 URLs synchronously, or up to 50 with [async mode](#async-processing).

## Core options

| Option | Values | Default |
| - | - | - |
| `response_length` | `short` (25k), `medium` (50k), `large` (100k), `max`, or a char count (1k-1M) | `short` |
| `extract_effort` | `normal` (HTTP extraction), `high` (browser rendering), `auto` | `auto` |
| `summary` | `false`, `true`, an instruction string, or a JSON schema | `false` |
| `screenshot` | `true` to capture a page screenshot (not for PDFs) | `false` |
| `include_image_links` | `false` to replace each image with its alt text. See [remove image links](#remove-image-links) | `true` |
| `max_age` | Oldest cached copy of a page, in seconds. `0` forces a live crawl. See [control caching](#control-caching) | Not set |

## Remove image links

Image URLs add many tokens to your context. They add little value for an LLM. The alt text keeps product names, specifications and captions.

Set `include_image_links` to `false` to remove image URLs from the content. Each image becomes `[Image: alt text]`. The API removes an image with no alt text. A linked image `[![alt](src)](href)` becomes `[[Image: alt]](href)`. Other links do not change. The default is `true`, which keeps image markdown such as `![Product photo](https://example.com/p.jpg)`.

```python Python theme={null}
response = valyu.contents(
    ["https://example.com/products/keyboard"],
    include_image_links=False,
)
```

```typescript TypeScript theme={null}
const response = await valyu.contents(
  ["https://example.com/products/keyboard"],
  { includeImageLinks: false }
);
```

```bash cURL theme={null}
curl -X POST https://api.valyu.ai/v1/contents \
  -H "x-api-key: $VALYU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "urls": ["https://example.com/products/keyboard"],
    "include_image_links": false
  }'
```

In the returned content, `![Product photo](https://example.com/p.jpg)` becomes `[Image: Product photo]`.

The same parameter works on [Search](https://docs.valyu.ai/search/tips-and-tricks.md#remove-image-links-to-save-tokens).

## Control caching

Valyu keeps a copy of each page it crawls. By default, Contents can return a copy up to 7 days old. If the copy is older than 30 minutes, Contents returns it and refreshes the page in the background.

Set `max_age` to the oldest copy, in seconds, that you accept.

| `max_age` | Result |
| - | - |
| Not set | Default policy: a copy up to 7 days old, with a background refresh |
| `0` | A live crawl. No cached copy is used |
| `3600` | A copy at most 1 hour old. If there is none, Valyu crawls the page |

Use an integer from `0` to `2592000` (30 days). Any other value returns `400`. Do not use `max_age` with `historical_cache`. It also works with `async: true`: each page in the job follows the same rule. A fresh crawl costs the same as a cached copy.

```python Python theme={null}
response = valyu.contents(["https://example.com/news"], max_age=0)
```

```typescript TypeScript theme={null}
const response = await valyu.contents(["https://example.com/news"], { maxAge: 0 });
```

```bash cURL theme={null}
curl -X POST https://api.valyu.ai/v1/contents \
  -H "x-api-key: $VALYU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "urls": ["https://example.com/news"],
    "max_age": 0
  }'
```

Each successful result has two fields that show how the page was served:

| Field | Values |
| - | - |
| `cache_state` | `miss`: Valyu crawled the page for this request. `hit`: a cached copy that was fresh for you. `stale`: a cached copy older than 30 minutes, returned while Valyu refreshes it. This happens only when `max_age` is not set. |
| `crawled_at` | The time the page copy was captured, in ISO 8601. `null` when there is no page copy to date, for example an academic paper served from the processed index. These papers return `cache_state: "hit"`. |

## Pages that answer 404

Some sites answer 404 but still send the real page. When the 404 body has the real content (at least 400 characters, with no not-found or sign-in wording), Contents returns it as a success. The result has `status: "success"` and `http_status: 404`. It is charged like any other success. A not-found template page still returns `status: "not_found"` and is not charged. The rule is the same for sync and async requests.

## Pages that redirect

When a URL redirects to a different page, the result has `final_url`, the page that Contents read. For example, a closed job posting can redirect to the careers page, and the `content` is then the careers page. Compare `final_url` with `url` before you use the content. `final_url` is not set when there was no redirect. A change of scheme, host case, `www.`, trailing slash or `#fragment` is not a different page.

## Point-in-time content

To read a page as it was at a past date, set `start_date` / `end_date` with `historical_cache: true` (Python `start_date`, `end_date`, `historical_cache`; TypeScript `startDate`, `endDate`, `historicalCache`). Dates accept `YYYY`, `YYYY-MM-DD` or an ISO-8601 datetime. Contents then serves only a snapshot captured inside the window: with `historical_cache` on, Contents always behaves as `historical_cache_strict: "only"`, whatever value you pass, and never falls back to a live crawl. A URL with no snapshot in the window fails rather than returning newer content.

```python theme={null}
response = valyu.contents(
    ["https://example.com/pricing"],
    end_date="2025-06-30",
    historical_cache=True,
)
```

## Academic papers

When you pass an academic paper URL or DOI, Valyu serves it from our **pre-processed academic index** rather than crawling the live page. You get clean markdown with preserved **figures**, **equations**, tables, and section structure, plus inline pre-signed image URLs - the things lost when a JavaScript-heavy or PDF paper is scraped live. This happens automatically; just pass the URL.

| Source | Example URL / id | Plan for index access |
| - | - | - |
| arXiv | `https://arxiv.org/pdf/2506.05440` (or `/abs/`, `/html/`) | tier\_0 (pay-as-you-go) |
| PubMed Central | `https://pmc.ncbi.nlm.nih.gov/articles/PMC10584482/` | tier\_0 |
| bioRxiv | `https://www.biorxiv.org/content/10.1101/2020.07.28.225581` | tier\_1 |
| medRxiv | `https://www.medrxiv.org/content/10.1101/...` | tier\_1 |
| ChemRxiv | `https://chemrxiv.org/doi/full/10.26434/chemrxiv-...` | tier\_2 |

If your plan covers the source, you get the processed markdown; if the specific paper isn't indexed yet, it falls back to live extraction. If your plan doesn't cover the source, the URL is live-crawled when the page is publicly accessible; extraction can still fail.

> [!NOTE]
>
> Academic results set `source` to the dataset id (e.g. `valyu/valyu-arxiv`) and include `doi`, `authors`, and `citation_count`. Figures are returned in `image_url` as a filename→URL map and referenced inline in the markdown.

## AI summaries and structured extraction

The `summary` field controls AI post-processing:

* **`false`** - raw markdown, fastest and cheapest (no AI)
* **`true`** - a basic AI summary
* **string** - custom instructions, e.g. `"Summarise the methodology and key findings in 2-3 paragraphs"`
* **object** - a JSON schema for structured extraction

```python theme={null}
# Structured extraction
data = valyu.contents(
    urls=["https://example.com/product-page"],
    summary={
        "type": "object",
        "properties": {
            "product_name": {"type": "string"},
            "price": {"type": "number", "description": "Price in USD"},
            "availability": {
                "type": "string",
                "enum": ["in_stock", "out_of_stock", "preorder"],
            },
        },
        "required": ["product_name", "price"],
    },
)
print(data.results[0].content)  # returns a JSON object
```

> [accordion] Summary examples (all four modes)
>
> ```python Python theme={null}
> # false - raw markdown, no AI
> valyu.contents(urls=["https://example.com/article"], summary=False)
>
> # true - basic AI summary
> valyu.contents(urls=["https://example.com/article"], summary=True)
>
> # string - custom instructions
> valyu.contents(
>     urls=["https://example.com/research-paper"],
>     summary="Summarise the methodology, key findings, and applications in 2-3 paragraphs",
> )
>
> # object - JSON schema extraction
> valyu.contents(
>     urls=["https://example.com/product-page"],
>     summary={
>         "type": "object",
>         "properties": {
>             "product_name": {"type": "string"},
>             "price": {"type": "number"},
>             "features": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
>         },
>         "required": ["product_name", "price"],
>     },
> )
> ```
>
> ```javascript JavaScript theme={null}
> // false - raw markdown, no AI
> await valyu.contents(["https://example.com/article"], { summary: false });
>
> // true - basic AI summary
> await valyu.contents(["https://example.com/article"], { summary: true });
>
> // string - custom instructions
> await valyu.contents(["https://example.com/research-paper"], {
>   summary: "Summarise the methodology, key findings, and applications in 2-3 paragraphs",
> });
>
> // object - JSON schema extraction
> await valyu.contents(["https://example.com/product-page"], {
>   summary: {
>     type: "object",
>     properties: {
>       product_name: { type: "string" },
>       price: { type: "number" },
>       features: { type: "array", items: { type: "string" }, maxItems: 5 },
>     },
>     required: ["product_name", "price"],
>   },
> });
> ```

> [accordion] How Valyu checks AI results
>
> For a JSON schema, Valyu checks each reply against your schema. If the reply does not match, Valyu asks once for a corrected reply. If the corrected reply still does not match, you get the data as extracted, so check the fields that you need. If Valyu cannot get usable JSON, the result has `summary_success: false` and `data_type: "unstructured"`.
>
> The AI step for one page has a time limit. If the limit passes before a usable reply, the result has `summary_success: false` and the page content is still in `content`. Always read `summary_success` before you use `summary`.

> [accordion] JSON schema reference and tips
>
> Use any valid [JSON Schema](https://json-schema.org/understanding-json-schema/reference/type). Limits: **5,000 characters**, **3 levels deep**, **20 properties per object**.
>
> Supported types: `string`, `number`/`integer`, `boolean`, `array`, `object`.
>
> Tips:
>
> * Use clear `description` fields to guide extraction.
> * Use `enum` for consistent categorisation.
> * Keep schemas shallow and mark essential fields `required`.

> [accordion] Screenshot capture
>
> ```python Python theme={null}
> data = valyu.contents(
>     urls=["https://example.com/article"],
>     extract_effort="auto",
>     screenshot=True,
> )
> print(data.results[0].screenshot_url)
> ```
>
> Screenshots are captured during page rendering and returned as pre-signed URLs. PDF files do not support screenshots.

## Async processing

For 11-50 URLs (required above 10) or non-blocking workflows, use async mode. Submit URLs, get a `job_id` immediately, then poll or receive results via webhook. Async also raises the per-URL timeout to 120s (vs 25s for sync).

```python theme={null}
job = valyu.contents(
    urls=["https://example.com/page1", "https://example.com/page2"],  # up to 50
    async_mode=True,
    webhook_url="https://your-app.com/webhooks/valyu",  # optional
)
print(job.job_id)

# Block until complete (SDK handles polling)
result = valyu.wait_for_contents_job(job.job_id, poll_interval=5, max_wait_time=3600)
for r in result.results or []:
    if r.status == "success":
        print(r.title, r.length)
    else:
        print(r.url, r.error)
print(f"Total cost: {result.actual_cost_dollars}")
```

> [!NOTE]
>
> Async mode is **required** above 10 URLs. For 1-10 URLs it's optional, for non-blocking workflows.

> [accordion] Polling, job lifecycle, and status fields
>
> The initial submit returns HTTP 202 with a `job_id`, `poll_url`, and a one-time `webhook_secret` (store it immediately - you cannot retrieve it later).
>
> Jobs move through these statuses:
>
> | Status | Meaning |
> | - | - |
> | `pending` | Created, not yet started |
> | `processing` | URLs running in batches of 5 |
> | `completed` | All URLs succeeded |
> | `partial` | Finished with some failures |
> | `failed` | All URLs failed. The poll response still lists every URL in `results` |
>
> To poll manually:
>
> ```python Python theme={null}
> import time
>
> while True:
>     status = valyu.get_contents_job(job.job_id)
>     if status.status in ("completed", "partial", "failed"):
>         break
>     time.sleep(2)
>
> if status.status in ("completed", "partial", "failed"):
>     for result in status.results or []:
>         if result.status == "success":
>             print(result.title, result.length)
>         else:
>             print(result.url, result.error)
> ```
>
> ```javascript JavaScript theme={null}
> let status;
> do {
>   status = await valyu.getContentsJob(job.job_id);
>   if (!["completed", "partial", "failed"].includes(status.status)) {
>     await new Promise((r) => setTimeout(r, 2000));
>   }
> } while (!["completed", "partial", "failed"].includes(status.status));
> ```
>
> A not-found page (a 404 with no real content) is a result with `status: "not_found"` and `error: "Page not found (404)"`. It is in `results` like any other URL, it counts in `urls_failed`, and it is not charged. A 404 page with real content is a success. See [pages that answer 404](#pages-that-answer-404).
>
> A URL that fails with a retryable error gets one automatic retry, and you are billed once. A `failed` job has the same shape: every URL has a row with its `error`, and `actual_cost_dollars` is `0`. The job-level `error` can be empty when every failure is per-URL, so read the `error` of each result.
>
> If the results of a job are very large (more than about 6 MB in total), the poll response cannot carry them. Use a webhook for such jobs.
>
> Status response fields include: `job_id`, `status`, `urls_total`, `urls_processed`, `urls_failed`, `created_at`, `updated_at`, `current_batch` / `total_batches` (while `processing`), `results` and `actual_cost_dollars` (when the job is finished: `completed`, `partial` or `failed`), and `error` (when `partial`/`failed`).

> [accordion] Webhooks and signature verification
>
> When you provide a `webhook_url`, Valyu POSTs to it when the job finishes (completed, partial, or failed). Headers: `Content-Type: application/json`, `User-Agent: Valyu-Contents/1.0`, `X-Webhook-Signature: sha256={hex}`, `X-Webhook-Timestamp` (Unix seconds).
>
> Retries: up to 5 attempts with exponential backoff (1s, 2s, 4s, 8s), no retry on 4xx, 5s connect / 15s read timeout.
>
> Valyu can send the webhook for a job more than once. If a delivery is not confirmed, Valyu sends it again, up to 3 times for each job. Use `job_id` to ignore a copy that you already processed.
>
> The payload is signed with HMAC-SHA256 over `"{timestamp}.{json_payload}"`. Verify the original request body before parsing or reserializing JSON. This example checks the signature; also check the timestamp against your accepted replay window and deduplicate processing by job ID:
>
> ```python Python theme={null}
> import hmac, hashlib
>
> def verify_webhook(payload: bytes, signature_header: str, timestamp_header: str, webhook_secret: str) -> bool:
>     signed = f"{timestamp_header}.{payload.decode('utf-8')}"
>     expected = hmac.new(webhook_secret.encode(), signed.encode(), hashlib.sha256).hexdigest()
>     return hmac.compare_digest(expected, signature_header.removeprefix("sha256="))
> ```
>
> ```javascript JavaScript theme={null}
> import crypto from "crypto";
>
> function verifyWebhook(payload, signatureHeader, timestampHeader, webhookSecret) {
>   const signed = `${timestampHeader}.${payload}`;
>   const expected = crypto.createHmac("sha256", webhookSecret).update(signed).digest("hex");
>   const received = signatureHeader.replace("sha256=", "");
>   const expectedBytes = Buffer.from(expected);
>   const receivedBytes = Buffer.from(received);
>   return expectedBytes.length === receivedBytes.length &&
>     crypto.timingSafeEqual(expectedBytes, receivedBytes);
> }
> ```
>
> > [!TIP]
> >
> > The TypeScript SDK exports `verifyContentsWebhookSignature()` which handles this for you.

## Limits and pricing

| Detail | Value |
| - | - |
| Max URLs (sync / async) | 10 / 50 |
| Batch size | 5 URLs |
| Timeout per URL (sync / async) | 25s / 120s |
| Base pricing | 0.2 credits per successfully extracted URL |
| AI features (summary/schema) | 0.6 credits per URL in total (0.2 base + 0.4 AI), same for both |
| Job expiry (TTL) | 7 days |

Failed and blocked URLs are free. If the AI step fails for a URL, you pay only the 0.2 credits for extraction. For example, 8 successful URLs use 1.6 credits, or 4.8 with `summary` set. `total_cost_dollars` (sync) and `actual_cost_dollars` (async) are the amounts charged. Each result's `price` is the base extraction price only and excludes the AI processing charge.

`max_price_dollars` caps the charge for a request. If the worst case exceeds it, the request is rejected with `400` before any work starts; if the actual cost exceeds it, you get `402`.

## Response format

Illustrative response:

```json theme={null}
{
  "success": true,
  "tx_id": "tx_12345678-1234-1234-1234-123456789abc",
  "results": [
    {
      "status": "success",
      "title": "AI Breakthrough in Natural Language Processing",
      "url": "https://example.com/article?utm_source=valyu",
      "content": "# AI Breakthrough...\n\nPage content in markdown...",
      "source": "web",
      "price": 0.00125,
      "length": 12840,
      "data_type": "unstructured"
    }
  ],
  "urls_requested": 1,
  "urls_processed": 1,
  "urls_failed": 0,
  "total_cost_dollars": 0.00125,
  "total_characters": 12840
}
```

With `summary` set, `content` is the AI summary (string) or extracted JSON (object), and each result adds `summary_success`.

> [accordion] Result fields
>
> | Field | Description |
> | - | - |
> | `status` | `"success"`, `"failed"` or `"not_found"` (a not-found page) for this URL |
> | `error` | Human-readable failure reason (failed results only) |
> | `title` | Extracted page title |
> | `url` | Original URL |
> | `content` | Extracted content (markdown or JSON) |
> | `description` | Page meta description (paper abstract for academic sources) |
> | `source` | `"web"`, or the dataset id for academic papers (e.g. `valyu/valyu-arxiv`) |
> | `price` | Base extraction price for this URL, excluding the AI processing charge. Use `total_cost_dollars` for the charge |
> | `length` | Character count |
> | `data_type` | `"unstructured"` or `"structured"` |
> | `summary_success` | Whether AI processing succeeded (only when `summary` is used) |
> | `image_url` | Extracted image URLs (figures, for academic papers) |
> | `screenshot_url` | Page screenshot URL (omitted unless `screenshot=true`) |
> | `doi`, `authors`, `citation_count` | Academic sources only |

## Error handling

Each result carries a `status` of `success`, `failed` or `not_found`. Failed and not found results include a descriptive `error` (page unavailable, required sign-in, blocked, timed out) - inspect `status` before reading the content.

| HTTP status | Meaning |
| - | - |
| `200` | All URLs extracted successfully |
| `206` | Partial - some succeeded, some failed (check `urls_failed` and per-result `status`) |
| `422` | Every URL failed - see the top-level `error` |

The following uses a raw HTTP response, rather than the SDK response model.

```python theme={null}
if response.status_code == 206:
    data = response.json()
    failed = [r for r in data["results"] if r.get("status") != "success"]
    for r in failed:
        print(f"{r['url']} failed: {r['error']}")
elif response.status_code == 422:
    error_message = response.json()["error"]
```

## Next steps

> [card] [API reference](https://docs.valyu.ai/api-reference/endpoint/contents.md)
>
> Complete parameter documentation

> [card] [Python SDK](https://docs.valyu.ai/sdk/python-sdk.md)
>
> Python integration

> [card] [TypeScript SDK](https://docs.valyu.ai/sdk/typescript-sdk.md)
>
> TypeScript integration

> [card] [Integrations](https://docs.valyu.ai/integrations/index)
>
> LangChain, LlamaIndex, and more


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