# Mandi Traders List — Clean, Dedupe & Score Your APMC File — API reference

The detail an integrator needs and a buyer does not: linked from the README's Integrations section. `/actor-deploy
--assets` hosts this file next to the images.

## Tested combinations

Every row is an input the test suite and the review runs start.

| Call | What runs | Input |
|---|---|---|
| Daily test / first agent call | the free demo on the sample rows, nothing charged | `{}` |
| Demo, as the form opens | the same free demo | `storage-example/INPUT.json` |
| Your file, capped | the reader on one sample file, AI off, ≤ $0.05 | `storage-example/INPUT.live.json` |
| AI on | the same sample rows with the AI verdict | `storage-example/INPUT.ai.json` |
| AI with your own key | the AI through your provider key | `{"enableAi": true, "llmProvider": "byok", "llmModel": "google:gemini-3.5-flash-lite", "llmApiKey": "…"}` + your file |
| Your files | your lists, read and merged | `{"sourceMode": "files", "keyValueStoreId": "<store>"}` |
| PortLess call | the same — `list` + `fileUrls` reads the files | `{"sourceMode": "list", "fileUrls": [ … ], "states": ["MH"], "commodities": ["onion"]}` |
| Your own rows | licensee rows as JSON | `{"sourceMode": "list", "itemsList": [ … ]}` (fields: README → List-mode rows) |
| A dataset you have | a dataset's licensee rows | `{"sourceMode": "dataset", "datasetId": "<id>"}` |
| A pasted table | the table read like a CSV file | `{"pastedTable": "Name of the Firm	Lic No	…
…"}` |
| Only rows with an e-mail | contacts from your file, rows without an e-mail dropped (never charged) | `{"includeContacts": true, "requireEmail": true}` + your file |

## API-only inputs

Hidden from the Console form, read from the API.

| Field | Default | Effect on cost and time |
|---|---|---|
| `asOfDate` | today (India time) | the day validity is measured on — changes statuses and the minimum-validity filter, so what is charged |
| `expiringWithinDays` | 90 | the `expiring` window — no cost effect unless `targetFlags` has `expiring` |
| `commodityMatch` | `exact` | `group` also keeps same-group traders at +15 — more rows, more charged |
| `sheetName` | every sheet with a header row | one sheet only — fewer rows |
| `dateOrder` | `auto` (day first) | how `03/04/2026` is read — no cost effect |
| `fileState` / `fileMandi` / `fileDistrict` | — | the place of a list that names it only in its title — no cost effect |
| `fileUrl` | — | one link, merged into `fileUrls` |
| `recordKeys` | every list file of `keyValueStoreId` | only these records of the picked store — fewer files read |
| `listAsOf` | — | the date your copy was issued or bought → `dataPeriod` — no cost effect |
| `suppressionList` / `allowList` | — | never output / never filtered firm names or licence numbers |
| `aiCandidateMultiplier` | 2 | AI shortlist = this × `maxQualified`: up to twice the AI calls, time and tokens |
| `autoSwitchToLive` | true | a file link next to the sample on the Console reads your file; `false` keeps the free demo |
| `failOnSourceError` | false | `true`: a run whose files could all not be read ends FAILED (alerts fire) |
| `dedupeTtlDays` | 0 | days a delivered trader stays remembered (0 = forever) |
| `historyDatasetName` | — | a named dataset every run appends its rows to — no cost effect |
| `dedupeStoreName` | `apmc-traders-ai-seen` | one named memory per client; a new name re-delivers (and re-charges) |
| `webhookUrl` / `webhookBatchSize` / `webhookHeaders` / `webhookSecret` | — / 1 | the row webhook — no cost effect |
| `llmModel` | `anthropic/claude-haiku-4.5` (Apify) | another model: other token cost and speed |
| `slackWebhookUrl` / `teamsWebhookUrl` / `googleChatWebhookUrl` / `discordWebhookUrl` / `telegramUrl` | — | per-service aliases of **Send alerts to** — no cost effect |
| `minValidityDays` | 0 | drop licences that expire in fewer days — fewer rows, less charged (the onion / chilli presets set 30) |
| `includeExpired` | false | keep expired, cancelled and suspended licences for a compliance view — more rows (the compliance preset sets it) |
| `targetFlags` | — | keep only rows with one of these flags (`expiring`, `missing_licence_number` …) — fewer rows |
| `maxToProcess` | every licensee | not needed — every licensee of the list is scored in memory |

## Which delivery field wins

Every URL is posted once. `fileUrl` is merged into `fileUrls` (the union, duplicates dropped). An explicit per-service field (`slackWebhookUrl` …) wins for its service over the same service's URL in `sendAlertsTo`; `webhookUrl` gets the rows as JSON, the alert fields and `notifyEmail` the digest — the merge rule in one line.

The AI reserve: while the AI is unavailable, rule-scored rows use your free traders down to a reserve of 5 kept for your first AI rows (`OUTPUT.chargeSplit.freeKeptForAi`).

## Every field of a row

| Field | Description |
|---|---|
| `itemId`, `rowId`, `rowType`, `name`, `url`, `contactRoute` | `url` = a web search for the firm at its mandi ("Find it on the web"); `contactRoute` = e-mail, else phone, else `url` |
| `label`, `score`, `ruleScore`, `fitScore`, `assessedBy`, `scoreReasons`, `fitReason`, `pitchAngle`, `recommendedNextStep`, `aiModel` | Tier, scores, rules or AI text |
| `buyerSegment`, `redFlags`, `questionToAsk` | AI only — null on a rules row |
| `whatsappLink` | wa.me with the pitch prefilled — only with `includeContacts` and a mobile in your file |
| `generatedText` | Same value as `pitchAngle` — deprecated alias, removed in 0.3, 2027-03-01 |
| `traderName`, `traderNameLatin`, `alsoKnownAs`, `licenceNumber`, `licenceNumberRaw`, `licenceType`, `licenceTypeRaw` | The licence |
| `mandi`, `mandiLatin`, `subYard`, `otherMandis`, `district`, `state`, `stateName`, `address`, `pincode` | The place |
| `commodities`, `commodityGroups`, `commoditiesRaw` | Slugs, groups, as published |
| `validFrom`, `validUntil`, `licenceStatus`, `daysToExpiry` | Dates as published in your list; status on `asOfDate` |
| `phone`, `email`, `contactPerson` | null unless `includeContacts` is on and your file has them |
| `missingFields`, `flags`, `targetFlagsMatched`, `source`, `sourceUrl`, `sourceFile`, `sourceRows`, `listAsOf`, `dedupeKey`, `chargedEvent`, `billedAs`, `fetchedAt` | `listAsOf` = the issue / purchase date of your copy (you give it), `fetchedAt` = when this run read your file |

## Flags

- `expired`
- `expiring`
- `cancelled`
- `suspended`
- `lifetime_licence`
- `validity_from_fy`
- `validity_unknown`
- `validity_inconsistent`
- `duplicate_merged`
- `merged_by_name`
- `possible_duplicate`
- `missing_licence_number`
- `missing_district`
- `missing_mandi`
- `commodities_unknown`
- `commodity_unmapped`
- `mandi_unmatched`
- `district_unmatched`
- `state_from_district`
- `mandi_from_sheet_name`
- `type_from_licence_number`
- `transliterated`
- `name_is_person_like`
- `sensitive_value_removed`
- `contact_from_buyer_file`

Meanings: the README → Output, and `src/rules.py → FLAG_DESCRIPTIONS`.

## Webhook body

What `webhookUrl` receives — the receiving end is built from this, never by trial run (gate
`check_webhook_body_example`, 2026-11-23 destination-rule-watch-ai V-205). Replace `{…}` with one real dataset item
from the first live run. Signed with `webhookSecret`: header `X-Signature: sha256=<HMAC-SHA256 of the raw body>`. A 429 / 5xx is retried once; failed rows are re-sent first on the next run.

`webhookBatchSize: 1` — one POST per trader:

```json
{
  "event": "trader.qualified",
  "runId": "a1B2c3D4e5F6g7H8i",
  "redelivery": false,
  "trader": {"itemId": "…", "dedupeKey": "…", "url": "https://…", "score": 82, "label": "hot"},
  "item": {"itemId": "…", "dedupeKey": "…", "url": "https://…", "score": 82, "label": "hot"}
}
```

`item` / `items` carry the same row(s) as the Actor's own key in every body — one receiver serves all of the
developer's Actors, and no hyphenated key needs bracket access.

`webhookBatchSize: N` — one POST per batch (the last one may be shorter):

```json
{
  "event": "traders.qualified",
  "runId": "a1B2c3D4e5F6g7H8i",
  "redelivery": false,
  "traders": [{"itemId": "…", "dedupeKey": "…"}, {"itemId": "…", "dedupeKey": "…"}],
  "items": [{"itemId": "…", "dedupeKey": "…"}, {"itemId": "…", "dedupeKey": "…"}]
}
```

A 429 / 5xx / network error is retried once after 2 s (15 s timeout); a POST that still fails is re-sent first on the
next run with `"redelivery": true` — upsert on `dedupeKey`.

## One dataset item

One real item from the 2026-11-24 AI run of the sample list (fictional firm):

```json
{
 "itemId": "6839ee6ea886",
 "name": "Warna Spice Exports",
 "label": "hot",
 "score": 95,
 "ruleScore": 70,
 "scoreReasons": [
  "Licensed exporter in Sangli yard with long-term licence validity through July 2029",
  "Trades key export commodities: turmeric and raisin",
  "Active licence status with nearly three years remaining before renewal"
 ],
 "fitScore": 95,
 "fitReason": "Warna Spice Exports is an active licensed exporter in Sangli, Maharashtra, dealing in turmeric and raisins with a valid licence extending to July 2029.",
 "pitchAngle": "Operating as an exporter in Sangli market, Warna Spice Exports is well-positioned for sourcing quality turmeric and raisins for your export operations. Given their valid licence through 2029, I recommend initiating direct discussions regarding their turmeric and raisin procurement capacity and grading standards.",
 "generatedText": "Operating as an exporter in Sangli market, Warna Spice Exports is well-positioned for sourcing quality turmeric and raisins for your export operations. Given their valid licence through 2029, I recommend initiating direct discussions regarding their turmeric and raisin procurement capacity and grading standards.",
 "recommendedNextStep": "Contact Warna Spice Exports at the Sangli mandi to discuss export-grade specifications and available volumes for turmeric and raisins.",
 "contactRoute": "https://www.google.com/search?q=%22Warna+Spice+Exports%22+Sangli+Sangli+APMC",
 "aiModel": "google:gemini-3.5-flash-lite",
 "assessedBy": "ai",
 "rowType": "trader",
 "rowId": "ca732f8010aae8c9",
 "source": "buyer_list:list",
 "sourceUrl": "itemsList",
 "traderName": "Warna Spice Exports",
 "traderNameLatin": null,
 "alsoKnownAs": [],
 "licenceNumber": "SNG/EX/2024/0012",
 "licenceNumberRaw": "SNG/EX/2024/0012",
 "licenceType": "exporter",
 "licenceTypeRaw": "निर्यातदार",
 "mandi": "Sangli",
 "mandiLatin": null,
 "subYard": null,
 "otherMandis": [],
 "district": "Sangli",
 "state": "MH",
 "stateName": "Maharashtra",
 "address": "नमुना औद्योगिक वसाहत, सांगली",
 "pincode": null,
 "commodities": [
  "turmeric",
  "raisin"
 ],
 "commodityGroups": [
  "spices",
  "dry_fruits"
 ],
 "commoditiesRaw": [
  "हळद",
  "बेदाणा"
 ],
 "validFrom": "2024-08-01",
 "validUntil": "2029-07-31",
 "licenceStatus": "active",
 "daysToExpiry": 980,
 "phone": null,
 "email": null,
 "contactPerson": null,
 "missingFields": [],
 "sourceFile": "itemsList",
 "sourceRows": [
  {
   "file": "itemsList",
   "sheet": null,
   "page": null,
   "rowNumber": 17
  }
 ],
 "listAsOf": null,
 "flags": [
  "state_from_district"
 ],
 "targetFlagsMatched": [],
 "url": "https://www.google.com/search?q=%22Warna+Spice+Exports%22+Sangli+Sangli+APMC",
 "dedupeKey": "lic:SNG/EX/2024/0012|sangli",
 "chargedEvent": "demo",
 "billedAs": "qualified-trader-ai",
 "fetchedAt": "2026-11-24T10:21:38+00:00"
}
```

## `OUTPUT` record keys

- `ok` — bool: `false` when any file was refused or no file could be read (rows of readable files still delivered)
- `rows` — int: traders delivered · `costUsd` — number: what this run charged · `dataPeriod` — `YYYY-MM` of `listAsOf` | null
- `refused` — array: `{source, sheet?, reason}` per refused file (`scanned_pdf_no_text_layer`, `legacy_font_pdf`,
  `government_host_not_fetched`, `not_a_data_file`, `columns not recognised …`, `live`)
- `queries` — array: per file / sheet `{file, fileName, format, sizeBytes, sheet, page, headerRow, language, confidence,
  mapping, headers, rowsRead, rowsKept, skipped, droppedColumns, aiMapping}`
- `asOfDate`, `listAsOf` — ISO date | null · `rowsRead`, `entities`, `duplicatesMerged`, `sensitiveValuesRemoved` — int
- `skipped` — `{total_row, empty, no_identity}` · `dropped` — `{labour_licence, state, mandi, licence_type, commodity,
  expired, below_min_validity, seen_in_previous_run, below_min_score}`
- `droppedColumns` — `{aadhaar, pan, bank, gstin, other_id}` (non-zero only)
- `licenceStatusCounts` — `{active, expiring, expired, lifetime, cancelled, suspended, unknown}` · `missingFieldCounts` — object
- `languages` — `{english, hindi, marathi, kannada, telugu, punjabi: files}` · `contactsIncluded` — bool · `flags` — array
  (`truncated`, `low_mapping_confidence`, `pdf_pages_without_text`)
- `statusText` — str: the FR-15 sentence · `outcome` — `ok` · `empty` · `files_refused` · `error` · `mode` — `demo` ·
  `files` · `list` · `dataset`
- `exportersInput` + `exportersActorUrl` — the APEDA Registered Exporters input for this run's commodities and states, ready to paste (traders → exporters).
- `stats`, `chargedEvents`, `chargeSplit`, `aiCoverage`, `aiTokens`, `timing`, `webhook`, `trend`, `history`,
  `nextSteps` — as in every Actor of this developer
