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

# Knowledge bases

> Attach, load, and query knowledge bases linked to an agent.

Agents can have knowledge bases linked to them in the Workbench. From code, you can attach more, load the `KnowledgeBase` objects, or build a retriever callable for use as a framework retriever.

```python theme={"dark"}
agent = await agents.aget("agent-123")

# Inspect linked KBs
for kb_link in agent.knowledge_bases:
    print(kb_link.id)

# Load full KnowledgeBase objects
kbs = await agent.aget_knowledge_bases()
for kb in kbs:
    print(kb.name, kb.total_documents)
```

## `aget_knowledge_bases`

Load every `KnowledgeBase` linked to the agent, in parallel.

```python theme={"dark"}
kbs = await agent.aget_knowledge_bases()
```

### Returns `list[KnowledgeBase]`

A list of full `KnowledgeBase` objects. See [`KnowledgeBase`](/developers/sdk-reference/knowledge-bases/knowledge-base) for the methods you can call on each.

### Sync version

```python theme={"dark"}
kbs = agent.get_knowledge_bases()
```

## `attach_knowledge_base`

Link a knowledge base to the agent on the in-memory instance. Pass either a `KnowledgeBase` object or a knowledge-base ID.

```python theme={"dark"}
from xpander_sdk import KnowledgeBases

kb = await KnowledgeBases().aget("kb-456")
agent.attach_knowledge_base(knowledge_base=kb)

# or by id only
agent.attach_knowledge_base(knowledge_base_id="kb-456")
```

### Parameters

| Parameter           | Type            | Required | Description                 |
| ------------------- | --------------- | -------- | --------------------------- |
| `knowledge_base`    | `KnowledgeBase` | No       | A `KnowledgeBase` instance. |
| `knowledge_base_id` | `str`           | No       | Knowledge-base ID.          |

You must pass at least one of the two. If both are passed, `knowledge_base.id` is used.

<Note>
  `attach_knowledge_base` only updates the agent in memory. To persist the link, save the agent through the platform (e.g. via the API or the Workbench UI). The runtime instance will use the link for the current session, but it won't survive a re-load.
</Note>

## `knowledge_bases_retriever`

Returns a `search(query, agent=None, num_documents=5)` callable that searches every linked KB and returns top-N results sorted by score. This is the form Agno expects as a custom retriever.

```python theme={"dark"}
retriever = agent.knowledge_bases_retriever()

results = retriever(query="quarterly revenue", num_documents=10)
for r in results:
    print(r["score"], r["content"][:100])
```

### Returned callable signature

```python theme={"dark"}
def search(
    query: str,
    agent: Optional[Any] = None,    # ignored; for compat with framework retrievers
    num_documents: int = 5,
    **kwargs,
) -> list[dict] | None
```

| Parameter       | Type  | Default | Description                                                             |
| --------------- | ----- | ------- | ----------------------------------------------------------------------- |
| `query`         | `str` | –       | Search query.                                                           |
| `agent`         | `Any` | `None`  | Ignored. Present for compatibility with framework retriever signatures. |
| `num_documents` | `int` | `5`     | Top-K to return. If `0` is passed, defaults to `10`.                    |

Each result is a dict from `KnowledgeBaseSearchResult.model_dump()`:

```python theme={"dark"}
{"content": "...", "score": 0.86}
```

The retriever swallows errors and returns `[]` if the search fails: useful for embedding into framework pipelines that shouldn't crash on retrieval errors.

## Patterns

### Wire as the Agno knowledge

```python theme={"dark"}
from xpander_sdk import Backend
from agno.agent import Agent as AgnoAgent

agent = await agents.aget("agent-123")
backend = Backend()
args = await backend.aget_args(agent=agent)

# args["knowledge"] is already populated when the agent has KBs linked.
agno_agent = AgnoAgent(**args)
```

`Backend.aget_args` already wires the retriever for you: you don't usually need to call `knowledge_bases_retriever()` directly. Use it only when bypassing the Backend dispatcher.

### Add a KB on the fly

```python theme={"dark"}
from xpander_sdk import KnowledgeBases

kbs = KnowledgeBases()
new_kb = await kbs.acreate(name="Q4 reports", description="Quarterly earnings")

await new_kb.aadd_documents([
    "https://example.com/Q4-2024.pdf",
    "https://example.com/Q4-2025.pdf",
])

agent.attach_knowledge_base(knowledge_base=new_kb)
```

After `attach_knowledge_base`, `agent.aget_knowledge_bases()` includes the new KB in the list.
