# Agent quickstart

Start a run, poll it, read the answer and its quotes. Then a schema, the event stream, a webhook and cancelling.

A run is a job. You start it, it works for a while, and you collect the result. There are three ways to wait: poll, read the event stream, or be told by webhook.

## 1. Start a run

```bash
curl https://api.millionshort.com/v1/agent \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: fares-2026-11-20" \
  -d '{
    "prompt": "What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?",
    "processor": "lite",
    "max_credits": 40
  }'
```

```python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent(
    "What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?",
    processor="lite",
    max_credits=40,
    idempotency_key="fares-2026-11-20",
)
print(run.id, run.status)
```

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent(
  'What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?',
  { processor: 'lite', maxCredits: 40, idempotencyKey: 'fares-2026-11-20' },
);
console.log(run.id, run.status);
```

The answer is `202` and comes back at once:

```json
{
  "data": {
    "id": "agt_01jd4f8q2m6r9t3v5x7z0b1c2d",
    "status": "queued",
    "processor": "lite",
    "model": "fast",
    "max_credits": 40,
    "request": { "processor": "lite", "model": "fast", "max_credits": 40 },
    "progress": { "step": "queued", "searches": 0, "pages_read": 0, "model_calls": 0, "credits": 0 },
    "stop_reason": null,
    "webhook_id": null,
    "created_at": "2026-11-20T14:02:11Z",
    "started_at": null,
    "finished_at": null
  },
  "request_id": "req_01JD4F8Q2M6R9T3V5X7Z",
  "usage": { "credits": 0, "cost_usd": 0, "breakdown": {}, "steps": {} },
  "warnings": []
}
```

- Keep `data.id`. Every other call names it.
- `max_credits` is held from your credits now. What the run does not use is handed back when it ends. [Pricing and limits](https://millionshort.com/docs/agent/pricing#the-cap-is-a-hold) says how.
- `Idempotency-Key` is optional. The same key with the same body returns the run it already made, with `200` in place of `202`, so a retry after a timeout does not start a second one.
- `processor` says how much work the run may do. `lite` is the smallest. Left out, it is `standard`.

## 2. Poll it

```bash
curl https://api.millionshort.com/v1/agent/$AGENT_ID \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

import requests

r = requests.get(
    f"https://api.millionshort.com/v1/agent/{os.environ['AGENT_ID']}",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch(`https://api.millionshort.com/v1/agent/${process.env.AGENT_ID}`, {
  headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
});
if (!res.ok) throw new Error(`GET /v1/agent/… failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

`status` is `queued`, then `running`, then one of the four endings: `completed`, `incomplete`, `failed` or `cancelled`. While the run is going, `progress` says which step it is on and what it has spent so far. Polling is free.

The SDKs have a waiter that polls for you and returns the run once it has ended:

```python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent(
    "What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?",
    processor="lite",
)
done = client.wait_agent(run.id, poll_interval=2.0, timeout=600.0)
print(done.status, done.stop_reason)
print(done.answer)
for cite in done.citations:
    print(cite["n"], cite["url"], cite["quote"])
print(done.usage.credits)
```

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent(
  'What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?',
  { processor: 'lite' },
);
const done = await client.waitAgent(run.id, { pollIntervalMs: 2000, timeoutMs: 600_000 });
console.log(done.status, done.stop_reason);
console.log(done.answer);
for (const cite of done.citations ?? []) console.log(cite.n, cite.url, cite.quote);
console.log(done.usage?.credits);
```

Past its timeout the waiter raises `PollTimeoutError`. The run goes on, and you can poll it again.

## 3. Read the result

Once the run has ended, the same `GET` carries the result:

```json
{
  "data": {
    "id": "agt_01jd4f8q2m6r9t3v5x7z0b1c2d",
    "status": "completed",
    "processor": "lite",
    "model": "fast",
    "max_credits": 40,
    "request": { "processor": "lite", "model": "fast", "max_credits": 40 },
    "progress": { "step": "check", "searches": 2, "pages_read": 4, "model_calls": 2, "credits": 8.8 },
    "stop_reason": "done",
    "webhook_id": null,
    "created_at": "2026-11-20T14:02:11Z",
    "started_at": "2026-11-20T14:02:11Z",
    "finished_at": "2026-11-20T14:02:18Z",
    "steps": [
      { "seq": 1, "type": "started", "at": "2026-11-20T14:02:11Z", "processor": "lite", "model": "fast" },
      { "seq": 2, "type": "plan", "at": "2026-11-20T14:02:12Z", "searches": [
        { "query": "Northbridge Transit monthly adult pass price 2026", "source": "web" },
        { "query": "Northbridge Transit fare change", "source": "news" }
      ] },
      { "seq": 3, "type": "search", "at": "2026-11-20T14:02:13Z", "query": "Northbridge Transit monthly adult pass price 2026", "source": "web", "results": 8, "new": 8 },
      { "seq": 4, "type": "search", "at": "2026-11-20T14:02:13Z", "query": "Northbridge Transit fare change", "source": "news", "results": 5, "new": 4 },
      { "seq": 5, "type": "read", "at": "2026-11-20T14:02:15Z", "asked": 3, "read": 3 },
      { "seq": 6, "type": "write", "at": "2026-11-20T14:02:17Z", "statements": 3, "quotes_checked": 4 },
      { "seq": 7, "type": "check", "at": "2026-11-20T14:02:18Z", "statements_kept": 2, "statements_removed": 1 }
    ],
    "answer": "A monthly adult pass on Northbridge Transit costs $96 in 2026 [1]. The price last changed on 1 March 2026, when it rose from $92 [1][2].",
    "output": null,
    "citations": [
      {
        "n": 1,
        "url": "https://transit.northbridge.example/fares",
        "title": "Fares and passes",
        "source": "web",
        "quote": "Monthly adult pass: $96, effective 1 March 2026."
      },
      {
        "n": 2,
        "url": "https://news.northbridge.example/2026/02/fares-rise-in-march",
        "title": "Transit fares rise in March",
        "source": "news",
        "quote": "the monthly adult pass goes from $92 to $96 on March 1"
      }
    ],
    "sources": [
      { "url": "https://transit.northbridge.example/fares", "title": "Fares and passes", "source": "web", "how": "live", "cited": true },
      { "url": "https://news.northbridge.example/2026/02/fares-rise-in-march", "title": "Transit fares rise in March", "source": "news", "how": "cached", "cited": true },
      { "url": "https://transit.northbridge.example/passes/students", "title": "Student passes", "source": "web", "how": "cached", "cited": false },
      { "url": "https://forum.northbridge.example/t/fare-increase", "title": "Fare increase thread", "source": "web", "how": "search", "cited": false }
    ],
    "uncited_removed": 1
  },
  "request_id": "req_01JD4F9A3N7S0U4W6Y8A",
  "usage": {
    "credits": 8.8,
    "cost_usd": 0.0088,
    "breakdown": {
      "search": 2,
      "search_content": 2,
      "extract_cached": 0.5,
      "extract_live": 0.5,
      "model_input": 2.6,
      "model_output": 1.2
    },
    "steps": {
      "searches": 2,
      "pages_read": 4,
      "places_lookups": 0,
      "model_calls": 2,
      "input_tokens": 6500,
      "output_tokens": 600
    }
  },
  "warnings": []
}
```

The site and its numbers are made up for this example.

- **`answer`** is the text. Every statement ends with one or more `[n]`.
- **`citations[n-1]`** is the page behind `[n]`, and `quote` is the words of that page that support the statement. The quote was found, whole and unbroken, in the text we fetched.
- **`sources`** is every page the writer was given. `how` says where its text came from: with the search result (`search`), a stored copy (`cached`), a live fetch (`live`) or a places lookup (`places`). `cited` says whether the answer uses it. Here three pages were fetched, two from stored copies and one live, and those are the `extract_cached` and `extract_live` lines of `usage`. The fourth came with its search result, so it was not fetched and has no line of its own.
- **`uncited_removed`** is 1 here: the writer made three statements, and one had no quote that was in its page, so it was removed.
- **`usage`** is 0 until the run ends. Then it is the one charge, line by line, with the counts behind it in `usage.steps`.
- **`stop_reason`** says why the run stopped. `done` goes with `completed`. An `incomplete` run says `budget`, `time`, `no_sources`, `no_support` or `no_answer`: see [Errors](https://millionshort.com/docs/agent/errors#runs-that-end-incomplete).

To fetch the result without the steps, ask for it alone. While the run is going this answers `202` with `"ready": false` and a `Retry-After` header; that is not an error.

```bash
curl https://api.millionshort.com/v1/agent/$AGENT_ID/results \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

import requests

r = requests.get(
    f"https://api.millionshort.com/v1/agent/{os.environ['AGENT_ID']}/results",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch(`https://api.millionshort.com/v1/agent/${process.env.AGENT_ID}/results`, {
  headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
});
if (!res.ok) throw new Error(`GET /v1/agent/…/results failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

## 4. Ask for data with a schema

Send a JSON Schema as `schema`, and the answer comes back as `output` in that shape.

```bash
curl https://api.millionshort.com/v1/agent \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Northbridge Transit fares in 2026: the monthly adult pass, the single fare, and when prices last changed.",
    "schema": {
      "type": "object",
      "properties": {
        "monthly_pass": { "type": "number" },
        "single_fare": { "type": "number" },
        "currency": { "type": "string" },
        "last_changed": { "type": "string", "description": "YYYY-MM-DD" }
      }
    }
  }'
```

```python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent(
    "Northbridge Transit fares in 2026: the monthly adult pass, the single fare, and when prices last changed.",
    schema={
        "type": "object",
        "properties": {
            "monthly_pass": {"type": "number"},
            "single_fare": {"type": "number"},
            "currency": {"type": "string"},
            "last_changed": {"type": "string", "description": "YYYY-MM-DD"},
        },
    },
)
done = client.wait_agent(run.id)
print(done.output)
print(done.field_citations, done.uncited_fields)
```

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent(
  'Northbridge Transit fares in 2026: the monthly adult pass, the single fare, and when prices last changed.',
  {
    schema: {
      type: 'object',
      properties: {
        monthly_pass: { type: 'number' },
        single_fare: { type: 'number' },
        currency: { type: 'string' },
        last_changed: { type: 'string', description: 'YYYY-MM-DD' },
      },
    },
  },
);
const done = await client.waitAgent(run.id);
console.log(done.output);
console.log(done.field_citations, done.uncited_fields);
```

The parts of the result that differ:

```text
"answer": null,
"output": { "monthly_pass": 96, "single_fare": 3.25, "currency": "CAD", "last_changed": "2026-03-01" },
"field_citations": { "monthly_pass": [1], "last_changed": [1, 2], "currency": [1] },
"uncited_fields": ["single_fare"],
```

`field_citations` gives the citation numbers of each field. `uncited_fields` lists the fields that are filled and that no checked quote supports: here the run filled `single_fare`, and could not show a quote for it. The value is returned, and you are told. [Guides](https://millionshort.com/docs/agent/guides#fill-a-table-of-facts-from-a-schema) says what to do with such a field.

## 5. Follow the steps as they happen

```text
GET https://api.millionshort.com/v1/agent/{id}/events
```

The steps of a run as server-sent events: `agent.step` for each step, then one `agent.done` when the run has ended.

```bash
curl "https://api.millionshort.com/v1/agent/$AGENT_ID/events" -N \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent("What changed in Northbridge Transit fares in 2026?", processor="lite")
for event in client.stream_agent_events(run.id):
    print(event["event"], event["data"])
```

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent('What changed in Northbridge Transit fares in 2026?', { processor: 'lite' });
for await (const { event, data } of client.streamAgentEvents(run.id)) {
  console.log(event, data);
}
```

```text
event: agent.step
data: {"seq":1,"type":"started","at":"2026-11-20T14:02:11Z","processor":"lite","model":"fast"}

event: agent.step
data: {"seq":2,"type":"plan","at":"2026-11-20T14:02:12Z","searches":[{"query":"Northbridge Transit fare change 2026","source":"news"}]}

event: agent.done
data: {"id":"agt_01jd4f8q2m6r9t3v5x7z0b1c2d","status":"completed","stop_reason":"done","usage":{...}}
```

- A stream stays open for 5 minutes at most. The run goes on after it closes. If a stream ends with no `agent.done`, open it again with `?after=` and the last `seq` you saw.
- `agent.done` carries `id`, `status`, `stop_reason` and `usage`. It does not carry the answer: fetch that with `GET /v1/agent/{id}` or `/results`.
- A team may have 2 streams open at once. The stream of a run that has already ended answers at once and is not counted.
- Streams also share a limit across all teams. When it is full, opening one answers `429 CAPACITY`: poll instead.
- Closing a stream does not cancel the run.

## 6. Or be told by webhook

Register an endpoint once ([Webhooks](https://millionshort.com/docs/webhooks)), then name it when you start a run:

```bash
curl https://api.millionshort.com/v1/agent \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "What changed in Northbridge Transit fares in 2026?",
    "webhook_id": "wh_01jd3v9k2m8q4r6s0t1u2v3w4x"
  }'
```

```python
import os

import requests

r = requests.post(
    "https://api.millionshort.com/v1/agent",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    json={
        "prompt": "What changed in Northbridge Transit fares in 2026?",
        "webhook_id": "wh_01jd3v9k2m8q4r6s0t1u2v3w4x"
    },
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch('https://api.millionshort.com/v1/agent', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "prompt": "What changed in Northbridge Transit fares in 2026?",
    "webhook_id": "wh_01jd3v9k2m8q4r6s0t1u2v3w4x"
  }),
});
if (!res.ok) throw new Error(`POST /v1/agent failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

When the run ends, however it ends, an `agent.completed` event is delivered there. Its `data` has `id`, `status`, `stop_reason` and `credits_used`. It does not carry the answer: fetch the run by its `id`. The event is signed like every other delivery.

## 7. Cancel a run

```bash
curl -X DELETE https://api.millionshort.com/v1/agent/$AGENT_ID \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

import requests

r = requests.delete(
    f"https://api.millionshort.com/v1/agent/{os.environ['AGENT_ID']}",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch(`https://api.millionshort.com/v1/agent/${process.env.AGENT_ID}`, {
  method: 'DELETE',
  headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
});
if (!res.ok) throw new Error(`DELETE /v1/agent/… failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

A run that has not started ends at once and costs nothing. A run in progress shows `cancelling` until its current step stops, then `cancelled`; the work it did is charged, with no minimum, and the rest of the hold is handed back. Cancelling a run that has already ended changes nothing and returns it.

In the SDKs this is `cancel_agent(id)` in Python and `cancelAgent(id)` in TypeScript.

## Next

- [Parameters](https://millionshort.com/docs/agent/parameters): every field of the request and of the result, the processors and the tiers of `model`.
- [Guides](https://millionshort.com/docs/agent/guides): a briefing held to your sources, a table of facts, choosing a processor and a cap, and use over MCP.
- [Pricing and limits](https://millionshort.com/docs/agent/pricing): what a run is charged for.
- [Errors](https://millionshort.com/docs/agent/errors): what is refused, and how a run can end.
