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

Wire up Valyu Answer (search-grounded answers) with the TypeScript SDK.

Open in Cursor

Basic usage

import { Valyu } from "valyu-js";

const valyu = new Valyu();

const response = await valyu.answer(
  "What are the latest developments in quantum computing?"
);

if (response.success) {
  console.log(response.contents);
  console.log("Sources used:", response.search_metadata.number_of_results);
}

Common patterns

// Steer tone and format
await valyu.answer("Explain quantum computing", {
  systemInstructions: "Explain clearly with practical examples, no jargon.",
});

// Restrict to authoritative sources
await valyu.answer("React performance best practices", {
  searchType: "web",
  includedSources: ["react.dev", "developer.mozilla.org"],
});

// Recent, location-specific answers
await valyu.answer("Current renewable energy incentives", {
  countryCode: "US",
  startDate: "2024-01-01",
});

// Lower latency
await valyu.answer("Current status of the stock market", { fastMode: true });

Structured output

Pass a JSON schema to structuredOutput and response.contents comes back as a structured object instead of a string. Detect it with typeof response.contents === "object":
const response = await valyu.answer("What is the impact of AI on software development?", {
  structuredOutput: {
    type: "object",
    properties: {
      summary: { type: "string" },
      key_impacts: { type: "array", items: { type: "string" } },
      future_outlook: { type: "string" },
    },
    required: ["summary", "key_impacts"],
  },
});

if (response.success && typeof response.contents === "object") {
  const answer = response.contents as any;
  console.log(answer.summary, answer.key_impacts);
}

Streaming

Set streaming: true to receive the answer progressively as an async generator of typed chunks:
import { Valyu, AnswerStreamChunk } from "valyu-js";

const stream = await valyu.answer("What is machine learning?", { streaming: true });

for await (const chunk of stream as AsyncGenerator<AnswerStreamChunk>) {
  if (chunk.type === "search_results") {
    console.log(`Found ${chunk.search_results?.length} sources`);
  } else if (chunk.type === "content" && chunk.content) {
    process.stdout.write(chunk.content);
  } else if (chunk.type === "metadata") {
    console.log(`\nCost: $${chunk.cost?.total_deduction_dollars.toFixed(4)}`);
  } else if (chunk.type === "error") {
    console.error(`Error: ${chunk.error}`);
  }
}
Chunk typeDescription
search_resultsSources found (streamed first, before answer generation)
contentPartial answer text chunk
metadataFinal costs, token usage, and full search results
doneStream completed successfully
errorAn error occurred
For open-ended, multi-step work (reports, diligence, deliverables), reach for DeepResearch instead of Answer.

Reference

query (string, required) - the question to answer.
ParameterTypeDescriptionDefault
structuredOutputobjectJSON schema for structured responseundefined
systemInstructionsstringCustom AI instructions (max 2000 chars)undefined
searchType"web" | "proprietary" | "all" | "news"Search type before generating the answer"all"
dataMaxPricenumberMax cost in USD for data retrieval (search costs only)1.0
countryCodestring2-letter ISO country code to bias resultsundefined
includedSources / excludedSourcesstring[]Sources to search within / excludeundefined
startDate / endDatestringDate filter (YYYY-MM-DD)undefined
fastModebooleanReduced latencyfalse
streamingbooleanStream chunks as they are generatedfalse
type AnswerResponse = AnswerSuccessResponse | AnswerErrorResponse;

interface AnswerSuccessResponse {
  success: true;
  tx_id: string;
  original_query: string;
  contents: string | Record<string, any>; // string, or an object when structuredOutput is passed
  search_results: SearchResult[];
  search_metadata: SearchMetadata;
  ai_usage: AIUsage;
  cost: Cost;
}

interface AnswerErrorResponse {
  success: false;
  error: string;
}