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

# Knowledge Bases

> Give your agents accurate, up-to-date answers by connecting them to your own documents

A knowledge base is a collection of documents your agent can search and reference during a live call. Instead of cramming every product detail into the system prompt, you store facts in a knowledge base and let the agent retrieve exactly what it needs, exactly when the caller asks.

## How it works

When a caller asks a question, the agent runs a semantic search across every source in the connected knowledge bases. It retrieves the most relevant passages and incorporates them into its response in real time — without any scripted branching or manual lookup logic on your part.

This means your agent can accurately answer questions about your pricing, product catalogue, return policy, or support runbook without you having to anticipate every possible question in advance.

## When to use a knowledge base

<Columns>
  <Card title="Good fits for a KB" icon="circle-check">
    * Product documentation and FAQs
    * Pricing sheets and feature comparisons
    * Support runbooks and troubleshooting guides
    * Policy documents (refunds, shipping, compliance)
    * Onboarding materials and how-to guides
  </Card>

  <Card title="Better suited to the system prompt" icon="sliders">
    * Agent persona and tone of voice
    * Call flow instructions ("always confirm the caller's name")
    * Business rules ("never quote pricing without checking availability")
    * Escalation conditions
    * Tool-use instructions
  </Card>
</Columns>

## KB vs system prompt

The **system prompt** contains static instructions that shape how your agent behaves. It is always present, never searched.

The **knowledge base** contains dynamic, searchable content that the agent pulls from on demand. It does not affect agent behaviour directly — it supplies facts.

<Note>
  A good rule of thumb: put *how to behave* in the prompt, put *what to know* in the knowledge base.
</Note>

## Source types

Each knowledge base is made up of one or more sources. Truedy supports two source types:

| Kind       | Description                                                               |
| ---------- | ------------------------------------------------------------------------- |
| `document` | A PDF, DOCX, TXT, or Markdown file you upload (max 50 MB, base64-encoded) |
| `web`      | One or more publicly accessible URLs that Truedy crawls and indexes       |

Web sources can be configured with a crawl depth so Truedy follows links and indexes linked pages automatically.

## Source status lifecycle

After you add a source, Truedy processes it asynchronously. The `status` field on a source follows this lifecycle:

```
pending → processing → ready
                    ↘ failed
```

Your agent can only retrieve content from sources in the `ready` state. Poll `GET /knowledge-bases/{id}/sources` to check when processing is complete.

## Connecting multiple knowledge bases

A single agent can be connected to multiple knowledge bases. All connected KBs are searched together at call time — the agent sees one unified search space across all of them.

This lets you modularise your content: a general FAQ KB, a product-specific KB, and a region-specific pricing KB can all coexist and be mixed across different agents as needed.

***

## End-to-end example

The following walkthrough creates a knowledge base, adds two sources, and attaches it to an agent.

### Step 1 — Create the knowledge base

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST https://api.truedy.ai/api/public/v1/knowledge-bases \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Product FAQ"
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.truedy.ai/api/public/v1/knowledge-bases",
      headers={"Authorization": "Bearer YOUR_API_KEY"},
      json={"name": "Product FAQ"},
  )
  kb = response.json()
  kb_id = kb["id"]
  print(f"Knowledge base created: {kb_id}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    "https://api.truedy.ai/api/public/v1/knowledge-bases",
    {
      method: "POST",
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name: "Product FAQ" }),
    }
  );
  const kb = await response.json();
  const kbId = kb.id;
  console.log("Knowledge base created:", kbId);
  ```
</CodeGroup>

**Response**

```json theme={null}
{
  "id": "kb_01J8X...",
  "name": "Product FAQ",
  "created_at": "2025-09-12T10:00:00Z",
  "source_count": 0
}
```

### Step 2 — Add a document source

Upload a file as base64-encoded content. Here we encode a plain text file. The same pattern works for PDF, DOCX, or Markdown.

<CodeGroup>
  ```bash curl theme={null}
  # Encode your file to base64 first:
  #   base64 -i refund_policy.txt
  # Then paste the output into the "data" field below.

  curl -X POST https://api.truedy.ai/api/public/v1/knowledge-bases/kb_01J8X.../sources/document \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Refund Policy",
      "file": {
        "filename": "refund_policy.txt",
        "content_type": "text/plain",
        "data": "Q3VzdG9tZXJzIG1heSByZXF1ZXN0IGEgZnVsbCByZWZ1bmQ..."
      }
    }'
  ```

  ```python Python theme={null}
  import base64

  content = (
      "Customers may request a full refund within 30 days of purchase. "
      "Refunds are processed within 5 business days to the original payment method. "
      "To initiate a refund, customers should contact support@example.com with their order number."
  )
  encoded = base64.b64encode(content.encode()).decode()

  source = requests.post(
      f"https://api.truedy.ai/api/public/v1/knowledge-bases/{kb_id}/sources/document",
      headers={"Authorization": "Bearer YOUR_API_KEY"},
      json={
          "name": "Refund Policy",
          "file": {
              "filename": "refund_policy.txt",
              "content_type": "text/plain",
              "data": encoded,
          },
      },
  ).json()
  print(f"Source added: {source['data']['id']} — status: {source['data']['status']}")
  ```

  ```javascript JavaScript theme={null}
  const content =
    "Customers may request a full refund within 30 days of purchase. " +
    "Refunds are processed within 5 business days. " +
    "Contact support@example.com with your order number.";
  const encoded = btoa(content);

  const res = await fetch(
    `https://api.truedy.ai/api/public/v1/knowledge-bases/${kbId}/sources/document`,
    {
      method: "POST",
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "Refund Policy",
        file: {
          filename: "refund_policy.txt",
          content_type: "text/plain",
          data: encoded,
        },
      }),
    }
  );
  const { data: source } = await res.json();
  console.log(`Source added: ${source.id} — status: ${source.status}`);
  ```
</CodeGroup>

### Step 3 — Add a web source

Provide one or more URLs. Truedy crawls them and indexes the text content.

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST https://api.truedy.ai/api/public/v1/knowledge-bases/kb_01J8X.../sources/web \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Pricing Page",
      "urls": ["https://www.example.com/pricing"],
      "max_depth": 1
    }'
  ```

  ```python Python theme={null}
  web_source = requests.post(
      f"https://api.truedy.ai/api/public/v1/knowledge-bases/{kb_id}/sources/web",
      headers={"Authorization": "Bearer YOUR_API_KEY"},
      json={
          "name": "Pricing Page",
          "urls": ["https://www.example.com/pricing"],
          "max_depth": 1,
      },
  ).json()
  print(f"Web source queued: {web_source['data']['id']}")
  ```

  ```javascript JavaScript theme={null}
  const res = await fetch(
    `https://api.truedy.ai/api/public/v1/knowledge-bases/${kbId}/sources/web`,
    {
      method: "POST",
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "Pricing Page",
        urls: ["https://www.example.com/pricing"],
        max_depth: 1,
      }),
    }
  );
  const { data: webSource } = await res.json();
  console.log(`Web source queued: ${webSource.id}`);
  ```
</CodeGroup>

<Note>
  Both source types move through `pending → processing → ready` asynchronously. Wait for `status: "ready"` before testing the agent. `max_depth: 0` indexes only the given URLs; `max_depth: 1` also follows one level of links from each page.
</Note>

### Step 4 — Attach the knowledge base to an agent

Pass the knowledge base ID in the `knowledge_bases` array when creating or updating your agent.

<CodeGroup>
  ```bash curl theme={null}
  curl -X PATCH https://api.truedy.ai/api/public/v1/agents/YOUR_AGENT_ID \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "knowledge_bases": ["kb_01J8X..."]
    }'
  ```

  ```python Python theme={null}
  requests.patch(
      "https://api.truedy.ai/api/public/v1/agents/YOUR_AGENT_ID",
      headers={"Authorization": "Bearer YOUR_API_KEY"},
      json={"knowledge_bases": [kb_id]},
  )
  print("Agent updated with knowledge base.")
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://api.truedy.ai/api/public/v1/agents/YOUR_AGENT_ID", {
    method: "PATCH",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ knowledge_bases: [kbId] }),
  });
  console.log("Agent updated with knowledge base.");
  ```
</CodeGroup>

Your agent will now search the "Product FAQ" knowledge base on every call.

***

## Next steps

<Card title="Managing KB Sources" icon="file-lines" href="/guides/managing-kb-sources">
  Add, update, and remove sources — including file uploads and URL re-crawls.
</Card>
