# Chosŏn API (v1)

Everything the Chosŏn app does with a study, over HTTPS: upload survey responses, fit the model, read the results,
run the simulators. Use it to build your own interface, connect another tool, or let an AI assistant run an
analysis for you ([setup](#use-chosŏn-from-your-ai-assistant)). This page is written to be read by people and by coding assistants; it is the whole reference.

- Base URL: `https://quantecarlo.com/api/v1`
- Auth: `Authorization: Bearer chs_...` (an API key) on every request.
- Bodies and responses are JSON, except file uploads (multipart form) and downloads (CSV, Excel).
- Access: paid plans. Your plan's limits (respondents, products, tasks, queued jobs) apply exactly as in the app.

## API keys

Create a key in the app: sign in, click API at the top, then Create key. The key is shown once; store it like a password (an
environment variable such as `CHOSON_API_KEY`, never in code or a shared file). Up to 10 active keys per account;
revoke a key in the same place and it stops working at once. Keys stop working if the account moves to the free
plan. Keys cannot create or revoke keys or change the account.

Limit: 120 requests per minute per key. Over it you get `429` with the wait in seconds.

```bash
export CHOSON_API_KEY=chs_...
curl -s https://quantecarlo.com/api/v1/me -H "Authorization: Bearer $CHOSON_API_KEY"
```

`GET /me` returns your plan (`tier`) and its limits (`limits`), and the GPU minutes used this month.

## Use Chosŏn from your AI assistant

Ask your assistant to run the study for you: upload the data, fit the model, read the results, run simulations. It
works in any assistant that supports MCP, the open standard for connecting assistants to tools (Claude Desktop,
Claude Code, Cursor, VS Code and others). The connector is open source: [choson-mcp](https://github.com/sign-of-fourier/choson-mcp).

1. Create an API key (above).
2. Install [uv](https://docs.astral.sh/uv/) if you don't have it, then add this to your assistant's MCP settings:

   ```json
   {"mcpServers": {"choson": {"command": "uvx", "args": ["choson-mcp"],
     "env": {"CHOSON_API_KEY": "chs_..."}}}}
   ```

   In Claude Code: `claude mcp add choson -e CHOSON_API_KEY=chs_... -- uvx choson-mcp`
3. Ask, for example: "Fit my CBC file and show me what happens to shares if we drop the 12-pack."

Before a fit the assistant shows the hardware, the estimated time and the 2-hour maximum, and asks you before it
starts. Fits count against your Chosŏn plan; your assistant's own subscription is separate.

Your data passes through your assistant's provider on the way to us, under that provider's terms. If that matters
for a study, use the API or the app directly.

## Cost and time limits

Every fit is stopped at 2 hours, whatever its size. To see what a fit will run on before starting it, send the
same settings with `"dry_run": true`: the response gives `compute` (the hardware: `cpu`, `modal_cpu`, `t4` or
`h100`), `estimated_seconds` and `max_seconds` (7,200) and queues nothing. Fits that need a GPU run only on plans
that include one. You can cancel any queued or running fit or search.

## The flow

1. `POST /projects` with `{"name": "Drinks", "kind": "cbc"}`. Kinds: `cbc`, `mbc`, `maxdiff`, `pricing`,
   `concept`, `volumetric`.
2. `POST /projects/{pid}/data` with the responses file (multipart field `responses`). Returns a dataset with a
   validation `report` (errors, warnings, summary) and, for CBC, the `design` (attributes and levels).
3. CBC only: check the design. If it was inferred (`design_inferred: true`), correct it with
   `PUT /datasets/{did}/design` (the same JSON shape, edited). Fix any `report.errors` before fitting.
4. `POST /datasets/{did}/fits` with settings (all optional). Returns the fit with `status: "queued"`.
5. Poll `GET /fits/{fid}` every few seconds until `status` is `done`, `failed` (see `error`) or `cancelled`.
   `progress.stage` says what it is doing.
6. `GET /fits/{fid}/result` for the results JSON; then the simulators below.

```bash
H="Authorization: Bearer $CHOSON_API_KEY"; B=https://quantecarlo.com/api/v1
pid=$(curl -s -X POST $B/projects -H "$H" -H 'content-type: application/json' -d '{"name":"Drinks"}' | jq -r .id)
did=$(curl -s -X POST $B/projects/$pid/data -H "$H" -F responses=@responses.csv | jq -r .id)
fid=$(curl -s -X POST $B/datasets/$did/fits -H "$H" -H 'content-type: application/json' -d '{}' | jq -r .id)
until curl -s $B/fits/$fid -H "$H" | jq -e '.status | test("done|failed|cancelled")' >/dev/null; do sleep 5; done
curl -s $B/fits/$fid/result -H "$H" > result.json
```

## Data formats

**CBC** (choice-based conjoint): long CSV, one row per alternative shown, `resp, task, alt`, one column per
attribute, `chosen` (0/1, one 1 per task). A "none" alternative has empty attribute cells. A column named `price`
with numbers is treated as price (linear). A Sawtooth `.CHO` file is also accepted.

```
resp,task,alt,brand,flavor,pack,price,chosen
1,1,1,Nova,Citrus,500ml can,1.99,0
1,1,2,Surge,Original,250ml can,1.49,1
1,1,3,Volt,Mango,500ml can,2.99,0
1,1,4,Apex,Citrus,500ml can,2.49,0
1,1,5,,,,,0
```

Optional: a design JSON as the multipart field `design`; respondent covariates (one row per respondent, `resp`
plus columns such as age or region) with `POST /datasets/{did}/covariates` (multipart field `file`).

The design:

```json
{"attributes": [
   {"name": "brand", "levels": ["Apex", "Nova", "Surge", "Volt"], "kind": "categorical"},
   {"name": "price", "levels": [1.49, 1.99, 2.49, 2.99], "kind": "linear"}],
 "none": true, "price": "price"}
```

**MBC** (menu): `resp, menu, item, price, bought` (0/1). Every menu lists every item; at least 4 menus per
respondent, the same number for everyone.

**MaxDiff**: `resp, set, item, best, worst` (0/1); one best and one worst per set, at least 3 items per set.

**Pricing**: Van Westendorp, one row per respondent: `too_cheap, cheap, expensive, too_expensive` (`resp`
optional). Gabor-Granger, one row per price asked: `resp, price, buy` (0/1, or 1-5 intent).

**Concept / claims tests**: `resp, item, metric, rating` (whole numbers), optional `position` (order shown).

**Volumetric CBC**: as CBC with `quantity` (0 or more) instead of `chosen`, plus `budget` (the most the respondent
would spend on the category on one occasion; the same on each of their rows).

## Fit settings (`POST /datasets/{did}/fits`)

| field | values | default | meaning |
|---|---|---|---|
| `taste` | `none`, `diagonal`, `full` | `diagonal` | how tastes vary across people: not at all, each on its own, with correlations (`full`: paid plans) |
| `error_shares` | list of attribute names | every categorical attribute | attributes that drive switching: products sharing a level of these substitute more for each other |
| `holdout` | `last`, `none` | `last` | hold out each respondent's last task to score prediction |
| `hb_baseline` | true / false | false | also fit HB logit for comparison (adds time) |
| `constraints` | `{"price": "decreasing"}` | none | force an attribute's utility to rise or fall with its level |
| `covariates` | list of covariate columns | none | let these move each respondent's mean tastes |
| `classes` | 2-6 | none | also fit a latent class model with this many segments |
| `compute` | `auto`, `cpu`, `t4`, `h100` | `auto` | hardware; `auto` picks by size and plan |
| `dry_run` | true / false | false | return the hardware, estimate and maximum without queuing |

For other modules most settings do not apply; MBC also takes `cross_prices` (true: every item's buy depends on every item's price), Gabor-Granger `unit_cost` (profit instead of revenue).

## Fits

- `GET /fits/{fid}`: status, settings, progress, error, timestamps.
- `POST /fits/{fid}/cancel`: cancels a queued fit at once, a running one within seconds.
- `GET /fits/{fid}/result`: the results JSON (below).
- `GET /fits/{fid}/respondents.csv`: per-respondent estimates.
- `GET /fits/{fid}/workbook.xlsx`: the study workbook (summary, importances, utilities, WTP, switching).
- `GET /fits/{fid}/excel-simulator.xlsx`: the CBC simulator for Excel (needs the Chosŏn add-in).
- `GET /fits/{fid}/segments?k=3`: taste segments from the per-respondent estimates (k optional).

### CBC result JSON

Every estimate is `{"est", "se", "lo", "hi"}`: the point and its 95% range.

- `derived.partworths`: utility of each level, per attribute (zero-centred within the attribute).
- `derived.importances`: share of the utility range per attribute.
- `derived.wtp`: willingness to pay per level, in price units (when there is a price).
- `params.b`: mean tastes as fitted (each level against the attribute's first level).
- `params.taste_sd`, `params.taste_corr`: how much tastes vary across people.
- `params.error_shares`: how much of each choice's randomness each attribute accounts for (0 to 1). Larger means
  products sharing that attribute's level are closer substitutes.
- `fit`: log-likelihood, AIC, BIC, `converged`, `holdout` (hit rate with 95% range, held-out log-likelihood) and
  `warnings` (read these: they say when results are rough).
- `baselines.logit` (and `baselines.hb_logit` when requested): the same data fitted by the comparison models.

## Simulators (CBC)

A shelf is a list of products, each a mapping from attribute to level. Use levels exactly as in the design; price
may be any number in the tested range. Up to 60 products. `models` defaults to `["model"]`; `GET
/fits/{fid}/simulate/models` lists what else the fit has (e.g. `logit`, `hb_logit`) and the covariate `groups`.
Pass `"group": "<name>"` to simulate one covariate group.

```json
{"products": [
  {"brand": "Apex", "flavor": "Citrus", "pack": "500ml can", "price": 1.99},
  {"brand": "Nova", "flavor": "Mango", "pack": "250ml can", "price": 1.49},
  {"brand": "Volt", "flavor": "Berry", "pack": "500ml can", "price": 2.49}]}
```

| route | extra fields | returns |
|---|---|---|
| `POST /fits/{fid}/simulate` | | share of each product and none, with 95% ranges |
| `POST /fits/{fid}/simulate/remove` | `remove` (index) | shares after removing one product and where its buyers go (diversion) |
| `POST /fits/{fid}/simulate/price-sweep` | `product` (index), `prices` (optional list) | shares across a range of prices for one product |
| `POST /fits/{fid}/simulate/elasticities` | | own- and cross-price elasticities |
| `POST /fits/{fid}/simulate/beats` | `a`, `b` (indexes) | the share of people who prefer product a to product b |
| `POST /fits/{fid}/simulate/forecast` | `occasions`, `prices`, `unit_costs`, `own` (indexes), optional `base` shelf and `hurdle` | units, revenue and profit with 95% ranges, change against the base, chance of clearing the hurdle |
| `POST /fits/{fid}/optimize` | `competitors`, `own` (products with levels to search), `objective`, `costs` | the best versions of your products against fixed competitors |

The shape of a `simulate` response (numbers illustrative):

```json
{"alternatives": ["product 1", "product 2", "product 3", "none"],
 "models": {"model": [{"est": 0.388, "lo": 0.301, "hi": 0.472}, {"est": 0.331, "lo": 0.259, "hi": 0.402},
                      {"est": 0.158, "lo": 0.110, "hi": 0.213}, {"est": 0.123, "lo": 0.081, "hi": 0.170}]}}
```

### Searches (queued; poll with GET on the same route)

| route | body | answers |
|---|---|---|
| `POST /fits/{fid}/range` | `products`, `k` (and `k_min`), `mode`, `own`, `objective`, `must_keep`, `must_drop` | which k products to keep |
| `POST /fits/{fid}/recommend` | `products`, `k`, `must_keep`, `must_drop` | which k products to recommend when a person takes at most one |
| `POST /fits/{fid}/test-next` | `candidates`, `control`, `k`, `objective`, `min_lift` | which k products to test against a control |

`GET` on the same route returns the latest search with its status and result; `POST /jobs/{jid}/cancel` stops it.

## Other modules

| route | module | body |
|---|---|---|
| `POST /fits/{fid}/menu-simulate` | MBC | `prices` (item to price), `offered`, `visits` |
| `POST /fits/{fid}/menu-sweep` | MBC | `item`, `prices` |
| `POST /fits/{fid}/menu-turf` | MBC | `prices`, `candidates`, `always`, `k_max` |
| `POST /fits/{fid}/maxdiff-shares` | MaxDiff | `offered` (items) |
| `POST /fits/{fid}/maxdiff-turf` | MaxDiff | `top`, `candidates`, `always`, `k_max` |
| `POST /fits/{fid}/volume-scenario` | Volumetric | `products` (with price), optional `base` |
| `POST /fits/{fid}/concept-reach` | Concept | `metrics`, `k_max`, `always`, `never` |

## Survey design

- `POST /cbc/design`: balanced CBC tasks for fielding. Body: `attributes` (`name`, `levels`, `price`), `products`
  per task, `tasks`, `versions`, `none`, `overlap`, `prohibitions`. Returns the balance report and the design.
- `POST /maxdiff/design`: balanced MaxDiff sets. Body: `items`, `set_size`, `sets`, `versions`. Returns the report
  and the design as CSV.

## Errors

| status | meaning |
|---|---|
| 400 | the request or the data has a problem; `detail` says what (for fits over a plan limit, `detail.problems`) |
| 401 | missing, invalid or revoked key |
| 403 | the plan does not include this |
| 404 | no such project, dataset or fit on your account |
| 429 | over 120 requests per minute, or too many queued jobs for your plan |

## Reading results well

- Report each number with its 95% range; differences whose range includes 0 are not established.
- Read `fit.warnings` before drawing conclusions; they flag small samples and rough estimates.
- For questions about substitution (what happens if a product is removed or reprices, which products compete),
  use `simulate/remove` and `simulate/elasticities`, not part-worths alone.
- Compare against `baselines` to see what the switching structure adds on your data.

Full OpenAPI schema: `https://quantecarlo.com/api/openapi.json` (the `/v1` paths).
