---
name: valyu-integrate
description: >
  Build the Valyu API (Search, Contents, DeepResearch, Monitor) into the
  user's own application: get an API key into the project without the user
  pasting one, write a server-side integration that matches their stack, test it
  and report back. Use when the user asks you to integrate Valyu, usually with a
  request they configured in the Valyu playground.
metadata:
  author: valyu
  homepage: https://valyu.ai
---

# Integrate Valyu into this codebase

You are wiring the Valyu API into the user's application. Valyu is search and
research for AI doing knowledge work: the web plus specialist sources (SEC
filings, academic papers, clinical trials, patents, market and economic data),
returned with source links a model can cite.

The user wants this done hands-off. Work through the five steps below without
stopping to ask about anything the repository can answer. Make the reasonable
call, and list the calls you made in your final report.

1. Read the request
2. Get a key into the project
3. Implement
4. Verify
5. Report

## 1. Read the request

The user's prompt usually contains a cURL request from the Valyu playground.
Treat it as the spec:

- The URL is the endpoint, including its version (`/v1` or `/v2`).
- The JSON body is the configuration. Keep every parameter and value exactly as
  given, including source IDs, dates, schemas and instructions. The one thing to
  turn into an input is the part that obviously varies per call: `query`,
  `urls`, or `workflow_params` for a workflow.
- The key always comes from the `VALYU_API_KEY` environment variable. The
  prompt never contains a key; never ask the user to paste one into the chat.

API reference for coding agents: https://docs.valyu.ai/AGENTS.md. Any docs page
is available as Markdown by appending `.md`. The docs index is
https://docs.valyu.ai/llms.txt.

## 2. Get a key into the project

Pick the env file the project's framework loads: `.env.local` for Next.js and
Vite, `.env` for most other projects. Use the existing one if there is one.

**Already set?** If that file (or the project's secret setup) already has a
non-empty `VALYU_API_KEY`, skip to step 3. Check without printing the value:

```bash
grep -c '^VALYU_API_KEY=.' .env.local 2>/dev/null
```

**Otherwise, mint a key with the Valyu CLI.** The user approves one sign-in in
their browser and nothing is copied or pasted. The key is written straight to
the env file, so it never appears in your output.

**1. Ignore the env file.** Make sure git ignores it before any secret goes in:

```bash
git check-ignore -q .env.local || echo ".env.local" >> .gitignore
```

**2. Get the CLI.** Use `valyu` if `command -v valyu` finds it (1.2.3 or
newer; `valyu upgrade --run` updates it). Otherwise run it through
`npx -y @valyu/cli` when Node.js 20+ is available, or install the binary with `curl -fsSL https://get.valyu.ai | bash` (Windows PowerShell:
`irm https://get.valyu.ai/install.ps1 | iex`).

**3. Sign in**, unless `valyu whoami` already shows an account:

```bash
valyu login --json
```

This starts a browser device flow and prints line-delimited JSON:
`device_code` (show the user the URL and code), `auth_waiting` (blocks until
they approve) and `auth_success`. Stream the output and tell the user you
are waiting for them to approve. Someone without an account can create one
on that page; new accounts get free credits. Add `--no-browser` in a
headless session.

**Working for yourself, with an AgentMail inbox?** You can approve that page
yourself: choose **Continue with AgentID** on the sign-in page. You get your
own Valyu account, and agents with the same AgentMail owner share one
organisation and its credits, each with its own key. Without the CLI, open
https://platform.valyu.ai/auth/agentid, sign in, then press **Get your API
key**; the key is in the element with id `valyu-api-key`.

**4. Create a key** for this project with a monthly spend cap, and write it
straight to the env file. The name uses the project folder so the user can
find it later:

```bash
valyu account keys create --name "$(basename "$PWD")-dev" --cap 10 --window monthly --json \
  | node -e '
const fs = require("fs");
let raw = "";
process.stdin.on("data", (d) => (raw += d)).on("end", () => {
  const out = JSON.parse(raw);
  if (!out.api_key) { console.error(JSON.stringify(out.error ?? out)); process.exit(1); }
  const file = process.argv[1];
  const kept = fs.existsSync(file)
    ? fs.readFileSync(file, "utf8").split("\n").filter((l) => !l.startsWith("VALYU_API_KEY=")).join("\n")
    : "";
  fs.writeFileSync(file, kept + (kept && !kept.endsWith("\n") ? "\n" : "") + "VALYU_API_KEY=" + out.api_key + "\n");
  console.log("VALYU_API_KEY written to " + file + " (key " + out.key_prefix + ")");
});' .env.local
```

Without Node.js, use Python for the same step:

```bash
valyu account keys create --name "$(basename "$PWD")-dev" --cap 10 --window monthly --json \
  | python3 -c '
import json, os, sys
out = json.load(sys.stdin)
if not out.get("api_key"):
    sys.exit(json.dumps(out.get("error", out)))
path = sys.argv[1]
kept = [l for l in open(path).read().split("\n") if not l.startswith("VALYU_API_KEY=")] if os.path.exists(path) else []
text = "\n".join(kept)
open(path, "w").write(text + ("\n" if text and not text.endswith("\n") else "") + "VALYU_API_KEY=" + out["api_key"] + "\n")
print("VALYU_API_KEY written to " + path + " (key " + out["key_prefix"] + ")")' .env
```

If this fails because the signed-in key can't manage keys, run
`valyu login` again: a fresh sign-in can create keys.

**5. Update the env example.** If the project has one (`.env.example`,
`.env.sample`), add `VALYU_API_KEY=` to it with no value.

Never `cat`, `echo`, print or log the key or the env file, and never commit it.
If the CLI route is impossible (no shell, no browser for the user), ask the user
to create a key at https://platform.valyu.ai/user/account/apikeys and add it to
the env file themselves.

Production is the user's call: tell them to create a separate key for
production and set it in their deployment's environment or secret manager.
Don't do it for them unless they ask.

## 3. Implement

### Pick the client from the stack

| The project uses | Use |
| --- | --- |
| Vercel AI SDK (`ai` in package.json), and a model should decide when to search | `@valyu/ai-sdk` tools. See https://docs.valyu.ai/integrations/vercel-ai-sdk.md |
| LangChain or LangGraph | `langchain-valyu`. See https://docs.valyu.ai/integrations/langchain.md |
| LlamaIndex | See https://docs.valyu.ai/integrations/llamaindex.md |
| Any other TypeScript or JavaScript | `valyu-js` (`import { Valyu } from "valyu-js"`). See https://docs.valyu.ai/sdk/typescript-sdk.md |
| Any other Python | `valyu` (`from valyu import Valyu`). See https://docs.valyu.ai/sdk/python-sdk.md |
| Anything else | HTTP: `x-api-key: $VALYU_API_KEY` header, JSON body |

Install with the project's package manager (match the lockfile: pnpm, npm,
yarn, bun, uv, poetry, pip).

Use plain HTTP instead of the SDK for this request when the prompt says so, or
when the body has a field the installed SDK version doesn't accept (check its
types after installing, rather than assuming). Never drop a parameter from the
user's request to make it fit an SDK. If the URL is a `/v2` endpoint and you
use an SDK, pass that base URL to the client (`base_url` in Python, the second
constructor argument in TypeScript).

### Where the code goes

- **Server side only**: a route handler, server action, API endpoint, worker or
  backend service. Never call Valyu from browser code, and never expose the key
  through a public env prefix such as `NEXT_PUBLIC_` or `VITE_`.
- **One small module** the rest of the app calls, for example `lib/valyu.ts` or
  `services/valyu.py`, exposing a typed function per operation. It reads
  `VALYU_API_KEY` and fails with a clear message if it's missing.
- **Follow the codebase's conventions**: language, style, error handling,
  logging, folder layout and test framework.
- **Wire it in where the user's request points.** If the app has an obvious
  place for it (an existing feature, route or agent tool that needs search or
  research), connect it there. If not, stop at the module plus one minimal
  server route or function that calls it, and say where it could plug in. Don't
  build UI unless asked.

### Per endpoint

**Search (`POST /v1/search`).** Returns `results[]` with `title`, `url`,
`content`, `source` and dates. Keep `url` and `source` with every passage you
pass to a model, so it can cite them. An empty `results` array is not an
error. Read `warnings[]`: it says what was skipped, for example a dataset
outside the plan. Keep `tx_id` for support. Restrict domains with
`included_sources` / `excluded_sources`, never with `site:` in the query.

**Contents (`POST /v1/contents`).** Returns clean Markdown per URL, with an
optional summary or JSON extraction. Up to 10 `urls` run synchronously; more
(up to 50) need `async: true` and a saved `job_id`. A request can partially
succeed (`206`; `422` when every URL fails): handle each result's `status`
rather than treating an HTTP success as proof every page was extracted.

**DeepResearch (`POST /v1|v2/deepresearch/tasks`).** Asynchronous: a task runs
for minutes, or longer on the heavier modes, and every task is billed.

- Create returns `202` with `deepresearch_id` and `status`. Save the ID before
  you do anything else, so a restart or a client timeout resumes the same task
  instead of creating and paying for a new one.
- Poll `GET {base}/deepresearch/tasks/{id}/status`. `status` is `queued`,
  `running`, `paused` (waiting for a reply), `completed`, `failed` or
  `cancelled`; the last three are final. Wait the `Retry-After` seconds between
  polls, and send `If-None-Match` with the last `ETag` to get a cheap `304`
  when nothing changed.
- Don't hold a web request open while a task runs: poll from a background job
  or queue, or use a webhook.
- Webhook (optional): add `webhook_url` to the create body. The create response
  then includes `webhook_secret`, once: store it as a secret. Each delivery has
  `X-Webhook-Timestamp` and `X-Webhook-Signature: sha256=<hex>`, where the hex
  is the HMAC-SHA256 of `"<timestamp>.<raw body>"` with that secret. Verify it
  with a constant-time comparison and reject old timestamps.
- Cancel with `POST {base}/deepresearch/tasks/{id}/cancel`.
- A completed task has `output` (Markdown or JSON, as `output_type` says),
  `sources[]`, `images[]`, `deliverables[]` (`type`, `status`, `url`,
  `filename`), `pdf_url` (empty when there is no PDF), `cost` and `warnings[]`.
  Deliverable and PDF URLs are signed and expire: download the files if the
  app needs to keep them. A failed task has `error` and sometimes
  `error_message`.
- Build `createTask`, `getTask`, `waitForTask` (with a timeout and a way to
  stop) and `cancelTask`.

**Monitor (`POST /v1/monitor`).** Creates a standing watch on a topic, so it is
set up once, not on every request: make creating it an explicit setup step (a
script or admin action), and store the returned `id`. Read matches from
`GET /v1/monitor/alerts`; when the monitor runs research, an alert carries a
`deepresearch_id` you poll like any DeepResearch task. With a `webhook_url`,
`webhook_secret` is returned once: store it and verify each delivery
(`X-Valyu-Signature` is `sha256=` plus the hex HMAC-SHA256 of
`"<X-Valyu-Timestamp>.<raw body>"`, keyed with the secret; reject old
timestamps). The SDKs have no Monitor client yet, so use HTTP. Monitor is not
in the docs yet: this section and the request from the playground are the
reference. It needs a paid plan: on Pay-as-you-go every call is `403
subscription_required`, so tell the user rather than retrying. Research is on
by default (a DeepResearch task per match); send
`"deep_research": {"enabled": false}` for alerts only. A monitor is
charged daily per watched source (5 to 40 credits a day each, 90 with no source
picked), so pin the sources the topic needs.

### Errors

Errors are JSON with `error` and usually `code`.

| Status | Meaning | Do |
| --- | --- | --- |
| 400 | Invalid request; the message says which field | Fix the request. Don't retry it unchanged |
| 401 | Missing or unknown key | Check `VALYU_API_KEY` is loaded in the running process |
| 402 | Out of credits, or the key's spend cap is reached | Surface it to the user; don't retry |
| 403 | Key disabled, source outside the plan, or rate limited | Read `error`. Back off and retry only for rate limits |
| 5xx | Temporary | Retry with exponential backoff and a cap |

## 4. Verify

- **Tests with the HTTP calls or SDK mocked**, in the project's test framework:
  a success, an empty result, a 402, and for DeepResearch a completed task, a
  failed task and a timeout. Never create real DeepResearch tasks in tests.
- **One live call through the code you wrote**, to prove the key and wiring
  work end to end. For Search use `max_num_results: 1`; for Contents, one URL.
  DeepResearch tasks cost more and keep running, so don't create one live unless the user asked you to. Prove the key
  instead with a one-result Search call.
- Run the project's type checker and linter on what you changed.

## 5. Report

Finish with a short report:

- Files created and changed.
- The endpoint and client (SDK, AI SDK tools or HTTP) you used, and why.
- The key: its name and cap, which env file holds it, and that the user can
  change the cap or revoke it at https://platform.valyu.ai/user/account/apikeys.
- What to set in production.
- The exact command to run the tests and the live check.
- Any choice you made on the user's behalf, such as where you wired it in.

## If something goes wrong

- `valyu: command not found` after the curl installer: it installs to
  `$HOME/.local/bin`, which may not be on `PATH`. Call it by full path.
- An access error on a dataset (`plan does not include access to ...`): check
  the ID with `valyu sources` first. The same error is returned for an ID that
  does not exist. Specialist sources such as SEC filings and market data need a
  plan: say so plainly, see https://www.valyu.ai/pricing.md.
- Data the user needs isn't in the catalog: tell them to email
  contact@valyu.ai. Valyu adds sources for customers.
- Anything else: `valyu doctor`, then the error message.
