> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zavu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Knowledge Base

> Upload documents and FAQs so your AI agent can answer questions accurately

# Knowledge Base

A Knowledge Base lets your AI agent answer questions using your own documents. Upload FAQs, product docs, policies, or any text content, and the agent will search for relevant information when responding to customers.

## What is a Knowledge Base?

A **Knowledge Base** is a collection of documents that your agent can reference. When a customer asks a question, the agent:

1. Searches the knowledge base for relevant content
2. Retrieves the most relevant chunks
3. Includes that context in its prompt
4. Generates an informed response

This approach is called **RAG** (Retrieval Augmented Generation).

## Use Cases

| Use Case                | Documents to Upload                             |
| ----------------------- | ----------------------------------------------- |
| **Customer Support**    | FAQs, troubleshooting guides, help articles     |
| **Product Information** | Product specs, features, pricing                |
| **Policy Questions**    | Terms of service, privacy policy, refund policy |
| **Technical Support**   | Documentation, API guides, tutorials            |
| **Sales**               | Product comparisons, case studies, benefits     |

## Via Dashboard

<Steps>
  <Step title="Navigate to Knowledge Bases">
    Go to **Senders** > select your sender > **Agent** tab > **Knowledge Bases** section.
  </Step>

  <Step title="Create Knowledge Base">
    Click **Create Knowledge Base** and enter:

    * **Name**: A descriptive name (e.g., "Product FAQs")
    * **Description**: What this knowledge base contains
  </Step>

  <Step title="Add Documents">
    Click **Add Document** and choose how to add content:

    * **Text**: Paste text content directly
    * **Markdown**: Upload `.md` files
    * **PDF**: Upload PDF documents
    * **URL**: Import content from a webpage
  </Step>

  <Step title="Wait for Processing">
    Documents are automatically chunked and embedded. This takes a few seconds for small documents, longer for large PDFs.

    <Info>
      You'll see a processing indicator while chunks are being created. The agent can only use fully processed documents.
    </Info>
  </Step>

  <Step title="Verify">
    Check the document list to see:

    * **Chunk Count**: Number of searchable chunks created
    * **Processing Status**: Whether the document is ready
  </Step>
</Steps>

## Via API

### Create Knowledge Base

<CodeGroup>
  ```typescript TypeScript theme={null}
  import Zavudev from "@zavudev/sdk";

  const zavu = new Zavudev({
    apiKey: process.env["ZAVUDEV_API_KEY"],
  });

  const kb = await zavu.senders.agent.knowledgeBases.create("sender_abc123", {
    name: "Product FAQs",
    description: "Frequently asked questions about our products",
  });

  console.log("Knowledge Base created:", kb.id);
  ```

  ```python Python theme={null}
  import os
  from zavudev import Zavudev

  zavu = Zavudev(
      api_key=os.environ.get("ZAVUDEV_API_KEY"),
  )

  kb = zavu.senders.agent.knowledge_bases.create(
      "sender_abc123",
      name="Product FAQs",
      description="Frequently asked questions about our products",
  )

  print(f"Knowledge Base created: {kb.id}")
  ```

  ```ruby Ruby theme={null}
  require "zavudev"

  client = Zavudev::Client.new(api_key: ENV["ZAVUDEV_API_KEY"])

  kb = client.senders.agent.knowledge_bases.create("sender_abc123",
    name: "Product FAQs",
    description: "Frequently asked questions about our products"
  )

  puts "Knowledge Base created: #{kb.id}"
  ```

  ```go Go theme={null}
  kb, _ := client.Senders.Agent.KnowledgeBases.Create(context.TODO(), "sender_abc123", zavudev.KnowledgeBaseCreateParams{
  	Name:        zavudev.String("Product FAQs"),
  	Description: zavudev.String("Frequently asked questions about our products"),
  })

  fmt.Printf("Knowledge Base created: %s\n", kb.ID)
  ```

  ```php PHP theme={null}
  $kb = $client->senders->agent->knowledgeBases->create('sender_abc123', [
      'name' => 'Product FAQs',
      'description' => 'Frequently asked questions about our products',
  ]);

  echo "Knowledge Base created: {$kb->id}\n";
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.zavu.dev/v1/senders/sender_abc123/agent/knowledge-bases \
    -H "Authorization: Bearer $ZAVU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Product FAQs",
      "description": "Frequently asked questions about our products"
    }'
  ```
</CodeGroup>

### Add Document

<CodeGroup>
  ```typescript TypeScript theme={null}
  const document = await zavu.senders.agent.knowledgeBases.documents.create(
    "sender_abc123",
    "kb_xyz789",
    {
      title: "Return Policy",
      content: `# Return Policy

  ## 30-Day Returns
  All products can be returned within 30 days of purchase for a full refund.

  ## Conditions
  - Items must be unused and in original packaging
  - Original receipt required
  - Shipping costs are non-refundable

  ## How to Return
  1. Contact support@example.com
  2. Receive return shipping label
  3. Ship item within 7 days
  4. Refund processed within 5 business days

  ## Exceptions
  - Final sale items cannot be returned
  - Custom orders are non-refundable
  `,
    }
  );

  console.log("Document added:", document.id);
  ```

  ```python Python theme={null}
  document = zavu.senders.agent.knowledge_bases.documents.create(
      "sender_abc123",
      "kb_xyz789",
      title="Return Policy",
      content="""# Return Policy

  ## 30-Day Returns
  All products can be returned within 30 days of purchase for a full refund.

  ## Conditions
  - Items must be unused and in original packaging
  - Original receipt required
  - Shipping costs are non-refundable

  ## How to Return
  1. Contact support@example.com
  2. Receive return shipping label
  3. Ship item within 7 days
  4. Refund processed within 5 business days

  ## Exceptions
  - Final sale items cannot be returned
  - Custom orders are non-refundable
  """,
  )

  print(f"Document added: {document.id}")
  ```

  ```ruby Ruby theme={null}
  document = client.senders.agent.knowledge_bases.documents.create("sender_abc123", "kb_xyz789",
    title: "Return Policy",
    content: "# Return Policy\n\n## 30-Day Returns\nAll products can be returned within 30 days of purchase for a full refund.\n\n## Conditions\n- Items must be unused and in original packaging\n- Original receipt required\n- Shipping costs are non-refundable\n\n## How to Return\n1. Contact support@example.com\n2. Receive return shipping label\n3. Ship item within 7 days\n4. Refund processed within 5 business days\n\n## Exceptions\n- Final sale items cannot be returned\n- Custom orders are non-refundable"
  )

  puts "Document added: #{document.id}"
  ```

  ```go Go theme={null}
  document, _ := client.Senders.Agent.KnowledgeBases.Documents.Create(context.TODO(), "sender_abc123", "kb_xyz789", zavudev.DocumentCreateParams{
  	Title:   zavudev.String("Return Policy"),
  	Content: zavudev.String("# Return Policy\n\n## 30-Day Returns\nAll products can be returned within 30 days of purchase for a full refund.\n\n## Conditions\n- Items must be unused and in original packaging\n- Original receipt required\n- Shipping costs are non-refundable\n\n## How to Return\n1. Contact support@example.com\n2. Receive return shipping label\n3. Ship item within 7 days\n4. Refund processed within 5 business days\n\n## Exceptions\n- Final sale items cannot be returned\n- Custom orders are non-refundable"),
  })

  fmt.Printf("Document added: %s\n", document.ID)
  ```

  ```php PHP theme={null}
  $document = $client->senders->agent->knowledgeBases->documents->create('sender_abc123', 'kb_xyz789', [
      'title' => 'Return Policy',
      'content' => "# Return Policy\n\n## 30-Day Returns\nAll products can be returned within 30 days of purchase for a full refund.\n\n## Conditions\n- Items must be unused and in original packaging\n- Original receipt required\n- Shipping costs are non-refundable\n\n## How to Return\n1. Contact support@example.com\n2. Receive return shipping label\n3. Ship item within 7 days\n4. Refund processed within 5 business days\n\n## Exceptions\n- Final sale items cannot be returned\n- Custom orders are non-refundable",
  ]);

  echo "Document added: {$document->id}\n";
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.zavu.dev/v1/senders/sender_abc123/agent/knowledge-bases/kb_xyz789/documents \
    -H "Authorization: Bearer $ZAVU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "title": "Return Policy",
      "content": "# Return Policy\n\n## 30-Day Returns\nAll products can be returned within 30 days..."
    }'
  ```
</CodeGroup>

### List Knowledge Bases

<CodeGroup>
  ```typescript TypeScript theme={null}
  const kbs = await zavu.senders.agent.knowledgeBases.list("sender_abc123");

  for (const kb of kbs.items) {
    console.log(`${kb.name}: ${kb.documentCount} documents, ${kb.totalChunks} chunks`);
  }
  ```

  ```python Python theme={null}
  kbs = zavu.senders.agent.knowledge_bases.list("sender_abc123")

  for kb in kbs.items:
      print(f"{kb.name}: {kb.document_count} documents, {kb.total_chunks} chunks")
  ```

  ```ruby Ruby theme={null}
  kbs = client.senders.agent.knowledge_bases.list("sender_abc123")

  kbs.items.each do |kb|
    puts "#{kb.name}: #{kb.document_count} documents, #{kb.total_chunks} chunks"
  end
  ```

  ```go Go theme={null}
  kbs, _ := client.Senders.Agent.KnowledgeBases.List(context.TODO(), "sender_abc123", zavudev.KnowledgeBaseListParams{})

  for _, kb := range kbs.Items {
  	fmt.Printf("%s: %d documents, %d chunks\n", kb.Name, kb.DocumentCount, kb.TotalChunks)
  }
  ```

  ```php PHP theme={null}
  $kbs = $client->senders->agent->knowledgeBases->list('sender_abc123');

  foreach ($kbs->items as $kb) {
      echo "{$kb->name}: {$kb->documentCount} documents, {$kb->totalChunks} chunks\n";
  }
  ```

  ```bash cURL theme={null}
  curl https://api.zavu.dev/v1/senders/sender_abc123/agent/knowledge-bases \
    -H "Authorization: Bearer $ZAVU_API_KEY"
  ```
</CodeGroup>

### List Documents

<CodeGroup>
  ```typescript TypeScript theme={null}
  const docs = await zavu.senders.agent.knowledgeBases.documents.list(
    "sender_abc123",
    "kb_xyz789"
  );

  for (const doc of docs.items) {
    console.log(`${doc.title}: ${doc.chunkCount} chunks`);
  }
  ```

  ```python Python theme={null}
  docs = zavu.senders.agent.knowledge_bases.documents.list(
      "sender_abc123",
      "kb_xyz789"
  )

  for doc in docs.items:
      print(f"{doc.title}: {doc.chunk_count} chunks")
  ```

  ```ruby Ruby theme={null}
  docs = client.senders.agent.knowledge_bases.documents.list("sender_abc123", "kb_xyz789")

  docs.items.each do |doc|
    puts "#{doc.title}: #{doc.chunk_count} chunks"
  end
  ```

  ```go Go theme={null}
  docs, _ := client.Senders.Agent.KnowledgeBases.Documents.List(context.TODO(), "sender_abc123", "kb_xyz789", zavudev.DocumentListParams{})

  for _, doc := range docs.Items {
  	fmt.Printf("%s: %d chunks\n", doc.Title, doc.ChunkCount)
  }
  ```

  ```php PHP theme={null}
  $docs = $client->senders->agent->knowledgeBases->documents->list('sender_abc123', 'kb_xyz789');

  foreach ($docs->items as $doc) {
      echo "{$doc->title}: {$doc->chunkCount} chunks\n";
  }
  ```

  ```bash cURL theme={null}
  curl https://api.zavu.dev/v1/senders/sender_abc123/agent/knowledge-bases/kb_xyz789/documents \
    -H "Authorization: Bearer $ZAVU_API_KEY"
  ```
</CodeGroup>

### Delete Document

<CodeGroup>
  ```typescript TypeScript theme={null}
  await zavu.senders.agent.knowledgeBases.documents.delete(
    "sender_abc123",
    "kb_xyz789",
    "doc_abc123"
  );
  ```

  ```python Python theme={null}
  zavu.senders.agent.knowledge_bases.documents.delete(
      "sender_abc123",
      "kb_xyz789",
      "doc_abc123"
  )
  ```

  ```ruby Ruby theme={null}
  client.senders.agent.knowledge_bases.documents.delete("sender_abc123", "kb_xyz789", "doc_abc123")
  ```

  ```go Go theme={null}
  client.Senders.Agent.KnowledgeBases.Documents.Delete(context.TODO(), "sender_abc123", "kb_xyz789", "doc_abc123")
  ```

  ```php PHP theme={null}
  $client->senders->agent->knowledgeBases->documents->delete('sender_abc123', 'kb_xyz789', 'doc_abc123');
  ```

  ```bash cURL theme={null}
  curl -X DELETE https://api.zavu.dev/v1/senders/sender_abc123/agent/knowledge-bases/kb_xyz789/documents/doc_abc123 \
    -H "Authorization: Bearer $ZAVU_API_KEY"
  ```
</CodeGroup>

## How RAG Works

```
Customer: "What's your return policy?"
                    |
                    v
            +------------------+
            | Embed Question   |
            | Create vector    |
            +------------------+
                    |
                    v
            +------------------+
            | Vector Search    |
            | Find similar     |
            | chunks           |
            +------------------+
                    |
                    v
            +------------------+
            | Retrieve Top     |
            | Chunks (e.g., 3) |
            +------------------+
                    |
                    v
            +------------------+
            | Inject Context   |
            | into LLM Prompt  |
            +------------------+
                    |
                    v
            +------------------+
            | Generate Answer  |
            | with Context     |
            +------------------+
                    |
                    v
Customer: "You can return any item within
           30 days for a full refund. Items
           must be unused and in original
           packaging. Contact support@..."
```

### Processing Steps

1. **Chunking**: Documents are split into smaller pieces (\~500-1000 tokens each)
2. **Embedding**: Each chunk is converted to a vector using an embedding model
3. **Indexing**: Vectors are stored for fast similarity search
4. **Retrieval**: When a question arrives, we find the most similar chunks
5. **Generation**: Retrieved chunks are included in the LLM prompt as context

## Supported File Types

| Type         | Extensions   | Max Size | Notes                     |
| ------------ | ------------ | -------- | ------------------------- |
| **Text**     | Direct input | 100 KB   | Plain text content        |
| **Markdown** | `.md`        | 100 KB   | Preserves formatting      |
| **PDF**      | `.pdf`       | 10 MB    | Text extraction only      |
| **URL**      | Web pages    | -        | Fetches and extracts text |

<Warning>
  PDF processing extracts text only. Images, charts, and tables within PDFs are not processed.
</Warning>

## Document Limits

| Limit                        | Value  |
| ---------------------------- | ------ |
| Documents per Knowledge Base | 100    |
| Knowledge Bases per Agent    | 10     |
| Max document size (text/md)  | 100 KB |
| Max document size (PDF)      | 10 MB  |
| Max chunks per document      | 500    |

## Best Practices

<CardGroup cols={2}>
  <Card title="Structure Content" icon="list">
    Use headers, bullet points, and clear sections. Well-structured content creates better chunks.
  </Card>

  <Card title="Be Specific" icon="bullseye">
    Include specific answers to common questions. The more explicit, the better the retrieval.
  </Card>

  <Card title="Keep Current" icon="rotate">
    Update documents when information changes. Outdated content leads to incorrect answers.
  </Card>

  <Card title="Separate Topics" icon="folder-tree">
    Create separate documents for different topics. This improves retrieval accuracy.
  </Card>
</CardGroup>

### Content Writing Tips

**Good document structure:**

```markdown theme={null}
# Product Returns

## How long do I have to return an item?
You have 30 days from the delivery date to return any item for a full refund.

## What condition must items be in?
Items must be unused, unworn, and in original packaging with all tags attached.

## How do I start a return?
1. Email support@example.com with your order number
2. We'll send a prepaid return label within 24 hours
3. Ship the item within 7 days
4. Refund processes within 5 business days of receipt
```

**Poor document structure:**

```text theme={null}
Returns are processed within the timeframe specified in our terms. Contact support for assistance with any issues you may have regarding your order.
```

<Tip>
  Write documents as if you're answering specific customer questions. This makes retrieval more accurate.
</Tip>

## Example Documents

### FAQ Document

```markdown theme={null}
# Shipping FAQs

## How long does shipping take?
- Standard shipping: 5-7 business days
- Express shipping: 2-3 business days
- Same-day delivery: Available in select cities

## How much does shipping cost?
- Free shipping on orders over $50
- Standard shipping: $5.99
- Express shipping: $12.99

## Do you ship internationally?
Yes! We ship to over 50 countries. International shipping takes 7-14 business days.

## Can I track my order?
Yes, you'll receive a tracking number via email once your order ships.
```

### Product Document

```markdown theme={null}
# Pro Widget X100

## Overview
The Pro Widget X100 is our flagship widget designed for professional use.

## Specifications
- Weight: 2.5 lbs
- Dimensions: 10" x 6" x 4"
- Battery life: 12 hours
- Warranty: 2 years

## Features
- Wireless connectivity (Bluetooth 5.0 and WiFi)
- Water-resistant (IP67 rating)
- Voice control compatible

## Price
- Standard edition: $299
- Pro edition: $449 (includes accessories)

## Common Questions

### Is it compatible with Mac?
Yes, works with macOS 10.15 and later.

### Can I use it outdoors?
Yes, the IP67 rating means it's water and dust resistant.
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Setup Guide" icon="rocket" href="/guides/ai-agents/setup">
    Configure your AI agent settings
  </Card>

  <Card title="Add Tools" icon="wrench" href="/guides/ai-agents/tools">
    Let your agent execute actions
  </Card>

  <Card title="Create Flows" icon="diagram-project" href="/guides/ai-agents/flows">
    Build structured conversation paths
  </Card>

  <Card title="AI Agents Concept" icon="brain" href="/concepts/ai-agents">
    Learn how agents work under the hood
  </Card>
</CardGroup>
