# Knowledge Base RAG API

Query knowledge bases directly from your agent code to retrieve relevant documents and generate responses with citations.

## Overview

The Knowledge Base RAG API provides two functions for interacting with knowledge bases:

* **`retrieveFromKnowledgeBase`**: Retrieve relevant documents based on a query
* **`retrieveAndGenerateFromKnowledgeBase`**: Retrieve documents and generate a response with citations

Both functions support metadata filtering, result count control, and automatic agent/environment isolation.

### Default Knowledge Base Selection

The `knowledgeBaseId` parameter is **optional**. If omitted, the backend will:

* **Exactly 1 KB** for the agent → automatically use it
* **0 KBs** → throw an error prompting you to create a knowledge base
* **>1 KBs** → throw an error requiring you to pass `knowledgeBaseId` explicitly to disambiguate

This simplifies usage for agents with a single knowledge base.

> **Before you start:** Create a knowledge base and upload documents in the platform dashboard. For agents with multiple knowledge bases, copy the `knowledgeBaseId` to pass explicitly. See [Knowledge Bases](/platform/knowledge-bases.md).

## retrieveFromKnowledgeBase

Retrieve relevant documents from a knowledge base.

### Function Signature

```typescript
retrieveFromKnowledgeBase(
  params: {
    knowledgeBaseId?: string;
    environment: string;
    query: string;
    numberOfResults?: number;
    filters?: KnowledgeBaseFilter;
  },
  timeoutMs?: number
): Promise<{
  retrievalResults: KnowledgeBaseRetrievalResult[];
  nextToken?: string;
}>
```

### Parameters

| Parameter                | Type                | Required | Description                                                                                                                    |
| ------------------------ | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `params.knowledgeBaseId` | string              |          | ID of the knowledge base to query. If omitted, backend auto-selects the KB if exactly one exists; errors if 0 or >1 KBs exist. |
| `params.environment`     | string              | ✓        | Environment (e.g., 'development', 'production')                                                                                |
| `params.query`           | string              | ✓        | Search query string                                                                                                            |
| `params.numberOfResults` | number              |          | Number of results to return (default: 5)                                                                                       |
| `params.filters`         | KnowledgeBaseFilter |          | Metadata filters for the query                                                                                                 |
| `timeoutMs`              | number              |          | Query timeout (default: 30000ms)                                                                                               |

### Return Value

Returns a Promise with:

* `retrievalResults`: Array of retrieval results, each containing:
  * `content.text`: Text content of the document chunk
  * `location.s3Location.uri`: URI of the source document
  * `metadata`: Associated metadata as key-value pairs
  * `score`: Relevance score (0-1)
* `nextToken`: Optional token for pagination

### Examples

**With explicit knowledgeBaseId:**

```typescript
import { retrieveFromKnowledgeBase } from '@minded-ai/mindedjs';

const results = await retrieveFromKnowledgeBase({
  knowledgeBaseId: 'kb-abc123',
  environment: 'production',
  query: 'How do I reset my password?',
  numberOfResults: 10,
  filters: {
    equals: { key: 'label1', value: 'dept:support' },
  },
});

for (const result of results.retrievalResults) {
  console.log(`Score: ${result.score}`);
  console.log(`Content: ${result.content.text}`);
  console.log(`Source: ${result.location.s3Location.uri}`);
}
```

## retrieveAndGenerateFromKnowledgeBase

Retrieve documents and generate a response using an LLM, with citations referencing source documents.

### Function Signature

```typescript
retrieveAndGenerateFromKnowledgeBase(
  params: {
    knowledgeBaseId?: string;
    environment: string;
    query: string;
    modelArn?: string;
    numberOfResults?: number;
    filters?: KnowledgeBaseFilter;
  },
  timeoutMs?: number
): Promise<{
  output: string | null;
  citations: KnowledgeBaseCitation[];
  sessionId?: string;
}>
```

### Parameters

| Parameter                | Type                | Required | Description                                                                                                                    |
| ------------------------ | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `params.knowledgeBaseId` | string              |          | ID of the knowledge base to query. If omitted, backend auto-selects the KB if exactly one exists; errors if 0 or >1 KBs exist. |
| `params.environment`     | string              | ✓        | Environment (e.g., 'development', 'production')                                                                                |
| `params.query`           | string              | ✓        | Search query string                                                                                                            |
| `params.modelArn`        | string              |          | Model ARN for generation (uses default if not specified)                                                                       |
| `params.numberOfResults` | number              |          | Number of documents to retrieve (default: 5)                                                                                   |
| `params.filters`         | KnowledgeBaseFilter |          | Metadata filters for the query                                                                                                 |
| `timeoutMs`              | number              |          | Query timeout (default: 60000ms)                                                                                               |

### Return Value

Returns a Promise with:

* `output`: Generated text response (null if no relevant documents found)
* `citations`: Array of citations, each containing:
  * `generatedResponsePart.textResponsePart.text`: The part of the response that cites this source
  * `generatedResponsePart.textResponsePart.span`: Start/end positions in the response
  * `retrievedReferences`: Array of source documents referenced
* `sessionId`: Optional session ID for conversation continuity

### Examples

**With explicit knowledgeBaseId:**

```typescript
import { retrieveAndGenerateFromKnowledgeBase } from '@minded-ai/mindedjs';

const result = await retrieveAndGenerateFromKnowledgeBase({
  knowledgeBaseId: 'kb-abc123',
  environment: 'production',
  query: 'Summarize the refund policy',
  numberOfResults: 5,
});

if (result.output) {
  console.log('Response:', result.output);

  // Process citations
  for (const citation of result.citations) {
    console.log('Cited text:', citation.generatedResponsePart.textResponsePart.text);

    for (const ref of citation.retrievedReferences) {
      console.log('  Source:', ref.location.s3Location.uri);
      console.log('  Content:', ref.content.text.substring(0, 100) + '...');
    }
  }
} else {
  console.log('No relevant documents found');
}
```

## Filtering

Both functions support metadata filters for precise document retrieval.

### Filter Types

```typescript
interface KnowledgeBaseFilter {
  equals?: { key: string; value: string };
  notEquals?: { key: string; value: string };
  greaterThan?: { key: string; value: string };
  lessThan?: { key: string; value: string };
  andAll?: KnowledgeBaseFilter[];
  orAll?: KnowledgeBaseFilter[];
}
```

### Filter Examples

```typescript
import { retrieveFromKnowledgeBase } from '@minded-ai/mindedjs';

// Filter by label1
const results = await retrieveFromKnowledgeBase({
  knowledgeBaseId: 'kb-abc123',
  environment: 'production',
  query: 'pricing information',
  filters: {
    equals: { key: 'label1', value: 'dept:sales' },
  },
});

// Combine multiple filters with andAll
const results2 = await retrieveFromKnowledgeBase({
  environment: 'production',
  query: 'pricing information',
  filters: {
    andAll: [
      { equals: { key: 'label1', value: 'dept:sales' } },
      { equals: { key: 'label2', value: 'lang:en' } }
    ],
  },
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.minded.com/sdk/knowledge-base-rag.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
