---
name: levanto-sage-decide
description: Call the Levanto Sage API: decisions (/decide: Yes/No, Choice, Scale, Sort, Tags, with optional reasoning, web grounding and images), extraction of typed fields (/v1/extract) and streaming decisions over growing text (/v1/stream). Use when the user gives a Sage endpoint, asks to classify, route, score, rank, tag or extract data from content, or wants Sage examples.
---

# Levanto Sage

Sage turns content plus a question into a structured decision your code acts on: route, approve, block, score, rank, tag or escalate. It also extracts typed fields from text, and streams decisions over text that grows, such as a live call. Typical uses: agent workflows and guardrails, ops triage, moderation, documents, voice and chat.

When you write about Sage:

- Say "decision kind" in prose; keep JSON wire fields exactly as shown.
- When Sage isn't sure, say "the answer is `null`", never "abstains".
- Don't describe internals, architecture or training unless the user asks.

## Endpoint and key

Base URL: `https://sage.levanto.ai`. Use the user's URL if they give one; never invent one.

| Method | Path | Use |
|---|---|---|
| GET | `/ready` | `200` ready, `503` loading. No key. |
| POST | `/decide` | One decision |
| POST | `/decide/batch` | Many decisions |
| POST | `/v1/extract` | Typed fields from a document |
| POST | `/v1/extract/batch` | The same fields from many documents |
| GET | `/v1/stream` | Decisions over growing text (WebSocket) |
| POST | `/usage/estimate` | Decision token counts without running |

Every call except `/ready` needs a Levanto API key, sent as `Authorization: Bearer lv_live_...`; without one they return `401`. If the user has no key, ask for one. Read it from an environment variable (e.g. `SAGE_API_KEY`); never hardcode, log, echo or commit it.

## Request

```json
{
  "content": "<what to judge>",
  "question": {"id": "<your result key>", "kind": "yesno | choice | scale | sort | tags", "instructions": "<the question>"}
}
```

`content` is a string, `{"kind": "text", "value": "..."}`, a list for Sort, or an image ([Images](#images-beta)). Optional top-level fields: `reasoning`, `grounding`. Every response is `{ id, kind, result, meta }`.

## Acting on answers

Yes/No, Choice and Tags return `null` when Sage isn't sure. Send `null` to a human:

```python
result = response["result"]
if result["answer"] is None:        # Choice: result["chosen"]; Tags: tag["applies"]
    escalate_to_human(response)
else:
    act_on(result["answer"])
```

Use `probability` only when a workflow needs a stricter bar than Sage's answer. Scale and Sort return `confidence` instead.

## Yes/No

```json
{
  "content": "Email draft promises \"guaranteed 40% returns\" and calls the product \"risk-free\".",
  "question": {"id": "needs_review", "kind": "yesno", "instructions": "Does this copy need compliance review before send?"}
}
```

```json
{
  "id": "needs_review",
  "kind": "yesno",
  "result": {
    "answer": "yes",
    "probability": 0.9997
  },
  "meta": { "model": "levanto-sage-2", "latency_ms": 79.1 }
}
```

- `answer`: `"yes"`, `"no"`, or `null` on a near-tie (e.g. `probability` 0.51).
- `probability`: calibrated P(yes), always returned.

## Choice

```json
{
  "content": "Vendor contract with automatic renewal and a 90-day termination clause. Liability for the customer is uncapped.",
  "question": {
    "id": "contract", "kind": "choice", "instructions": "How should legal handle this contract?",
    "options": [
      {"option": "approve", "description": "Standard terms, no red flags"},
      {"option": "revise", "description": "Acceptable with clause changes"},
      {"option": "escalate", "description": "Unusual or high-risk terms"}
    ]
  }
}
```

```json
{
  "id": "contract",
  "kind": "choice",
  "result": {
    "chosen": "escalate",
    "probability": 0.8405,
    "probabilities": [
      {"option": "approve", "probability": 0.0022},
      {"option": "revise", "probability": 0.1572},
      {"option": "escalate", "probability": 0.8405}
    ]
  },
  "meta": { "model": "levanto-sage-2", "latency_ms": 115.8 }
}
```

- `chosen`: the winning option, or `null` when the top two are too close to call.
- `probability`: calibrated P(`chosen` is correct); `null` when `chosen` is.
- `probabilities`: every option in request order; they sum to 1.
- 2–120 options (20 with an image).
- Put the rules in `content` or `instructions` and describe each option.

## Scale

Send 2–26 `levels`, distinct whole numbers of your choice (e.g. `0`–`4`, `1`–`5`); anything else returns `400`.

```json
{
  "content": "Candidate explained the roadmap clearly but struggled with database scaling tradeoffs.",
  "question": {
    "id": "interview", "kind": "scale", "instructions": "How strong was this technical interview?",
    "levels": [
      {"level": 0, "description": "Not qualified"},
      {"level": 1, "description": "Weak"},
      {"level": 2, "description": "Mixed"},
      {"level": 3, "description": "Solid"},
      {"level": 4, "description": "Strong hire"}
    ]
  }
}
```

```json
{
  "id": "interview",
  "kind": "scale",
  "result": {
    "expectation": 2.89,
    "confidence": 0.66,
    "probabilities": [
      {"level": 0, "probability": 0.0},
      {"level": 1, "probability": 0.01},
      {"level": 2, "probability": 0.12},
      {"level": 3, "probability": 0.84},
      {"level": 4, "probability": 0.03}
    ]
  }
}
```

`expectation` is the expected level; `probabilities` sum to 1; `confidence` is how sure Sage is of the score.

## Sort

`content` is a list of 2–120 items. The question takes only `kind`, `id` and `instructions`; other fields are rejected, and the server picks the ranking method.

```json
{
  "content": {"kind": "list", "value": [
    {"id": "typo", "content": "Spelling mistake on the FAQ page."},
    {"id": "db_down", "content": "Production database is unreachable."},
    {"id": "pricing", "content": "Prospect asking about Enterprise pricing."}
  ]},
  "question": {"id": "triage", "kind": "sort", "instructions": "Most urgent first."}
}
```

```json
{ "id": "triage", "kind": "sort", "result": { "sorted": ["db_down", "pricing", "typo"], "confidence": 0.92 } }
```

`confidence` (0–1, or `null`) is how trustworthy the whole order is.

## Tags

Decide which of 1–120 labels apply. Each tag returns `probability` and `applies`: `true`, `false`, or `null` when too close to call. Don't read `null` as `false`: send it to a person or skip the action that depends on that tag.

- Write `instructions` as the rule for when a tag applies; similar tags are judged against each other.
- Give each tag a `name` (label plus one line); the `id` is only the key you get back. Say what doesn't count when two tags are easy to confuse.
- For "does anything apply", gate with Yes/No first. For exactly one of N, use Choice.

```json
{
  "content": "Forum post: \"I help indie artists grow their streams. First month half price, DM me.\"",
  "question": {
    "id": "moderate", "kind": "tags",
    "instructions": "Tag the issues. Members may promote their own work once.",
    "tags": [
      {"id": "spam", "name": "spam: bulk or repeated posting; a single genuine offer is not spam"},
      {"id": "promotion", "name": "promotion: advertises the poster's own product"},
      {"id": "scam", "name": "scam: deceptive offer, fake results or payment tricks"}
    ]
  }
}
```

```json
{
  "id": "moderate",
  "kind": "tags",
  "result": {
    "tags": [
      {"id": "spam", "probability": 0.03, "applies": false},
      {"id": "promotion", "probability": 1.0, "applies": true},
      {"id": "scam", "probability": 0.03, "applies": false}
    ]
  }
}
```

## Images (beta)

Yes/No, Choice, Scale and Tags accept an image as `content`, on `/decide` and per batch group.

```json
{
  "content": {"kind": "image", "media": "data:image/png;base64,iVBORw0KGgo...", "text": "Ticket: checkout button missing on mobile."},
  "question": {"id": "shows_bug", "kind": "yesno", "instructions": "Does the screenshot show the reported problem?"}
}
```

- `media`: base64 `data:` URI (PNG, JPEG or WebP), up to 4 MiB decoded, longest edge 8192 px, 4096² pixels. No remote URLs.
- `text` (optional): context to judge with the image.
- Not with Sort, `list` items, `grounding`, or more than 20 Choice options (`400`).
- Image tokens are input tokens (`meta.usage.image_tokens`).

## Reasoning

Top-level `reasoning` on `/decide` and `/decide/batch`:

- `off` (default): answer right away. Fastest and cheapest; right for most calls.
- `auto`: reason only when the question needs it (long policy text, multi-step rules).
- `on`: always reason, up to a few seconds, when accuracy beats speed.

With `auto` or `on`, set client timeouts above 10 seconds.

```json
{
  "content": "Refund request: $180 order, bought 41 days ago, box unopened. Policy: refunds within 30 days; store credit up to 60 days if unopened.",
  "question": {"id": "refund_ok", "kind": "yesno", "instructions": "Should we issue a cash refund?"},
  "reasoning": "auto"
}
```

`meta.reasoning` (omitted on kinds without reasoning):

```json
"reasoning": {"fired": true, "ran": true, "finished": true, "tokens": 312, "limited": null}
```

- `ran`: Sage reasoned. `finished`: `false` if cut off (`limited`: `cap`, `timeout` or `budget`); Sage still answers.
- `tokens`: thinking tokens, charged as output.

## Grounding (optional)

Add `grounding` to a Yes/No, Choice, Scale or Tags request to search the web before deciding, for recent or factual questions. Not with images. Omit it if the server isn't set up for grounding.

```json
{
  "content": "Has there been a major Cloudflare incident this month?",
  "question": {"id": "incident", "kind": "yesno", "instructions": "Is this likely true?"},
  "grounding": {"trigger": "low_confidence", "confidence_floor": 0.8}
}
```

- `trigger`: `low_confidence` (default: search when Sage is less sure than `confidence_floor`, default `0.80`), `always` or `never`.
- Search runs before the `null` check, so it can turn `null` into an answer. The response adds `grounding_meta` (`triggered`, `queries`, `sources`).
- Each search that runs is charged at your plan's search rate, plus tokens.

## Extract

`POST /v1/extract` returns typed values from `content`. The shape of `extract` is the shape of the answer.

```json
{
  "content": "INVOICE 2026-117\nNordlicht GmbH, Hafenstrasse 4, Hamburg\nBill to: Acme Ltd\n\n2 x Espresso machine service: 480.00 EUR\n1 x Descaling kit: 60.00 EUR\nTotal due: 540.00 EUR\nDue date: 21 November 2026",
  "extract": {
    "vendor": "the company issuing the invoice",
    "total": {"type": "money", "definition": "the amount payable"},
    "due_date": {"type": "date"},
    "products": ["a product or service billed"]
  }
}
```

```json
{
  "values": {"vendor": "Nordlicht GmbH", "total": {"amount": 540.0, "currency": "EUR"}, "due_date": "2026-11-21", "products": ["Espresso machine service", "Descaling kit"]},
  "results": {"total": {"value": {"amount": 540.0, "currency": "EUR"}, "text": "540.00 EUR", "start": 157, "end": 167, "probability": 0.9863, "probabilities": [...]}, ...},
  "meta": {"model": "levanto-sage-2", "mode": "fast", "usage": {"input_tokens": 265, "output_tokens": 440}}
}
```

- A field is a definition (`""` if the name says it all), `{"type", "definition"}`, or a one-item list for every mention. `extract` can also be a question, or `["question"]` for every answer.
- Types: `text` (default), `integer`, `decimal`, `money` (`{amount, currency}`), `date` (`YYYY-MM-DD`), `time` (`HH:MM`, plus the offset when a zone is written), `duration` (ISO 8601, e.g. `P3Y`). Values come only from what the text states.
- `values` is `null` when a field is absent or too close to call. `results` adds `text`, `start`/`end` (offsets into `content`), `probability` and `probabilities` (candidates, then `null`; sum 1).
- `POST /v1/extract/batch`: up to 64 `contents`, one `extract`. Each result is `{"ok": true, "values", "results"}` or `{"ok": false, "error"}`.
- Limits: 64 fields; names up to 256 characters, no double quotes or line breaks; content plus definitions up to 16,384 tokens, else `413` (split it). `429`: retry after `Retry-After`.

## Stream

`wss://sage.levanto.ai/v1/stream` (WebSocket): send questions once, append text as it arrives, and get a `decision` frame whenever an answer changes. Full guide: https://docs.levanto.ai/stream.

```json
{"type": "start", "questions": [{"id": "agreed", "kind": "yesno", "instructions": "Has the customer agreed to go ahead?"}]}
{"type": "append", "text": "Customer: OK, 48 months then. Send me the quote.\n"}
```

```json
{"type": "decision", "answers": {"agreed": {"id": "agreed", "kind": "yesno", "result": {"answer": "yes", "probability": 0.9848}}}, "changed": ["agreed"]}
```

- Auth: `Authorization: Bearer` on the upgrade, or `api_key` in `start` (browsers).
- `start`: 1–32 `/decide/batch` questions with an `id`; optional `content`, `reasoning`, `emit` (`changes`, the default: a frame only when an answer changes; or `all`). Don't wait for a frame before appending.
- Also: `questions` (replace the set), `evaluate`, `ping`, `close`. Text can only be appended.
- An `append` past 16,384 tokens (text plus questions) is refused (`prompt_too_long`); the session stays open. On `draining` (close 1012), reconnect and `start` with the full text. Ignore `ping` and `sig` frames; 300 s idle closes.

## Pricing

Each plan includes usage each month. Calls are charged per input token, output token and search at your plan's rates:

| Plan | Price | Input / 1M tokens |
|------|------:|------------------:|
| Free | Free ($1 usage / month) | $0.05 |
| Developer | $14 / month | $0.05 |
| Starter | $49 / month | $0.046 |
| Pro | $99 / month | $0.042 |
| Growth | $249 / month | $0.038 |

All plans: output $1 / 1M tokens · search $0.10.

- **Input**: everything Sage reads, including instructions, options and images. A decision counts content once per question (ten questions on one document count it ten times), once per tag for Tags, once per item for Sort. A stream counts new text plus the questions on each update.
- **Output**: what extraction and streaming send back, plus thinking when Sage reasons. A decision's answer is free.
- **Search**: per grounding search that runs.
- `meta.usage` reports the tokens (stream frames: `usage`); `POST /usage/estimate` predicts a decision's (images excluded).
- Unused usage doesn't roll over. When it runs out, calls return `402` until the next period or an upgrade. No seats, no overage invoices.

## Batch

`requests` is a list of groups: one `content` and its `questions`. Batching saves round trips, not tokens. Top-level `reasoning` applies to every question; `grounding` goes on each question.

```json
{
  "reasoning": "auto",
  "requests": [
    {"content": "Selling verified Instagram accounts, DM for bulk pricing.", "questions": [
      {"id": "violates", "kind": "yesno", "instructions": "Does this post violate marketplace policy?"},
      {"id": "action", "kind": "choice", "instructions": "What should moderation do?",
       "options": [{"option": "remove"}, {"option": "warn"}, {"option": "allow"}]}
    ]},
    {"content": "doc B", "questions": [{"id": "b1", "kind": "yesno", "instructions": "Urgent?"}]}
  ]
}
```

`results[i].answers[j]` matches `requests[i].questions[j]`: `ok` plus `result` or `error`.

```json
{
  "results": [
    {"answers": [
      {"ok": true, "result": {"id": "violates", "kind": "yesno", "result": {"answer": "yes", "probability": 0.995}}},
      {"ok": true, "result": {"id": "action", "kind": "choice", "result": {"chosen": "remove", "probability": 0.9488, "probabilities": [...]}}}
    ]},
    {"answers": [{"ok": true, "result": {"id": "b1", "kind": "yesno", "result": {"answer": "no", "probability": 0.1839}}}]}
  ],
  "meta": {"model": "levanto-sage-2", "request_count": 2, "question_count": 3, "latency_ms": 611.8,
           "usage": {"input_tokens": 308, "output_tokens": 19}}
}
```

## Errors and limits

| HTTP | Meaning | Example body |
|---|---|---|
| `400` | Invalid request, a limit below, or an unsupported image combination | `{"detail": "content: Field required"}` |
| `401` | Missing or invalid API key | `{"detail": "API key required. Provide a valid Levanto API key."}` |
| `402` | This period's included usage is used up | |
| `503` | Loading or temporarily unavailable | `{"detail": "Service is still loading."}` |

| Kind | Field | Min | Max |
|---|---|---:|---:|
| choice | `options` | 2 | 120 (20 with an image) |
| scale | `levels` | 2 | 26 (distinct whole numbers) |
| sort | `content.value` items | 2 | 120 |
| tags | `tags` | 1 | 120 |

A decision request (content, instructions, options and any search results) must fit the plan's context: about 32K tokens, or 128K on Growth. Oversized requests fail, never truncate; stay well under the limit.

## Smoke Test

```bash
endpoint="https://sage.levanto.ai"
auth="Authorization: Bearer ${SAGE_API_KEY:?set SAGE_API_KEY to your lv_live_ key}"

# /ready needs no key: 200 ready, 503 loading.
curl -s -o /dev/null -w '%{http_code}\n' "$endpoint/ready" | grep -qx 200

curl -s -H "$auth" -H 'Content-Type: application/json' "$endpoint/decide" -d '{
  "content": "Email draft promises \"guaranteed 40% returns\" and calls the product \"risk-free\".",
  "question": {"id": "needs_review", "kind": "yesno", "instructions": "Does this copy need compliance review before send?"}
}' | jq -e '.kind == "yesno" and .result.probability != null and (.result | has("answer")) and (.result.answer == "yes" or .result.answer == "no" or .result.answer == null)'

curl -s -H "$auth" -H 'Content-Type: application/json' "$endpoint/decide/batch" -d '{
  "requests": [{"content": "same doc", "questions": [
    {"id": "a", "kind": "yesno", "instructions": "urgent?"},
    {"id": "b", "kind": "yesno", "instructions": "positive?"}
  ]}]
}' | jq -e '.meta.request_count == 1 and .meta.question_count == 2 and (.results | length) == 1 and (.results[0].answers | length) == 2'
```
