> For the complete documentation index, see [llms.txt](https://docs.meganova.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.meganova.ai/libra-os/use-cases/document-qa-copilot.md).

# Document Q\&A Copilot

Build a copilot that answers grounded, cited questions over your own uploaded documents — manuals, contracts, handbooks, research PDFs — without ever fabricating a claim it cannot find in the source material.

Libra OS delivers this as a **persona bound to a knowledge collection**. You upload documents once; every question retrieves the relevant passages, and the persona writes an answer that cites exactly where it looked. Ask a question the documents do not cover and the copilot says so rather than guessing.

> **Runnable version:** a self-contained implementation (ingest + `knowledge_gate` persona + grounded/refusal questions) lives in the cookbook: [`nova-os-cookbook/document-qa`](https://github.com/libraos/cookbook/tree/main/document-qa).

***

## When to build this vs a raw chatbot

A raw chatbot (model only, no retrieval) is appropriate when you want a general assistant that draws on training-data knowledge. A document Q\&A copilot is the right choice when:

* **Answers must come from your documents, not training data.** Legal agreements, internal policies, proprietary research — the model has not seen these and must not invent them.
* **Every claim must be traceable.** A cited `Source:` reference lets the reader verify the answer in the original document rather than trust the model blindly.
* **The document corpus changes.** You upload a revised handbook today; questions answered tomorrow reflect the new version automatically — no retraining, no prompt-stuffing.
* **You need to prevent fabrication.** The system-prompt instruction "answer only from the provided documents" combined with retrieval grounding eliminates the class of hallucinations that come from confident-sounding guesswork.
* **You want per-user or per-collection scoping.** Each collection is isolated; a user bound to `handbook-kb` cannot inadvertently retrieve from `legal-kb`.

If a question genuinely spans everything a general-purpose model already knows (coding help, grammar, arithmetic), a raw chatbot is simpler. If correctness is load-bearing and you own the authoritative source, build the copilot.

***

## How it works

Libra OS wires three capabilities together:

1. **Knowledge collection** — a named, indexed store of your documents. Chunks are embedded and searched at query time.
2. **Persona** — an agent that has `knowledge_bindings` pointing at the collection; before answering, the persona retrieves the most relevant chunks and receives them as grounded context.
3. **Grounding field** — every chat response carries a `grounding` field (`grounded`, `ungrounded_refusal`, `degraded`) so you can verify the copilot is behaving correctly in production.

***

## Build it: step by step

### Step 1 — Create the knowledge collection

A collection must exist before you add content to it. Uploading to an unknown collection name silently lands in the root collection and is never bindable or searchable.

```bash
curl -X POST "https://demo.meganova.app/api/knowledge/collections" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "handbook-kb",
    "description": "Employee handbook",
    "access_level": "private"
  }'
```

`access_level: "private"` scopes the collection to your tenant. Run this once per collection; re-running with the same `name` after it exists has no effect.

### Step 2 — Add content

Two options; both chunk, embed, and index automatically.

**Option A — ingest text directly (JSON):**

```bash
curl -X POST "https://demo.meganova.app/v1/managed/knowledge/ingest" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "collection": "handbook-kb",
    "title": "Vacation policy",
    "content": "New hires receive 15 days of paid vacation per year, accruing from their start date. Unused days may be carried over up to a maximum of 5..."
  }'
```

**Option B — upload a file (multipart):**

```bash
curl -X POST "https://demo.meganova.app/v1/managed/documents/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "collection_id=handbook-kb" \
  -F "file=@employee-handbook.pdf"
```

> **Note:** The multipart field is `collection_id`, not `collection`. Scanned or image-only PDFs are automatically OCR'd before indexing — you do not need to pre-process them.

Repeat for every document you want the copilot to cover. You can add more documents at any time; the persona picks up new content on the next question without any configuration change.

### Step 3 — Verify indexing

Before binding a persona, confirm the content is searchable:

```bash
curl -X POST "https://demo.meganova.app/v1/managed/knowledge/search" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "collection": "handbook-kb",
    "query": "vacation days new hires",
    "top_k": 3
  }'
```

The response returns matching chunks with scores. If you see zero results for a query that should match, the document may still be processing — wait a few seconds and retry. If results remain empty, check that the upload returned a 200 and that the `collection_id` matched exactly.

### Step 4 — Register the Q\&A persona

```bash
curl -X POST "https://demo.meganova.app/v1/agents" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -d '{
    "name": "handbook-qa",
    "agent_type": "persona",
    "model": "gemini/gemini-2.5-flash",
    "system": "Answer only from the provided documents. Cite the source after each claim using [Source: <title>]. If the documents do not cover the question, say so clearly — never invent an answer.",
    "capabilities": ["document_search"],
    "knowledge_bindings": ["handbook-kb"]
  }'
```

Key fields:

| Field                | Value                                 | Why                                                                                                                     |
| -------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `model`              | `gemini/gemini-2.5-flash`             | Fast, cost-effective for retrieval-grounded Q\&A. Gateway models need a `<provider>/` prefix — bare names are rejected. |
| `system`             | Grounding instruction + citation rule | Sets the behavioral contract: answer from documents, cite, admit gaps.                                                  |
| `capabilities`       | `["document_search"]`                 | Activates the retrieval path for this persona.                                                                          |
| `knowledge_bindings` | `["handbook-kb"]`                     | Scopes retrieval to this collection only.                                                                               |

Alternatively, drop a markdown file with YAML frontmatter into your agents directory and Libra OS hot-reloads it:

```yaml
---
name: handbook-qa
agent_type: persona
model: gemini/gemini-2.5-flash
capabilities:
  - document_search
knowledge_bindings:
  - handbook-kb
---

Answer only from the provided documents. Cite the source after each claim
using [Source: <title>]. If the documents do not cover the question, say so
clearly — never invent an answer.
```

### Step 5 — Ask a question

```bash
curl -X POST "https://demo.meganova.app/agents/v1/$API_KEY/chat" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "How many vacation days do new hires get?"}
    ]
  }'
```

A grounded response looks like:

```json
{
  "content": "New hires receive 15 days of paid vacation per year, accruing from their start date [Source: Vacation policy]. Unused days may be carried over up to a maximum of 5 days.",
  "grounding": "grounded"
}
```

The `grounding: "grounded"` field confirms that retrieved chunks were present and used. `ungrounded_refusal` means the persona acknowledged it could not find an answer — which is correct behavior for an out-of-scope question, not an error.

***

## Faster answers with `knowledge_gate`

For high-volume document Q\&A where most questions have a clear answer in the collection, enable `knowledge_gate` on the persona. When the bound-collection retrieval returns a chunk whose score clears the threshold, a single cheap call answers directly and skips the full planning pipeline — typically much lower latency.

Update the persona:

```bash
curl -X PUT "https://demo.meganova.app/v1/agents/handbook-qa" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -d '{
    "knowledge_gate": true,
    "knowledge_gate_min_score": 0.45
  }'
```

`knowledge_gate_min_score` (default `0.45`) is the retrieval confidence floor. If the top chunk scores below this — meaning the collection probably does not cover the question — the gate fails open to the full path. You do not need to tune this for most document Q\&A use cases; the default works well for corporate documents and manuals.

> **Note:** `knowledge_gate` requires real `knowledge_bindings`. The wildcard `["*"]` combined with `knowledge_gate` is not supported — bind a specific collection.

***

## Verify correctness

Run these checks before exposing the copilot to users.

**Grounding is present.** Ask a question that is definitely covered by an uploaded document and confirm `grounding: "grounded"` in the response. If you see `grounding: "degraded"`, retrieval ran but timed out or errored — the persona injected a note rather than answering ungrounded.

**Citations appear.** Confirm the response contains a `[Source: ...]` reference. If citations are missing, tighten the system prompt: "You MUST cite the source document after each factual claim."

**Out-of-scope questions are refused.** Ask something you know is not in any document ("What is the capital of France?"). The response must say the documents do not cover it — not invent an answer. A fabricated response means the system prompt grounding rule needs to be stronger, or the model tier should be swapped for one that follows instructions more reliably.

**Collection scoping.** If you have multiple collections, confirm that a persona bound to `handbook-kb` cannot retrieve content from a different collection. The binding is enforced server-side; there is nothing for the user to bypass. Verify by asking a question whose answer exists only in the other collection and confirming no relevant content appears in the response.

***

## Improve retrieval quality

### Coverage of multi-document questions

The default retrieval returns 5 chunks per turn. For handbooks that span multiple PDFs — a general policy guide, a department-specific addendum, a benefits summary — a question may need passages from more than one document. Raise the operator-level default:

```
LIBRA_OS_RAG_TOP_K=12
```

\~7 chunks per document means 12 covers a two-document question comfortably. The trade-off is more tokens in each prompt, slightly higher latency and cost per turn. For a pure Q\&A copilot (no agentic loop, no tool calls), the latency impact is small.

### Document quality matters more than chunk count

Retrieval is only as good as the source text. Scanned PDFs with poor OCR, documents with heavy tables-as-images, or files with proprietary encoding produce low-quality chunks that score poorly even on relevant queries. The highest-leverage improvement is usually source quality:

* Prefer text-native PDFs over scanned images where possible.
* For scanned documents, the built-in OCR handles typical office scans well; test with a search query after upload.
* Split very large documents (400+ pages) into topic-scoped files — a 5-page benefits summary retrieves more precisely than a 300-page combined handbook where benefits are on page 247.

### Lower the similarity threshold for broad corpora

If a collection covers many loosely related topics (a general policy library rather than a single handbook), the default vector similarity threshold may filter out relevant chunks that use different vocabulary than the query. Lower it:

```
LIBRA_OS_RAG_VECTOR_THRESHOLD=0.15
```

This trades precision for recall — more candidates enter the pool, and the model sees a wider set of potentially relevant chunks. Combine with a higher `top_k` for best coverage.

### Disable the post-retrieval LLM filter for deterministic results

By default, retrieved chunks pass through an LLM relevance filter before injection. For document Q\&A with a tight, well-named collection, this filter sometimes discards correct chunks due to the nondeterministic nature of a YES/NO LLM gate. Disable it for more consistent results:

```
LIBRA_OS_RAG_LLM_FILTER=false
```

All `top_k` chunks survive and are injected deterministically. The persona's system-prompt grounding instruction then selects which chunks to cite — a more controllable path than a hidden filter.

***

## Per-user scoping

If each user should only retrieve their own documents (a legal copilot where each client's files must stay private), use per-user collections combined with the identity headers:

```bash
# Create a per-user collection (once, at onboarding)
curl -X POST "https://demo.meganova.app/api/knowledge/collections" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "client-1042-docs", "description": "Client 1042 files", "access_level": "private"}'

# Upload files into the per-user collection
curl -X POST "https://demo.meganova.app/v1/managed/documents/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "collection_id=client-1042-docs" \
  -F "file=@agreement-v3.pdf"

# Chat with identity headers so the session is attributable
curl -X POST "https://demo.meganova.app/agents/v1/$API_KEY/chat" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "X-Platform-User: my-app" \
  -H "X-End-User: client-1042" \
  -d '{"messages":[{"role":"user","content":"What are the indemnification limits in our agreement?"}]}'
```

`X-Platform-User` identifies your application; `X-End-User` identifies the end user within it. These headers appear in the audit log for every turn, enabling per-user call history without any additional instrumentation.

For a shared copilot where all users read the same documents (an internal handbook everyone can access), a single collection with `access_level: "private"` is sufficient — just omit the per-user collection split.

***

## Next steps

* Add a tool so the copilot can do more than answer: search a live database, open a support ticket, or draft a document based on what it found — [Customer Support Agent](https://docs.meganova.ai/libra-os/use-cases/customer-support-agent.md).
* Run research across a web corpus instead of (or in addition to) uploaded documents: [Legal Research Assistant](https://docs.meganova.ai/libra-os/use-cases/legal-research-assistant.md).
* See the full retrieval tuning surface, model tiers, and grounding options: [Capabilities](https://docs.meganova.ai/libra-os/capabilities.md).
