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

# Knowledge Base & RAG - Voice Agent API

> Implement Retrieval Augmented Generation (RAG) for voice agents. Create knowledge bases, manage documents, and link external data to Voice.ai agents via REST

Create and manage knowledge bases for retrieval augmented generation (RAG) with your voice agents.

<Info>
  **Prerequisites**: [API key](/docs/guides/authentication)
</Info>

## Create a Knowledge Base

Create a knowledge base with documents that your agent can use for RAG. See the [Create Knowledge Base](/docs/api-reference/agent-knowledge-base/create-knowledge-base) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://dev.voice.ai/api/v1/knowledge-base/',
      headers={'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json'},
      json={
          'name': 'Product Information',
          'description': 'FAQ and product details',
          'documents': [
              {
                  'content': 'Our product supports voice cloning, text-to-speech, and real-time conversations.',
                  'metadata': {'source': 'product-docs.md', 'category': 'features'}
              },
              {
                  'content': 'Pricing starts at $0.01 per minute for voice calls.',
                  'metadata': {'source': 'pricing.md', 'category': 'pricing'}
              }
          ]
      }
  )

  kb_id = response.json()['kb_id']
  print(f'Created knowledge base: {kb_id}')
  ```

  ```bash cURL theme={null}
  curl -X POST "https://dev.voice.ai/api/v1/knowledge-base/" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Product Information",
      "description": "FAQ and product details",
      "documents": [
        {
          "content": "Our product supports voice cloning, text-to-speech, and real-time conversations.",
          "metadata": {"source": "product-docs.md", "category": "features"}
        },
        {
          "content": "Pricing starts at $0.01 per minute for voice calls.",
          "metadata": {"source": "pricing.md", "category": "pricing"}
        }
      ]
    }'
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch('https://dev.voice.ai/api/v1/knowledge-base/', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Product Information',
      description: 'FAQ and product details',
      documents: [
        {
          content: 'Our product supports voice cloning, text-to-speech, and real-time conversations.',
          metadata: { source: 'product-docs.md', category: 'features' }
        },
        {
          content: 'Pricing starts at $0.01 per minute for voice calls.',
          metadata: { source: 'pricing.md', category: 'pricing' }
        }
      ]
    })
  });

  const data = await response.json();
  console.log(`Created knowledge base: ${data.kb_id}`);
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "kb_id": 123,
  "name": "Product Information",
  "description": "FAQ and product details",
  "document_count": 2,
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

## List Knowledge Bases

Get all your knowledge bases with pagination support. See the [Knowledge Base List](/docs/api-reference/agent-knowledge-base/knowledge-base-list) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://dev.voice.ai/api/v1/knowledge-base/',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'page': 1, 'page_size': 10}
  )

  data = response.json()
  for kb in data['knowledge_bases']:
      print(f"{kb['name']} ({kb['document_count']} documents) - ID: {kb['kb_id']}")
  ```

  ```bash cURL theme={null}
  curl -X GET "https://dev.voice.ai/api/v1/knowledge-base/?page=1&page_size=10" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch('https://dev.voice.ai/api/v1/knowledge-base/?page=1&page_size=10', {
    method: 'GET',
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  const data = await response.json();
  data.knowledge_bases.forEach((kb: any) => {
    console.log(`${kb.name} (${kb.document_count} documents) - ID: ${kb.kb_id}`);
  });
  ```
</CodeGroup>

## Get Knowledge Base Details

Retrieve details for a specific knowledge base, including all documents. See the [Knowledge Base Details](/docs/api-reference/agent-knowledge-base/knowledge-base-details) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.get(
      f'https://dev.voice.ai/api/v1/knowledge-base/{kb_id}',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

  kb = response.json()
  print(f"Name: {kb['name']}")
  print(f"Documents: {kb['document_count']}")
  ```

  ```bash cURL theme={null}
  curl -X GET "https://dev.voice.ai/api/v1/knowledge-base/{kb_id}" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch(`https://dev.voice.ai/api/v1/knowledge-base/${kbId}`, {
    method: 'GET',
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  const kb = await response.json();
  console.log(`Name: ${kb.name}`);
  console.log(`Documents: ${kb.document_count}`);
  ```
</CodeGroup>

## Update a Knowledge Base

Update the name, description, or replace all documents in an existing knowledge base. **Note:** If you provide `documents`, they will replace ALL existing documents in the knowledge base. See the [Update Knowledge Base](/docs/api-reference/agent-knowledge-base/update-knowledge-base) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.put(
      f'https://dev.voice.ai/api/v1/knowledge-base/{kb_id}',
      headers={'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json'},
      json={
          'name': 'Updated Product Information',
          'description': 'Updated FAQ and product details',
          'documents': [
              {
                  'content': 'New feature: Real-time voice cloning is now available.',
                  'metadata': {'source': 'changelog.md'}
              }
          ]
      }
  )

  print(f"Updated: {response.json()['name']}")
  ```

  ```bash cURL theme={null}
  curl -X PUT "https://dev.voice.ai/api/v1/knowledge-base/{kb_id}" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Updated Product Information",
      "description": "Updated FAQ and product details",
      "documents": [
        {
          "content": "New feature: Real-time voice cloning is now available.",
          "metadata": {"source": "changelog.md"}
        }
      ]
    }'
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch(`https://dev.voice.ai/api/v1/knowledge-base/${kbId}`, {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Updated Product Information',
      description: 'Updated FAQ and product details',
      documents: [
        {
          content: 'New feature: Real-time voice cloning is now available.',
          metadata: { source: 'changelog.md' }
        }
      ]
    })
  });

  const data = await response.json();
  console.log(`Updated: ${data.name}`);
  ```
</CodeGroup>

## Assign Knowledge Base to Agent

Assign an existing knowledge base to an agent for RAG capabilities. See the [Assign Knowledge Base](/docs/api-reference/agent-knowledge-base/assign-knowledge-base) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.post(
      f'https://dev.voice.ai/api/v1/agent/{agent_id}/assign-knowledge-base',
      headers={'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json'},
      json={'kb_id': kb_id}
  )

  agent = response.json()
  print(f"Agent {agent['agent_id']} now uses knowledge base {agent['kb_id']}")
  ```

  ```bash cURL theme={null}
  curl -X POST "https://dev.voice.ai/api/v1/agent/{agent_id}/assign-knowledge-base" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "kb_id": 123
    }'
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch(`https://dev.voice.ai/api/v1/agent/${agentId}/assign-knowledge-base`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ kb_id: kbId })
  });

  const agent = await response.json();
  console.log(`Agent ${agent.agent_id} now uses knowledge base ${agent.kb_id}`);
  ```
</CodeGroup>

## Create Agent with Knowledge Base

You can create an agent and assign an existing knowledge base during agent creation.

<CodeGroup>
  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://dev.voice.ai/api/v1/agent/',
      headers={'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json'},
      json={
          'name': 'Support Agent',
          'config': {'prompt': 'You are a helpful support agent.'},
          'kb_id': kb_id
      }
  )

  agent = response.json()
  print(f"Created agent {agent['agent_id']} with knowledge base {agent['kb_id']}")
  ```

  ```bash cURL theme={null}
  curl -X POST "https://dev.voice.ai/api/v1/agent/" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Support Agent",
      "config": {"prompt": "You are a helpful support agent."},
      "kb_id": 123
    }'
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch('https://dev.voice.ai/api/v1/agent/', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Support Agent',
      config: { prompt: 'You are a helpful support agent.' },
      kb_id: kbId
    })
  });

  const agent = await response.json();
  console.log(`Created agent ${agent.agent_id} with knowledge base ${agent.kb_id}`);
  ```
</CodeGroup>

## Remove Knowledge Base from Agent

Unassign a knowledge base from an agent. See the [Unassign Knowledge Base](/docs/api-reference/agent-knowledge-base/unassign-knowledge-base) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  requests.delete(
      f'https://dev.voice.ai/api/v1/agent/{agent_id}/knowledge-base',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

  print('Knowledge base removed from agent')
  ```

  ```bash cURL theme={null}
  curl -X DELETE "https://dev.voice.ai/api/v1/agent/{agent_id}/knowledge-base" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```typescript TypeScript theme={null}
  await fetch(`https://dev.voice.ai/api/v1/agent/${agentId}/knowledge-base`, {
    method: 'DELETE',
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  console.log('Knowledge base removed from agent');
  ```
</CodeGroup>

## Delete a Knowledge Base

Permanently delete a knowledge base. **Note:** You must unassign it from all agents first. See the [Delete Knowledge Base](/docs/api-reference/agent-knowledge-base/delete-knowledge-base) endpoint for details.

<CodeGroup>
  ```python Python theme={null}
  import requests

  requests.delete(
      f'https://dev.voice.ai/api/v1/knowledge-base/{kb_id}',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

  print('Knowledge base deleted')
  ```

  ```bash cURL theme={null}
  curl -X DELETE "https://dev.voice.ai/api/v1/knowledge-base/{kb_id}" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```typescript TypeScript theme={null}
  await fetch(`https://dev.voice.ai/api/v1/knowledge-base/${kbId}`, {
    method: 'DELETE',
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  console.log('Knowledge base deleted');
  ```
</CodeGroup>

## Best Practices

* **Document Structure**: Use clear, concise content with relevant metadata for better retrieval
* **Knowledge Base Reuse**: The API automatically detects and reuses knowledge bases with identical content
* **Agent Assignment**: One knowledge base can be shared across multiple agents
* **Updates**: When updating documents, provide the complete set of documents you want in the knowledge base, as updates replace all existing documents

## Next Steps

* [Agent Quickstart](/docs/guides/voice-agents/quickstart) - Create your first agent
* [API Reference](/docs/api-reference) - Complete API reference
