> 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/ticket-routing.md).

# Ticket Routing

Route customer support tickets to the right team automatically by classifying intent, urgency, and priority — at scale, without maintaining brittle rule trees.

The Libra OS way: a **persona with `output_type`** accepts a ticket, returns a validated JSON verdict `{reasoning, intent}`, and your ticketing system acts on the `intent` field. The classifier is a registered agent you call over HTTP — no ML infrastructure, no labeled training set required to get started.

> **Runnable version:** a self-contained implementation of this guide (SDK client + a labelled validation set + accuracy loop) lives in the cookbook: [`nova-os-cookbook/ticket-routing`](https://github.com/libraos/cookbook/tree/main/ticket-routing).

***

## Should you use an LLM for ticket routing?

An LLM classifier is a good fit when:

* You have **limited labeled data** and can't train a dedicated ML model.
* Your **categories evolve** — new products, new issue types, seasonal spikes — and you want to update a description, not retrain.
* Tickets arrive as **unstructured text**: chat transcripts, emails, voice-to-text, multilingual input.
* Routing rules depend on **semantic understanding** (a ticket saying "I can't log in" is a Technical issue even if the word "technical" never appears).
* You want **interpretable decisions** — a `reasoning` field that explains each verdict.
* You need graceful **edge-case handling** — ambiguous tickets, emotional language, multiple issues in one message.
* Your user base is **multilingual** and you don't want a separate classifier per language.

***

## Define your intent categories

Start with a taxonomy that matches your support workflow. Example:

| Category            | Sub-categories                                            |
| ------------------- | --------------------------------------------------------- |
| Technical issue     | Bug report, Integration failure, Performance degradation  |
| Account management  | Password reset, Billing update, Account closure           |
| Product information | Pricing, Feature availability, Roadmap question           |
| User guidance       | How-to question, Onboarding help, Workflow walkthrough    |
| Feedback            | Feature request, Complaint, Compliment                    |
| Order-related       | Order status, Refund request, Shipping issue              |
| Security            | Unauthorized access, Data breach concern, Phishing report |
| Emergency           | Service down, Data loss, Critical outage                  |

Routing decisions may also depend on:

* **Urgency** — infer from language ("production is down", "our demo is in an hour").
* **Customer tier** — SLA obligations differ for enterprise vs. free-plan users.
* **Language** — route to the right regional team.

You can extend the `output_type` schema to include these extra fields (see [Improve performance](#improve-performance)).

***

## Establish success criteria

Define what good looks like before you ship. Measure against a hand-labeled validation set.

| Metric                     | Definition                                                 | Target  |
| -------------------------- | ---------------------------------------------------------- | ------- |
| Routing accuracy           | Fraction of tickets assigned the correct category          | ≥ 90%   |
| Classification consistency | Same ticket, same verdict on re-run (temperature 0)        | ≥ 97%   |
| Adaptation speed           | Time from new category description to production           | < 1 day |
| Multilingual parity        | Accuracy gap between English and other languages           | < 5 pp  |
| Edge-case handling         | Accuracy on ambiguous or multi-issue tickets               | ≥ 80%   |
| Rerouting rate             | Fraction of tickets human agents reassign after auto-route | < 8%    |

Start conservative: validate on 200–500 hand-labeled tickets before routing live traffic.

***

## Choose the model

Ticket classification is a single, short call — one ticket in, one verdict out. No planning, no tool use, no multi-step reasoning.

Use the **skill tier**: a fast, low-cost model (Flash/Haiku-class, configured via `LIBRA_OS_SKILL_MODEL`). Set `"brain": false` on the agent so Libra OS skips the planner entirely and routes the request straight to the model.

For large taxonomies (20+ categories) or tickets that require reading long threads, a stronger model may improve accuracy. The trade-off is cost and latency per classification. Start with the skill tier and only upgrade if your accuracy target isn't met.

***

## Build the classifier persona

Register a persona that accepts ticket text and returns a structured verdict. The `output_type` field tells Libra OS to enforce a JSON Schema on every response; `on_violation: "repair"` causes Libra OS to re-prompt the model to fix any non-conforming output automatically.

```bash
curl -X POST https://demo.meganova.app/v1/agents \
  -H "Authorization: Bearer $TOKEN" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ticket-router",
    "agent_type": "persona",
    "brain": false,
    "model": "gemini/gemini-2.5-flash",
    "system": "You are a support ticket classifier. Read the ticket carefully and identify the primary intent. Always write your reasoning before selecting a category. Be concise. If a ticket contains multiple issues, classify by the most urgent one.",
    "output_type": {
      "schema_inline": {
        "type": "object",
        "properties": {
          "reasoning": {
            "type": "string",
            "description": "A brief explanation of why this category fits the ticket."
          },
          "intent": {
            "type": "string",
            "enum": [
              "Technical issue",
              "Account management",
              "Product information",
              "User guidance",
              "Feedback",
              "Order-related",
              "Security",
              "Emergency"
            ]
          }
        },
        "required": ["reasoning", "intent"]
      },
      "on_violation": "repair"
    }
  }'
```

> **Note:** Gateway-bound models must include a `<provider>/` prefix (e.g. `gemini/gemini-2.5-flash`, `anthropic/claude-haiku-4-5`). A bare model name will return a 404 from the gateway.

The response includes an `api_key` for the agent. Save it — you'll use it when classifying tickets.

***

## Run a classification

Send ticket text as a user message. The response `content` is a validated JSON object.

```bash
curl -X POST https://demo.meganova.app/agents/v1/{api_key}/chat \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {
        "role": "user",
        "content": "Hi, I have been trying to reset my password for the past hour. The reset email never arrives, even after clicking the link multiple times. This is blocking our whole team."
      }
    ]
  }'
```

Example response:

```json
{
  "content": {
    "reasoning": "The user is unable to receive password reset emails and has tried multiple times. This is a concrete technical failure on a core authentication flow, not a how-to question. The urgency language ('blocking our whole team') suggests it should be escalated, but the primary category is a technical failure.",
    "intent": "Technical issue"
  }
}
```

The `reasoning` field is surfaced in your support dashboard or audit log. The `intent` field drives your routing rule.

You can also call the classifier via the OpenAI-compatible endpoint (`POST /v1/chat/completions`) or the Anthropic-compatible endpoint (`POST /v1/messages`) — both honor `output_type`.

***

## Evaluate

Before routing live traffic, validate accuracy against a labeled set.

**Simple evaluation loop:**

```python
import httpx, json

labeled = [
    {"ticket": "My invoice shows the wrong amount.", "expected": "Order-related"},
    {"ticket": "Someone logged in from an unknown device.", "expected": "Security"},
    # ... more examples
]

correct = 0
for item in labeled:
    resp = httpx.post(
        "https://demo.meganova.app/agents/v1/{api_key}/chat",
        json={"messages": [{"role": "user", "content": item["ticket"]}]},
        headers={"Content-Type": "application/json"},
    )
    verdict = resp.json()["content"]
    if verdict["intent"] == item["expected"]:
        correct += 1
    else:
        print(f"MISS — expected {item['expected']}, got {verdict['intent']}")
        print(f"  Reasoning: {verdict['reasoning']}")

print(f"Accuracy: {correct}/{len(labeled)} = {correct/len(labeled):.1%}")
```

Track **cost per classification** by checking the `usage` block on each response (`prompt_tokens` + `completion_tokens`). On a Flash-class model, a typical ticket classifies in under a second for a fraction of a cent.

Investigate every miss: read the `reasoning` field. Most misses fall into one of three buckets — wrong category description, ambiguous ticket text, or a genuine edge case. That tells you exactly what to improve.

***

## Improve performance

### Hierarchical classification for large taxonomies

When your taxonomy exceeds 20 categories, a single classifier struggles to hold the full enum and degrades in accuracy. Use a two-level cascade:

1. A **top-level classifier** routes to a branch (e.g. `Technical issue`, `Account management`, `Billing`).
2. A **sub-classifier persona** per branch narrows to the specific sub-category (e.g. under `Technical issue`: `Bug report`, `Integration failure`, `Performance degradation`).

Register each persona separately with its own `output_type` enum. Your integration calls the top-level classifier first, then dispatches to the matching sub-classifier. The trade-off is one extra LLM call (\~1–2 seconds); the gain is significantly higher accuracy and easier maintenance (you update one branch without touching the others).

### Few-shot examples via a bound knowledge collection

Labeled examples dramatically improve accuracy on domain-specific language. Upload your labeled tickets as a knowledge collection, then bind the classifier to it:

```bash
# 1. Create the collection (once)
curl -X POST https://demo.meganova.app/api/knowledge/collections \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"name": "ticket-examples", "access_level": "private"}'

# 2. Upload a labeled-examples document (field is collection_id)
curl -X POST https://demo.meganova.app/v1/managed/documents/upload \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@labeled-tickets.md" \
  -F "collection_id=ticket-examples"

# 3. Bind the classifier to the collection
curl -X PUT https://demo.meganova.app/v1/agents/ticket-router \
  -H "Authorization: Bearer $TOKEN" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{"knowledge_bindings": ["ticket-examples"]}'
```

Libra OS retrieves the nearest labeled examples for each incoming ticket and injects them into the system context automatically. No prompt engineering needed — the model sees real examples of correctly classified tickets before it sees the new one.

### Edge-case handling in the system prompt

Add explicit guidance for the cases that trip up classifiers most often:

* **Implicit requests** — "The export button doesn't do what I expect" is a Technical issue, not Feedback.
* **Emotion vs. intent** — "I'm furious that my order hasn't arrived" routes to Order-related, not Feedback.
* **Multiple issues** — classify by the most urgent issue; note secondary issues in `reasoning`.
* **Questions that are actually complaints** — "Why did my subscription renew without warning?" is Account management, not Product information.

Extend the schema to include `urgency` (`low|medium|high|critical`) or `secondary_intent` if your routing logic needs them. Keep each field narrow — an enum with `on_violation: "repair"` is more reliable than a free-text urgency score.

***

## Integrate

### Push: your ticketing system calls Libra OS

The simplest integration: wire your ticketing system (Zendesk, Freshdesk, Linear, etc.) to POST new tickets to a small relay service. The relay calls the classifier and writes the returned `intent` back to the ticket before it enters the queue.

```
Ticket created → relay service → POST /agents/v1/{api_key}/chat
                                ← {reasoning, intent}
                              → update ticket field + assign queue
```

If your ticketing system supports webhooks, a serverless function (AWS Lambda, Cloud Run) works well as the relay.

### Pull: your service polls and classifies in batch

For existing backlogs or lower-latency requirements:

1. Your service queries the ticketing system for unclassified tickets.
2. For each ticket, call the classifier.
3. Write the verdict back to the ticket record.

Run the batch on a schedule (every 5 minutes) or trigger it from your ticket-creation event stream.

### Using lifecycle hooks (advanced)

Libra OS supports lifecycle hooks (`POST /v1/managed/hooks`) that fire on agent events. You can register a webhook to receive the classifier's output and forward it to your downstream ticketing system without building a relay service.

***

## Next steps

* [Customer Support Agent](https://docs.meganova.ai/libra-os/use-cases/customer-support-agent.md) — build a full support agent that not only classifies but also resolves common tickets autonomously.
* [Content Moderation](https://docs.meganova.ai/libra-os/use-cases/content-moderation.md) — apply the same `output_type` pattern to classify and filter user-generated content.
* [Capabilities](https://docs.meganova.ai/libra-os/capabilities.md) — overview of what Libra OS agents can do out of the box.
