> 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/customer-support-agent.md).

# Customer Support Agent

Build a support chatbot that answers product questions from your knowledge base, stays on topic, takes actions (such as generating a quote), and hands off gracefully when it cannot help — all as a single deployable persona.

This guide exercises the three levers from the [Use Cases overview](https://docs.meganova.ai/libra-os/use-cases.md): model tiers, grounding, and domain guardrails. By the end you'll have a deployable `support-agent` persona wired to a product knowledge collection, a quote tool, and the built-in AI Firewall.

> **Runnable version:** a self-contained implementation (KB ingest + persona + a Mode B order-lookup webhook + guardrails) lives in the cookbook: [`nova-os-cookbook/customer-support`](https://github.com/libraos/cookbook/tree/main/customer-support).

***

## Should you build this on Libra OS?

Libra OS fits support chat well when you have:

* **High volume of repetitive queries** — the same "how do I…" or "what does X include?" asked hundreds of times a day.
* **A product knowledge base** — manuals, FAQs, pricing sheets, spec sheets you want the agent to read rather than hallucinate from.
* **24/7 availability** — no staffing ramp required; the persona is always on.
* **Consistent brand voice** — you control the persona's tone and guardrails once, and every response inherits them.
* **Multilingual volume** — the underlying model handles the language; your knowledge and persona instructions stay in one place.
* **Action requirements** — generating a quote, looking up an order, opening a ticket — tasks that go beyond a static FAQ but don't need a human every time.

If queries require deep judgment, sensitive negotiation, or access to systems that cannot expose a webhook, plan for escalation (covered in [Improve performance](#improve-performance) below) rather than full automation.

***

## Define your ideal interaction

Map the happy path before you configure anything. For an automotive insurance quote bot:

1. **Greet.** The agent introduces itself and asks how it can help.
2. **Answer a product question.** "What does your comprehensive cover?" — answered from the uploaded policy document.
3. **Stay on topic.** Off-topic questions ("who won the Premier League?") get a polite redirect.
4. **Collect the required info.** The agent asks for make, model, year, mileage, and driver age.
5. **Call the quote tool.** Libra OS calls your `get_quote` webhook with those fields; the webhook returns a price.
6. **Present the quote.** The agent relays the result in plain language, citing the retrieved coverage details.
7. **Follow-up.** "Is third-party cover cheaper?" — answered from knowledge, keeping the session alive.
8. **Escalate if needed.** Complaint or out-of-scope: the agent offers to open a ticket or connect to a human.

***

## Break the interaction into tasks

| Task                     | Libra OS mechanism                                               |
| ------------------------ | ---------------------------------------------------------------- |
| Greet and guide          | Persona system prompt — opening message instructions             |
| Answer product questions | Knowledge collection bound to the persona (`knowledge_bindings`) |
| Stay on topic            | Guardrail instructions in the system prompt + AI Firewall        |
| Generate a quote         | Custom tool (`get_quote`) with a webhook callback                |
| Escalate                 | Custom `escalate` tool that POSTs to your ticketing system       |

***

## Establish success criteria

Define measurable targets before you build so you know when you're done.

| Metric                | What it measures                                                 | Target                                  |
| --------------------- | ---------------------------------------------------------------- | --------------------------------------- |
| Query comprehension   | Does the agent correctly identify what the user is asking?       | ≥ 95 % on a held-out set                |
| Response relevance    | Does the reply address the question, not a different one?        | ≥ 90 % grounded response rate           |
| Response accuracy     | Are factual claims traceable to the knowledge source?            | 0 fabricated policy facts per 100 turns |
| Topic adherence       | What fraction of off-topic prompts are redirected, not answered? | ≥ 90 % redirected                       |
| Escalation efficiency | Do genuine escalations reach a human in one turn?                | ≥ 95 % single-turn handoff              |
| Deflection rate       | Queries resolved without a human agent                           | ≥ 70 % of total volume                  |
| CSAT                  | User satisfaction score (post-session survey)                    | ≥ 4.0 / 5.0                             |

Track these weekly from your `call_log` records; the accuracy and grounding columns come for free once you have knowledge bound.

***

## Configure the persona

Register the agent through the managed API. Send a `POST /v1/agents` with the `anthropic-beta: managed-agents-2026-04-01` header:

```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": "support-agent",
    "agent_type": "persona",
    "model": "anthropic/claude-opus-4-8",
    "system": "You are Aria, the Acme Insurance support assistant. Your job is to answer questions about Acme products, collect the information needed for a quote, and generate quotes using the get_quote tool.\n\nRules:\n- Only answer questions about Acme Insurance products. Politely decline unrelated topics.\n- Never mention competitor products or pricing.\n- Never invent policy terms; if the answer is not in the product knowledge, say so and offer to connect the customer to a specialist.\n- If the customer expresses dissatisfaction or needs something outside your scope, use the escalate tool.",
    "capabilities": ["document_search"],
    "knowledge_bindings": ["acme-product-kb"],
    "tools": ["get_quote", "escalate"],
    "max_turns": 8
  }'
```

**Gateway models need a `<provider>/` prefix** — `anthropic/claude-opus-4-8`, not bare `claude-opus-4-8`. The API validates this on registration and rejects bare names.

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

```yaml
---
name: support-agent
agent_type: persona
model: anthropic/claude-opus-4-8
capabilities:
  - document_search
knowledge_bindings:
  - acme-product-kb
tools:
  - get_quote
  - escalate
max_turns: 8
---

# Aria — Acme Insurance Support

You are Aria, the Acme Insurance support assistant. Your job is to answer
questions about Acme products, collect the information needed for a quote,
and generate quotes using the get_quote tool.

Rules:
- Only answer questions about Acme Insurance products. Politely decline
  unrelated topics.
- Never mention competitor products or pricing.
- Never invent policy terms; if the answer is not in the product knowledge,
  say so and offer to connect the customer to a specialist.
- If the customer expresses dissatisfaction or needs something outside your
  scope, use the escalate tool.
```

> **Note:** `max_turns` caps the agentic loop per request — for most support flows, 8 is generous. Raise it only if your tool chain is genuinely deep.

***

## Add product knowledge (RAG)

There are two steps: **create the collection**, then **add content** to it. A collection must exist before you upload into it — uploading to an unknown collection name silently lands in the root collection and won't be bindable.

**1. Create the collection** (once):

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

**2. Add content.** Either ingest text directly (JSON), or upload a file. For files, the field is **`collection_id`** (not `collection`); scanned PDFs are OCR'd, and text is chunked, embedded, and indexed automatically.

```bash
# Option A — ingest text directly
curl -X POST "https://demo.meganova.app/v1/managed/knowledge/ingest" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"collection": "acme-product-kb", "title": "EV coverage",
       "content": "Acme Electric Car Insurance covers battery-system damage, home charging equipment, and cybersecurity protection..."}'

# Option B — upload a file (note: collection_id, not collection)
curl -X POST "https://demo.meganova.app/v1/managed/documents/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "collection_id=acme-product-kb" \
  -F "file=@comprehensive-cover-policy.pdf"
```

Once content is indexed, any persona whose `knowledge_bindings` includes `acme-product-kb` retrieves relevant chunks before answering — automatically, with a `Source:` reference. You don't change the persona config each time you add a document.

> **Note:** Retrieval is automatically scoped to the bound collection — customers from one tenant cannot retrieve another tenant's documents. Per-user scope is enforced by the `X-Platform-User` and `X-End-User` headers on every chat request.

***

## Add a tool (quote generation)

Custom tools let the persona call your backend. You declare the tool's name, description, and input schema; Libra OS calls your webhook with the collected arguments and feeds the result back into the conversation.

Register the tool alongside the persona, or add it to an existing persona with `PUT /v1/agents/support-agent`:

```json
{
  "custom_tools": [
    {
      "name": "get_quote",
      "description": "Generate an insurance quote for a vehicle. Call this once you have collected make, model, year, mileage, and driver age from the customer.",
      "input_schema": {
        "type": "object",
        "properties": {
          "make":       {"type": "string",  "description": "Vehicle make, e.g. Toyota"},
          "model":      {"type": "string",  "description": "Vehicle model, e.g. Camry"},
          "year":       {"type": "integer", "description": "Model year, e.g. 2022"},
          "mileage":    {"type": "integer", "description": "Annual mileage in km"},
          "driver_age": {"type": "integer", "description": "Age of the primary driver"}
        },
        "required": ["make", "model", "year", "mileage", "driver_age"]
      },
      "webhook_url": "https://api.acme.example.com/quotes/generate",
      "risk_tier": "low"
    },
    {
      "name": "escalate",
      "description": "Open a support ticket and notify a human agent. Use when the customer is dissatisfied or the request is outside your scope.",
      "input_schema": {
        "type": "object",
        "properties": {
          "reason":  {"type": "string", "description": "Brief reason for escalation"},
          "summary": {"type": "string", "description": "Short summary of the conversation so far"}
        },
        "required": ["reason", "summary"]
      },
      "webhook_url": "https://api.acme.example.com/tickets/create",
      "risk_tier": "low",
      "side_effects": true
    }
  ]
}
```

**How it works.** When the persona decides to call `get_quote`, Libra OS sends your webhook a JSON body with the collected arguments. Your server returns the quote details; Libra OS injects them into the conversation as a tool result, and the persona writes the customer-facing reply.

**Risk gate.** `risk_tier: "low"` means the tool auto-executes inline. A `"high"`-risk tool (say, one that charges a card) parks a pending action for human approval before the webhook fires — the customer sees "I've submitted your request for approval" instead of an immediate result. This is controlled by `LIBRA_OS_AUTOEXEC_RISK` and `LIBRA_OS_PENDING_ACTIONS_ENABLED`.

> **Note:** Tool input schemas must be fully specified — every `array` type needs an `items` field, even `"items": {}`. Incomplete schemas cause a `400` from Vertex-routed Gemini models (the error message says "unable to reach the upstream endpoints" but it is deterministic and not transient).

***

## Deploy and talk to it

Send a chat request to the persona's native endpoint. Use `stream: true` and `metadata.stream_events: true` for real-time progressive responses:

```bash
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: acme-insurance" \
  -H "X-End-User: customer-9821" \
  -d '{
    "messages": [
      {"role": "user", "content": "Hi, what does your comprehensive cover include?"}
    ],
    "stream": true,
    "metadata": {
      "stream_events": true
    }
  }'
```

The SSE stream emits:

* `text` events — incremental prose as the model writes.
* `tool_use` events — when the persona calls `get_quote` or `escalate`.
* `tool_result` events — the webhook response injected back.
* `:nova-heartbeat elapsed_ms=N` comments every 10 seconds — keep-alive, invisible to OpenAI-compatible clients.

A follow-up turn for the quote continues the same session:

```bash
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: acme-insurance" \
  -H "X-End-User: customer-9821" \
  -d '{
    "messages": [
      {"role": "user", "content": "Great. My car is a 2021 Toyota Camry, 18 000 km a year, and I am 34."},
      {"role": "assistant", "content": "Thanks! Just to confirm — is this for comprehensive cover? And what is the primary driver age?"},
      {"role": "user", "content": "Yes, comprehensive. Driver is 34."}
    ],
    "stream": true,
    "metadata": {"stream_events": true}
  }'
```

Libra OS passes the full conversation to the persona, which decides to call `get_quote`, gets the result, and writes the customer-facing answer — all in one request.

***

## Evaluate

Check the persona against the success criteria you defined earlier.

**Grounding check.** The response body carries a `grounding` field (`grounded`, `ungrounded_refusal`, or `degraded`). A healthy turn returns `grounded` once the knowledge base is populated. If you see `ungrounded_refusal` on a well-scoped question, the knowledge may not contain that topic — add a document and re-test.

**Topic adherence.** Replay a set of off-topic prompts ("who won the Premier League?", "write me a poem") and confirm every reply redirects without answering. A reply that answers an off-topic question means the system prompt rule needs tightening.

**Fabrication.** Ask about a coverage detail you know is not in any uploaded document. The agent must say it does not have that information, not invent a plausible policy term. This is the most important test for a support agent — one invented policy claim erodes trust faster than a slow response.

**Tool invocation.** Confirm the persona collects all required fields before calling `get_quote`. Send a message with only partial info ("I have a Toyota Camry") and verify the agent asks follow-up questions rather than calling the tool with missing arguments.

**Escalation.** Send a complaint ("I want to cancel and I am very unhappy") and confirm the `escalate` tool fires within one turn, creating a ticket in your system.

***

## Improve performance

### Ground long context with RAG

The default retrieval returns 5 chunks per turn (`LIBRA_OS_RAG_TOP_K`). For a multi-document policy suite — multiple PDFs covering comprehensive, third-party, and add-ons — raise it:

```
LIBRA_OS_RAG_TOP_K=12
```

For questions comparing two policies, 12 chunks covers both documents. Trade-off: more tokens in the prompt means slightly higher latency and cost per turn.

### Use tools for real-time data

Anything that changes faster than your upload cadence (live pricing, order status, availability) belongs in a tool, not a document. Keep documents for stable reference material; tools for live lookups.

### Strengthen guardrails

**AI Firewall** is on by default and blocks jailbreak attempts, toxic inputs, and PII extraction patterns at a threshold of 0.4. Tighten it for a high-trust deployment:

```
LIBRA_OS_FIREWALL_THRESHOLD=0.3
```

**Brand rules and topic scope** live in the persona `system` prompt — this is the right place for "never mention CompetitorX" and "only discuss Acme products." The firewall handles abuse; the system prompt handles brand policy.

**PII.** The PII redactor is on by default — it scrubs names, emails, and phone numbers. For a quote flow you need the driver's age (a number, not a name) and vehicle info, but not the customer's full name in the model's output. Leave the redactor on; only disable it (`guardrails.pii_redactor: disabled`) on personas whose workflow genuinely requires the raw personal identifier.

### Stream for perceived latency

`stream: true` on the chat request sends prose deltas as the model writes them. Users see the first words within 1–2 seconds rather than waiting for the full response. This matters most on longer knowledge-grounded answers where the model is reading retrieved chunks before writing.

### Escalation to a human

The `escalate` tool is the recommended pattern: the persona calls it, you receive a structured webhook payload (reason + conversation summary), and your system creates the ticket or triggers a live-agent notification. This is a **composed** integration — Libra OS calls your endpoint; the ticketing system is yours.

For high-risk actions (charge a card, cancel a policy) set `risk_tier: "high"` on the tool. Libra OS will dry-run the call, park a pending action, and notify your approval queue before the webhook fires — the customer is told "your request has been submitted for review."

***

## Integrate with your app

The native chat endpoint is the integration surface. Your backend (or frontend, for a browser widget) sends the request and renders the SSE stream.

```python
import httpx, json

LIBRA_OS_URL = "https://demo.meganova.app"
API_KEY      = "nk_..."   # per-agent key from POST /api/agents/support-agent/keys
TOKEN        = "..."       # JWT from your auth service or OIDC session

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type":  "application/json",
    "X-Platform-User": "acme-insurance",
    "X-End-User":      session["user_id"],
}

payload = {
    "messages": conversation_history,
    "stream":   True,
    "metadata": {"stream_events": True},
}

with httpx.stream(
    "POST",
    f"{LIBRA_OS_URL}/agents/v1/{API_KEY}/chat",
    headers=headers,
    json=payload,
    timeout=60,
) as response:
    for line in response.iter_lines():
        if line.startswith("data:"):
            event = json.loads(line[5:])
            if event.get("type") == "text":
                yield event["content"]          # stream prose to browser
            elif event.get("type") == "tool_use":
                log_tool_call(event["name"], event["input"])
            elif event.get("done"):
                break
```

**Auth note.** Issue a per-agent API key (`POST /api/agents/support-agent/keys`) scoped to `agents_only` — it can only call this agent, nothing else. Pass it as the `{api_key}` path segment. The `Authorization: Bearer` header is a separate JWT from your login flow (or Libra OS's built-in OIDC provider).

**OpenAI-compatible surface.** If your frontend or SDK already speaks the OpenAI chat-completions API, `POST /v1/chat/completions` with `model: support-agent` is supported and streams the same prose. Tool-use and grounding events are only available on the native `/agents/v1/` path.

***

## Next steps

* Classify and route incoming support tickets by intent before they reach the persona: [Ticket Routing](https://docs.meganova.ai/libra-os/use-cases/ticket-routing.md).
* Add a moderation layer to flag user-generated content in the same product: [Content Moderation](https://docs.meganova.ai/libra-os/use-cases/content-moderation.md).
* See the full list of capabilities, model tier configuration, and guardrail options: [Capabilities](https://docs.meganova.ai/libra-os/capabilities.md).
