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

# Answer API

> AI-powered answer generation with search integration using the Valyu TypeScript SDK

The Answer API combines intelligent search with AI processing to generate comprehensive, factual answers to questions. It automatically searches relevant sources and uses advanced AI to synthesize accurate responses.

The API supports both **streaming** and **non-streaming** modes. By default, streaming is disabled for backward compatibility.

## Basic Usage

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

const valyu = new Valyu();

// Non-streaming (default) - waits for complete response
const response = await valyu.answer(
  "What are the latest developments in quantum computing?"
);

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

## Streaming Mode

Enable streaming to receive the answer progressively as it's generated:

```typescript theme={null}
import { Valyu, AnswerStreamChunk } from "valyu-js";

const valyu = new Valyu();

// Streaming mode - returns async generator yielding chunks
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") {
    // Print content as it streams in
    if (chunk.content) {
      process.stdout.write(chunk.content);
    }
  } else if (chunk.type === "metadata") {
    console.log(`\nCost: $${chunk.cost?.total_deduction_dollars.toFixed(4)}`);
    console.log(`Tokens: ${chunk.ai_usage?.input_tokens} in, ${chunk.ai_usage?.output_tokens} out`);
  } else if (chunk.type === "done") {
    console.log("\n[Complete]");
  } else if (chunk.type === "error") {
    console.error(`Error: ${chunk.error}`);
  }
}
```

### Stream Chunk Types

| Type             | Description                                                     |
| ---------------- | --------------------------------------------------------------- |
| `search_results` | Search sources found (streamed first, before answer generation) |
| `content`        | Partial answer text chunk                                       |
| `metadata`       | Final metadata with costs, token usage, and full search results |
| `done`           | Stream completed successfully                                   |
| `error`          | An error occurred                                               |

## Parameters

### Query (Required)

| Parameter | Type   | Description                     |
| --------- | ------ | ------------------------------- |
| `query`   | string | The question or query to answer |

### Options (Optional)

| Parameter            | Type                                              | Description                                                  | Default   |
| -------------------- | ------------------------------------------------- | ------------------------------------------------------------ | --------- |
| `structuredOutput`   | object                                            | JSON schema for structured response format                   | undefined |
| `systemInstructions` | string                                            | Custom AI instructions (max 2000 characters)                 | undefined |
| `searchType`         | `"web"` \| `"proprietary"` \| `"all"` \| `"news"` | Search type before generating answer                         | `"all"`   |
| `dataMaxPrice`       | number                                            | Maximum cost in USD for data retrieval (search costs only)   | 1.0       |
| `countryCode`        | string                                            | 2-letter ISO country code to bias results                    | undefined |
| `includedSources`    | string\[]                                         | Sources to search within                                     | undefined |
| `excludedSources`    | string\[]                                         | Sources to exclude                                           | undefined |
| `startDate`          | string                                            | Start date for filtering (YYYY-MM-DD)                        | undefined |
| `endDate`            | string                                            | End date for filtering (YYYY-MM-DD)                          | undefined |
| `fastMode`           | boolean                                           | Enable fast mode for reduced latency                         | false     |
| `streaming`          | boolean                                           | Enable streaming mode to receive chunks as they're generated | false     |

## Response Format

```typescript theme={null}
type AnswerResponse = AnswerSuccessResponse | AnswerErrorResponse;

interface AnswerSuccessResponse {
  success: true;
  tx_id: string;
  original_query: string;
  contents: string | Record<string, any>; // string or structured object
  data_type: "unstructured" | "structured";
  search_results: SearchResult[];
  search_metadata: SearchMetadata;
  ai_usage: AIUsage;
  cost: Cost;
}

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

## Parameter Examples

### Basic Question Answering

Get a comprehensive answer to any question:

```typescript theme={null}
const response = await valyu.answer(
  "How do neural networks learn?"
);

if (response.success) {
  console.log(response.contents);
}
```

### System Instructions

Customize the AI's response style and focus:

```typescript theme={null}
const response = await valyu.answer(
  "Explain quantum computing",
  {
    systemInstructions: "You are a computer science professor. Explain concepts clearly with practical examples and avoid overly technical jargon.",
  }
);
```

### Structured Output Response

Get answers in a specific JSON format:

```typescript theme={null}
const response = await valyu.answer(
  "What is the impact of AI on software development?",
  {
    structuredOutput: {
      type: "object",
      properties: {
        summary: {
          type: "string",
          description: "Brief summary of AI's impact"
        },
        key_impacts: {
          type: "array",
          items: { type: "string" },
          description: "List of key impacts"
        },
        benefits: {
          type: "array",
          items: { type: "string" },
          maxItems: 5
        },
        challenges: {
          type: "array", 
          items: { type: "string" },
          maxItems: 5
        },
        future_outlook: {
          type: "string",
          description: "Future implications and trends"
        }
      },
      required: ["summary", "key_impacts", "future_outlook"]
    }
  }
);

if (response.success && response.data_type === "structured") {
  const structuredAnswer = response.contents as any;
  console.log("Summary:", structuredAnswer.summary);
  console.log("Key impacts:", structuredAnswer.key_impacts);
}
```

### Source Filtering

Get answers from specific, authoritative sources:

```typescript theme={null}
const response = await valyu.answer(
  "What are the best practices for React performance optimization?",
  {
    searchType: "web",
    includedSources: [
      "react.dev", 
      "developer.mozilla.org",
      "web.dev"
    ],
    systemInstructions: "Focus on official recommendations and proven techniques"
  }
);
```

### Geographic Filtering

Get location-specific information:

```typescript theme={null}
const response = await valyu.answer(
  "What are the current renewable energy policies and incentives?",
  {
    countryCode: "US",
    startDate: "2024-01-01",
    systemInstructions: "Focus on federal and state-level policies with specific program details"
  }
);
```

### Date Range Filtering

Get answers about recent events or developments:

```typescript theme={null}
const response = await valyu.answer(
  "What are the latest breakthroughs in AI model architectures?",
  {
    startDate: "2024-06-01",
    endDate: "2024-12-01",
    searchType: "proprietary",
    includedSources: ["valyu/valyu-arxiv"],
    systemInstructions: "Focus on novel architectures and their performance improvements"
  }
);
```

### Fast Mode

For time-sensitive applications, enable fast mode for quicker responses:

```typescript theme={null}
const response = await valyu.answer(
  "What's the current status of the stock market?",
  {
    fastMode: true,
  }
);
```

## Use Case Examples

### Financial Analysis

Build an AI-powered financial research assistant that provides comprehensive market analysis:

```typescript theme={null}
const response = await valyu.answer(
  "How has Tesla's stock performance compared to other EV companies in 2024?",
  {
    searchType: "proprietary",
    includedSources: ["valyu/valyu-stocks"],
    structuredOutput: {
      type: "object",
      properties: {
        tesla_performance: {
          type: "object",
          properties: {
            ytd_return: { type: "string" },
            current_price: { type: "string" },
            key_events: { 
              type: "array", 
              items: { type: "string" } 
            }
          }
        },
        competitor_comparison: {
          type: "array",
          items: {
            type: "object",
            properties: {
              company: { type: "string" },
              ytd_return: { type: "string" },
              relative_performance: { type: "string" }
            }
          }
        },
        market_analysis: { type: "string" }
      }
    },
    systemInstructions: "Provide detailed financial analysis with specific metrics, key events, and market context. Include percentage changes and dollar values where applicable."
  }
);

if (response.success && response.data_type === "structured") {
  const analysis = response.contents as any;
  
  // Display Tesla performance
  console.log("Tesla Performance:");
  console.log(`YTD Return: ${analysis.tesla_performance.ytd_return}`);
  console.log(`Current Price: ${analysis.tesla_performance.current_price}`);
  
  // Compare with competitors
  console.log("\nCompetitor Analysis:");
  analysis.competitor_comparison.forEach((comp: any) => {
    console.log(`${comp.company}: ${comp.ytd_return} (${comp.relative_performance})`);
  });
  
  console.log(`\nMarket Analysis: ${analysis.market_analysis}`);
}
```

### Technical Documentation Assistant

Create an AI assistant that provides comprehensive technical guidance with implementation details:

```typescript theme={null}
async function getTechnicalGuide(topic: string) {
  const response = await valyu.answer(
    `How do I implement ${topic} in a Node.js application?`,
    {
      systemInstructions: "Provide step-by-step implementation guidance with code examples, security best practices, and common pitfalls to avoid. Structure the response as a comprehensive tutorial.",
      includedSources: [
        "nodejs.org",
        "developer.mozilla.org",
        "github.com"
      ],
      structuredOutput: {
        type: "object",
        properties: {
          overview: {
            type: "string",
            description: "Brief overview of the implementation"
          },
          prerequisites: {
            type: "array",
            items: { type: "string" },
            description: "Required dependencies and setup"
          },
          implementation_steps: {
            type: "array",
            items: {
              type: "object",
              properties: {
                step: { type: "string" },
                description: { type: "string" },
                code_example: { type: "string" }
              }
            }
          },
          security_considerations: {
            type: "array",
            items: { type: "string" }
          },
          common_pitfalls: {
            type: "array",
            items: { type: "string" }
          },
          additional_resources: {
            type: "array",
            items: { type: "string" }
          }
        },
        required: ["overview", "implementation_steps", "security_considerations"]
      }
    }
  );

  if (response.success && response.data_type === "structured") {
    const guide = response.contents as any;
    
    console.log("=== Technical Implementation Guide ===");
    console.log(`\nOverview: ${guide.overview}`);
    
    console.log("\nPrerequisites:");
    guide.prerequisites?.forEach((req: string, i: number) => {
      console.log(`${i + 1}. ${req}`);
    });
    
    console.log("\nImplementation Steps:");
    guide.implementation_steps.forEach((step: any, i: number) => {
      console.log(`\n${i + 1}. ${step.step}`);
      console.log(`   ${step.description}`);
      if (step.code_example) {
        console.log(`   Code: ${step.code_example}`);
      }
    });
    
    return guide;
  }
  
  return null;
}

// Usage example
const oauthGuide = await getTechnicalGuide("OAuth 2.0 authentication");
```

### Comparative Analysis Tool

Build a decision-making assistant that provides structured comparisons of different options:

```typescript theme={null}
async function compareOptions(topic: string, options: string[]) {
  const response = await valyu.answer(
    `Compare the pros and cons of ${options.join(", ")} for ${topic}`,
    {
      systemInstructions: "Provide a comprehensive comparison with objective analysis. Include specific examples, metrics, and real-world considerations for each option.",
      structuredOutput: {
        type: "object",
        properties: {
          comparison_summary: {
            type: "string",
            description: "Brief overview of the comparison"
          },
          options: {
            type: "array",
            items: {
              type: "object", 
              properties: {
                name: { type: "string" },
                pros: { 
                  type: "array", 
                  items: { type: "string" } 
                },
                cons: { 
                  type: "array", 
                  items: { type: "string" } 
                },
                best_for: { type: "string" },
                learning_curve: { type: "string" },
                market_adoption: { type: "string" },
                performance_rating: { type: "string" }
              }
            }
          },
          decision_matrix: {
            type: "object",
            properties: {
              criteria: {
                type: "array",
                items: { type: "string" }
              },
              scores: {
                type: "object",
                description: "Scores for each option on each criteria"
              }
            }
          },
          recommendation: { 
            type: "string",
            description: "Final recommendation with reasoning"
          }
        },
        required: ["comparison_summary", "options", "recommendation"]
      }
    }
  );

  if (response.success && response.data_type === "structured") {
    const comparison = response.contents as any;
    
    console.log("=== Comparative Analysis ===");
    console.log(`\n${comparison.comparison_summary}`);
    
    console.log("\n=== Option Analysis ===");
    comparison.options.forEach((option: any) => {
      console.log(`\n${option.name.toUpperCase()}`);
      console.log(`Best for: ${option.best_for}`);
      console.log(`Learning curve: ${option.learning_curve}`);
      console.log(`Market adoption: ${option.market_adoption}`);
      
      console.log("Pros:");
      option.pros.forEach((pro: string) => console.log(`  ✓ ${pro}`));
      
      console.log("Cons:");
      option.cons.forEach((con: string) => console.log(`  ✗ ${con}`));
    });
    
    console.log(`\n=== Final Recommendation ===`);
    console.log(comparison.recommendation);
    
    return comparison;
  }
  
  return null;
}

// Usage examples
const frameworkComparison = await compareOptions(
  "enterprise web applications", 
  ["React", "Vue", "Angular"]
);

const databaseComparison = await compareOptions(
  "scalable microservices architecture",
  ["PostgreSQL", "MongoDB", "Cassandra"]
);
```

## Error Handling

```typescript theme={null}
const response = await valyu.answer(query, options);

if (!response.success) {
  console.error("Answer generation failed:", response.error);
  
  // Handle specific error cases
  if (response.error.includes("insufficient credits")) {
    console.log("Please add more credits to your account");
  } else if (response.error.includes("invalid")) {
    console.log("Check your query and options");
  }
  
  return;
}

// Process successful response
console.log(`Transaction ID: ${response.tx_id}`);
console.log(`Data type: ${response.data_type}`);
console.log(`Sources processed: ${response.search_metadata.number_of_results}`);
console.log(`Answer: ${response.contents}`);
```

## Best Practices

### Improve Answer Quality

```typescript theme={null}
const response = await valyu.answer(query, {
  systemInstructions: "Provide detailed, evidence-based answers with specific examples",
  searchType: "proprietary", // Use high-quality academic/professional sources
  includedSources: ["authoritative-domain.com"],
  startDate: "2024-01-01" // Focus on recent information
});
```

### Handle Structured Responses

```typescript theme={null}
const response = await valyu.answer(query, {
  structuredOutput: schema
});

if (response.success) {
  if (response.data_type === "structured") {
    const structuredData = response.contents as Record<string, any>;
    // Process structured data
  } else {
    const textAnswer = response.contents as string;
    // Process text answer
  }
}
```
