Skip to content
valyuAIPublic

About

The Official Valyu JavaScript SDK

Resources

Stars

4 stars

Watchers

1 watching

Forks

Repository files navigation

Valyu JavaScript SDK

npm version License: MIT

Search and research APIs built for AI agents. Access web and proprietary data sources through Search, extract content from URLs, generate grounded answers, and run multi-step research with DeepResearch - all through a single SDK.

Documentation | API Reference | Platform

Installation

npm install valyu-js

Quick Start

import { Valyu } from "valyu-js";

const valyu = new Valyu(process.env.VALYU_API_KEY);

const response = await valyu.search("latest advances in transformer architectures", {
  maxNumResults: 5,
  searchType: "all",
});

for (const result of response.results) {
  console.log(result.title, result.url);
}

Get $10 free credits when you sign up at platform.valyu.ai. No credit card required.

APIs

Search

Search across web and proprietary data sources with a single query.

const response = await valyu.search("CRISPR gene therapy clinical trials 2026", {
  searchType: "proprietary",                    // "all", "web", or "proprietary"
  maxNumResults: 10,                            // 1-20 results
  includedSources: ["valyu/valyu-pubmed"],      // filter to specific sources
  includeAbstracts: true,                       // search the full PubMed abstract corpus
  startDate: "2026-01-01",                      // date filtering
  endDate: "2026-12-31",
});
All search parameters
Parameter Type Default Description
query string required Search query
searchType string "all" "all", "web", or "proprietary"
maxNumResults number 10 Results to return (1-20)
maxPrice number 30 Max price per thousand queries (CPM)
relevanceThreshold number 0.5 Min relevance score (0-1)
includedSources string[] [] Sources to search
excludeSources string[] [] Sources to exclude
startDate string - Start date (YYYY-MM-DD)
endDate string - End date (YYYY-MM-DD)
countryCode string - Country filter (e.g. "US", "GB")
responseLength string | number - "short", "medium", "large", "max", or character count
includeAbstracts boolean false Search PubMed's complete abstract corpus instead of full-text papers
includeImageLinks boolean true When false, image markdown ![alt](url) in result content becomes [Image: alt]; images with no alt text are removed
category string - Category filter

Contents

Extract clean, structured content from URLs. Supports sync (1-10 URLs) and async (up to 50 URLs) modes.

// Basic extraction
const response = await valyu.contents(["https://arxiv.org/abs/2301.00001"]);

// With AI summarization
const response = await valyu.contents(["https://example.com/article"], {
  summary: true,
  responseLength: "medium",
});

// Replace image links with their alt text
const response = await valyu.contents(["https://example.com/article"], {
  includeImageLinks: false,   // `![alt](url)` becomes `[Image: alt]`; also available on search()
});

// Structured data extraction with JSON schema
const response = await valyu.contents(["https://en.wikipedia.org/wiki/OpenAI"], {
  summary: {
    type: "object",
    properties: {
      company_name: { type: "string" },
      founded_year: { type: "integer" },
    },
  },
});

Answer

Deprecated. The Answer API is deprecated (announced 2026-11-17) and stops working on 2026-12-17, when the endpoint returns HTTP 410. valyu.answer() still works until then but logs a one-time console.warn per process. Use DeepResearch with mode: "instant", or search() plus your own LLM. See the migration guide.

AI-generated answers grounded by Valyu's search. Supports streaming.

const response = await valyu.answer("What are the side effects of metformin?", {
  searchType: "proprietary",
  includedSources: ["valyu/valyu-pubmed"],
});

console.log(response.contents);        // AI-generated answer
console.log(response.search_results);  // Source citations

DeepResearch

Multi-step research agent that produces comprehensive reports with citations.

// Start a research task
const task = await valyu.deepresearch.create({
  query: "Compare CRISPR and base editing approaches for sickle cell disease",
  model: "heavy",
  outputFormats: ["markdown", "pdf"],
});

// Wait for completion with progress
const result = await valyu.deepresearch.wait(task.deepresearch_id, {
  onProgress: (status) => {
    console.log(`Step ${status.progress.current_step}/${status.progress.total_steps}`);
  },
});

console.log(result.output);   // Markdown report
console.log(result.pdf_url);  // PDF download link

Modes. From quickest to most thorough: instant, fast (SDK default), standard, heavy, max. instant returns a short cited answer, typically in under 30 seconds:

const task = await valyu.deepresearch.create({
  query: "What is the capital of Australia and why was it chosen?",
  mode: "instant",
});
const result = await valyu.deepresearch.wait(task.deepresearch_id);
console.log(result.output);

Human-in-the-loop checkpoints (hitl) do not run in instant mode, and batches cannot use it. An instant task's mode reads "instant"; the API also reports it as research_mode.

Human-in-the-loop. With hitl enabled, wait() passes each checkpoint to onInteraction once. Return a response to answer it, or null to leave it unanswered:

const task = await valyu.deepresearch.create({
  query: "Assess ASML's competitive position in EUV lithography",
  mode: "fast",
  hitl: { planReview: true },
});

const result = await valyu.deepresearch.wait(task.deepresearch_id, {
  onInteraction: (interaction) =>
    interaction.type === "plan_review" ? { approved: true } : null,
});

Editing a finished report. Make small, targeted edits to a finished DeepResearch report or deliverable with a plain-language instruction. Untouched text stays exactly as it was, citations stay consistent, and every edit creates a new version you can restore.

const status = await valyu.deepresearch.status(taskId);
if (status.editable) {
  let edit = await valyu.deepresearch.edit(taskId, {
    instruction: "Cut the executive summary to 3 bullets",
    focus: { section: "Executive Summary" },
    baseVersion: status.version,
    waitSeconds: 15,
  });
  if (edit.success && edit.status === "running") {
    edit = await valyu.deepresearch.waitForEdit(taskId, edit.edit_id);
  }
  if (edit.success && edit.status === "applied") {
    const updated = await valyu.deepresearch.status(taskId);
    console.log(updated.version, edit.summary);
  } else if (edit.success && edit.status === "declined") {
    console.log(edit.decline?.code, edit.decline?.suggestion);
  } else if (!edit.success) {
    console.log(edit.code, edit.error); // e.g. "edit.revision_conflict"
  }
}
  • target: { kind: "report" } (default) or { kind: "deliverable", deliverableId: "f_01" }.
  • focus: a highlighted passage (startChar/endChar UTF-16 offsets into output, text, prefix, suffix) or a section heading, with scope: "prefer" (default) or "strict".
  • citations: "stable" (default) keeps citation numbers, "compact" renumbers them by first use.
  • idempotencyKey is sent as the Idempotency-Key header, so a retry returns the same edit.
  • A declined edit (for example edit.out_of_evidence or edit.rewrite_requested) is a successful response with status: "declined". Large rewrites are declined; start a new task for those.
  • Request errors come back as { success: false, error, code, httpStatus }, with candidates for focus.ambiguous.
  • Versions: listVersions(taskId), status(taskId, { version: 1 }) to read an older one, and restoreVersion(taskId, 1) to make it the head again (history is kept).
All DeepResearch methods
Method Description
create(options) Start a new research task
status(taskId, { version }?) Get task status, or one version of the report
wait(taskId, options?) Poll until completion
stream(taskId, callbacks) Stream real-time updates
list(options) List research tasks
update(taskId, instruction) Add follow-up instruction
cancel(taskId) Cancel a running task
delete(taskId) Delete a task
togglePublic(taskId, isPublic) Toggle public access
respond(taskId, interactionId, response) Answer a HITL checkpoint
edit(taskId, options) Edit a finished report or deliverable
getEdit(taskId, editId) Get one edit
listEdits(taskId) List a task's edits
waitForEdit(taskId, editId, options?) Poll until an edit is applied, declined or failed
listVersions(taskId) List the report's versions
restoreVersion(taskId, version) Restore an earlier version as the new head

Polling. status(), wait() and stream() poll conditionally. When the server returns an ETag, the next poll for that task sends it as If-None-Match; a 304 Not Modified reuses the previous response with no body transferred, and onProgress / stream progress callbacks are not repeated for a 304. When pollInterval is not set, wait() and stream() follow the server's Retry-After hint (clamped to 1-30 seconds, default 5 seconds); an explicit pollInterval always wins. Rate limits (429) and server errors (5xx) are retried with jittered exponential backoff. Servers that send no ETag are polled exactly as before. wait() and stream() give up after maxWaitTime (default 2 hours).

Timeouts. DeepResearch, batch and workflow requests time out after 120 seconds, so a stalled connection fails instead of hanging; status polls retry it. Change it with new Valyu(apiKey, baseUrl, { timeout: 60000 }), or pass 0 to disable it.

Batch

Run multiple DeepResearch tasks in parallel. Batches support every mode except instant.

const batch = await valyu.batch.create({
  name: "Q1 Analysis",
  mode: "fast",
  outputFormats: ["markdown"],
});

await valyu.batch.addTasks(batch.batch_id, {
  tasks: [
    { query: "Analyze recent SPAC performance" },
    { query: "Review semiconductor supply chain trends" },
  ],
});

const result = await valyu.batch.waitForCompletion(batch.batch_id, {
  onProgress: (b) => console.log(`${b.counts.completed}/${b.counts.total}`),
});

Workflows

Templated DeepResearch starting points - curated by Valyu or created by your org - with typed {variable} placeholders and version history.

// Browse curated workflows
const catalog = await valyu.workflows.list({ scope: "valyu", vertical: "investment-banking" });
for (const wf of catalog.workflows ?? []) {
  console.log(`${wf.slug} - ${wf.title}`);
}

// Run one as a DeepResearch task
const task = await valyu.deepresearch.create({
  workflowId: "ib-company-profile",
  workflowParams: { company: "NVIDIA (NVDA)" },
});

const result = await valyu.deepresearch.wait(task.deepresearch_id);
console.log(result.output);

Create your own:

await valyu.workflows.create({
  slug: "weekly-competitor-scan",
  title: "Weekly Competitor Scan",
  version: {
    prompt: "Summarize the week's most important developments at {company}.",
    strategy: "Prioritize primary sources: filings, press releases, earnings calls.",
    report_format: "Bullet-point briefing, grouped by theme.",
    variables: [{ key: "company", label: "Company", required: true }],
  },
});
All Workflows methods
Method Description
list(options?) List available workflows (filter by vertical, scope, tags, free text)
get(slug, version?) Get a workflow's full template
versions(slug) List a workflow's version history
preview(slug, options?) Resolve the template without creating a task
create(options) Create an org workflow
update(slug, options) Update metadata and/or publish a new version
delete(slug) Delete an org workflow

Data Sources

List available data sources programmatically.

const sources = await valyu.datasources.list();
const categories = await valyu.datasources.categories();

Authentication

export VALYU_API_KEY="your-api-key"

Or pass directly:

const valyu = new Valyu("your-api-key");

TypeScript

Full type definitions are included. All request and response types are exported:

import { Valyu, SearchOptions, SearchResponse, SearchResult } from "valyu-js";

Error Handling

const response = await valyu.search("test");

if (!response.success) {
  console.error(response.error);
  console.error(`tx_id: ${response.tx_id}`);
}

Search, answer and DeepResearch responses may also carry non-fatal warnings (ResponseWarning[] with type, message and optional detail), for example when a requested dataset isn't included in your plan and was skipped.

Rate Limiting

The API returns 429 when a request exceeds your plan's rate limit. The SDK retries search(), contents(), answer(), deepresearch.create(), batch.create() and batch.addTasks() automatically on a 429 — these requests are never accepted when rate-limited, so a retry is always safe. Retries wait for the amount of time the server asks for (capped at 60 seconds per attempt).

// Default: up to 2 automatic retries. Set 0 to disable.
const valyu = new Valyu(apiKey, baseUrl, { maxRateLimitRetries: 2 });

If every retry still comes back 429, the failed response carries a rateLimit field with the detail from the last attempt:

const response = await valyu.search("test");

if (!response.success && response.rateLimit) {
  console.error(response.rateLimit.retryAfter); // seconds to wait
  console.error(response.rateLimit.plan); // e.g. "Pay-as-you-go" (older servers may omit this)
  console.error(response.rateLimit.upgradeUrl ?? response.rateLimit.contactUrl);
}

plan, limit, upgradeUrl and contactUrl are only sent by newer servers, so treat them as optional.

Integrations

Valyu works with Vercel AI SDK, LangChain, MCP, and more. See docs.valyu.ai for integration guides.

Links

License

MIT

About

The Official Valyu JavaScript SDK

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages