Colony Colony Segmentation

Audience Segmentation API

Overview

New to the codebase? The Developer guide explains how the data is stored and how the service is wired together, with diagrams.

The Audience Segmentation API analyses listener behaviour and automatically groups listeners into meaningful engagement segments. It combines RFM scoring, semantic vector search, AI inference, predictive intelligence and an AI agent layer to build a complete audience intelligence platform for radio stations.

Beyond reading the audience, a station can act on it: save audiences that stay up to date, set listeners aside in a retarget bucket, export exactly the columns it needs, and enrich listeners with AI on demand.


Authentication

All /api/v1/* endpoints require an API key in the request header:

X-Segmentation-Key: <your-api-key>

Public routes — no authentication required:

Requests without a valid key return:

{ "detail": "Invalid or missing API key" }

HTTP Status Codes

Code Meaning When
200 OK Request succeeded
201 Created Resource created (audiences)
400 Bad Request Invalid parameters
401 Unauthorized Missing or invalid X-Segmentation-Key
402 Payment Required AI credits exhausted, not loaded, or AI paused
404 Not Found Company, listener or audience not found
429 Too Many Requests A part of the product has used its monthly AI limit (only that part is blocked)
409 Conflict Action not possible now (e.g. an enrichment is already running, nothing to replace)
422 Unprocessable Could not parse brief or invalid input
503 Service Unavailable Qdrant or OpenAI unavailable

Error response format

{
  "detail": "No profile found for 27821234567 at company <company_id>"
}

Common error scenarios

Scenario Status Detail
Missing API key 401 "Invalid or missing API key"
Wrong API key 401 "Invalid or missing API key"
Unknown company 404 "No profiles found for company {company_id}" (not for the dashboard segment endpoints, which return zeros)
No AI credits 402 "AI credits exhausted. Please contact Colony to top up."
AI paused 402 "AI usage paused for this station. Reason: …"
Monthly limit 429 "Monthly limit reached for {part} ({n} credits). It resets on the 1st."
Enrichment running 409 "An enrichment is already running for this station."
Nothing to replace 409 "Nothing is in conflict with a confident AI inference"
Unknown listener 404 "No profile found for {originator} at company {id}"
Unknown audience 404 "Audience {id} not found for company {id}"
Already erased 400 "Profile already erased"
Brief too vague 422 "Could not parse brief — please provide more detail"
Search unavailable 503 "Search unavailable: {reason}"

How Segmentation Works

RFM Scoring

Score Measures Range
Recency Days since last interaction 1–5 (5 = most recent)
Frequency Interactions in last 30 days 1–5 (5 = highest)
Momentum Trend vs previous 30 days -1 / 0 / +1

Seven Primary Segments

Priority Segment Behaviour
0 new_listener First interaction within the last 7 days
1 super_fan Recent, frequent, multi-channel, stable/growing
2 show_loyalist Same show ≥60%, stable/growing
3 competition_chaser 70%+ competition entries, active within 60d
4 occasional_engager Active within 30d
5 at_risk Last seen 30–60d, declining momentum
6 dormant No recent engagement

How Demographics Are Populated

1. Survey answers — structured profile questions.

2. USSD/bot conversations — Q&A extraction, SA ID → gender + age auto-derived.

3. ORE signals — extracted from every interaction by live-core:

4. Free text extraction — SA ID number (13 digits) detected via regex. Gender and age group derived automatically.

5. AI inference — run on demand when a producer clicks AI Enrichment on a listener (or enriches a segment in bulk). Cached 30 days. Declared values are never overwritten automatically.

Caching

The dashboard's counts scan every listener of a station. That takes about a second at 100,000 listeners and much longer at a million, so the results are stored and served from the store.

View Fresh for Served expired for
Segment summary, list, insights, tags 5 minutes 24 hours
Freshness (when the data last changed) 1 minute 24 hours
Breakdown, completeness and cross-channel, whole station 15 minutes 24 hours
The same, with a filter 1 hour 24 hours

What resets them:

Event Effect
The nightly recalculation Every whole-station view is worked out again (NIGHTLY_WARM_CACHE_ENABLED), so the first person in the morning gets them instantly
The Refresh button (POST /segments/{id}/refresh) Drops the station's stored views (AI insights are kept), so the next requests are worked out from live data
An erasure Drops the station's stored views
Enrichment, topic edits, audience refreshes, consent changes Nothing is dropped: they show within the times above, or on Refresh

GET /segments/{id}/freshness carries data_updated_at. The dashboard asks for it every minute while the tab is open and, when it moves on, quietly reloads its numbers, so new data appears without a refresh. To work a station's views out ahead of time by hand: PYTHONPATH=. python jobs/warm_dashboard.py <company_id|all>.


Interests and Product Affinity

A listener's interests (inferred_interests) and product affinities (inferred_product_affinity) come from two places, and interest_sources says which, per value: activity, ai or both.

interest_sources looks like { "interests": { "food": "activity", "cooking": "ai" }, "product_affinity": { "FMCG": "both" } }. It is returned on the listener profile and in the enrich response.

Two flags on each profile decide what a listener may be used for. They are overall, not per channel, and an unknown or missing flag counts as not consented.

Flag Meaning Needed for
permission Consent to process their data AI enrichment (single and bulk)
opt_in Marketing consent Adding to the retarget bucket, and exports

The default is to leave listeners without consent out. Enrichment, adding to the bucket and exporting each do this unless the request sends "include_unconsented": true. Where a request leaves people out, the reply says how many (without_permission or excluded). The choice to include them belongs to the station: every time it is made, the service records who asked (requested_by), when, for what and how many listeners, in consent_overrides, and never changes it afterwards.

Permission for social channels and email. These channels do not send us a consent record, so permission and opt-in would otherwise stay empty. Under POPIA someone who contacts the station can be treated as allowing their data to be processed for that conversation, so permission is set to true. Whether that also covers marketing is not settled, so opt-in is left alone. A listener who writes to the station on email, Twitter, Facebook, Instagram or TikTok with no consent record has permission true (implied), so they can be enriched. opt_in is never implied, so they still stay out of the retarget bucket and exports until they opt in. It is only a default:

The channels are the IMPLIED_PERMISSION_CHANNELS setting (an empty list turns it off). Each channel's entry in consent_by_channel carries "implied": true while it is only implied. For listeners stored before this, run scripts/db/backfill_implied_permission.py (a dry run first).

POST /api/v1/retarget/{company_id}/check and POST /api/v1/export/{company_id}/check return the counts first (total, without_opt_in) so a client can ask before it adds or exports.


Adding a New Station

Run everything from the segmentation service folder. In production, run it inside the segmentation-worker container and put PYTHONPATH=/app in front of each command (locally use PYTHONPATH=.).

Replace <id> with the station's company ID. Do one station at a time, outside busy hours.

Colony staff can also run the backfill (step 1) and the recalculation (step 3) from the admin page at /admin (sign in with the live-core login) instead of the terminal; it runs the same scripts. See the developer guide.

Order matters: backfill first, switch the segmentation plugin on last. The backfill reads the history from live-core with the shared key and does not need the plugin. The plugin (route app.profiles.segmentation) is what makes live-core send the station's new interactions to this service and what lets the station see the dashboard ("Segmentation isn't available" until then). Turning it on at the end means the station never sees a half-loaded dashboard. See step 4.

Step 1. Backfill the history

./scripts/backfill_chunks.sh <id> <start date> [end date] [workers] [page size] [chunk size]
Argument What it is Default
<id> The station required
<start date> First day to fetch, YYYY-MM-DD required
[end date] Last day to fetch. Write - to mean today and still set the arguments after it today
[workers] Pages fetched at once 1
[page size] Interactions per page (most 1000) 500
[chunk size] weekly, monthly or yearly weekly

Examples:

# Everything from 2018 until today, a week at a time (the safe default)
./scripts/backfill_chunks.sh <id> 2018-01-01

# A fixed range, a week at a time
./scripts/backfill_chunks.sh <id> 2023-06-15 2025-12-31

# Same range a month at a time (to pick the chunk size, also pass workers and page size)
./scripts/backfill_chunks.sh <id> 2023-06-15 2025-12-31 1 500 monthly

# Same range a year at a time
./scripts/backfill_chunks.sh <id> 2023-06-15 2025-12-31 1 500 yearly

# Until today, a month at a time (the - stands for today)
./scripts/backfill_chunks.sh <id> 2020-01-01 - 1 500 monthly

Use weekly for a big station. Monthly and yearly are only for small stations or local testing, because a long date range is slow to read.

What it does: fetches the interactions chunk by chunk and saves the listeners, clears dead profile images, then builds the search index. The database indexes are created for you.

Step 2. Build the topic catalogue

The station needs AI credits loaded for this step. In the dashboard, open the topics window and click Find topics for new campaigns. One click makes up to 10 calls of 40 campaigns each (most used first), so click again until it says there is nothing new to classify. Through the API it is POST /api/v1/topics/<id>/refresh, repeated while remaining is above 0.

This is what gives most listeners their interests and product affinities. A listener's free interests come from what their campaigns are about, and the catalogue is where that comes from. Without it, only the few listeners who were AI-enriched have any. Neither the backfill nor the nightly recalculation builds the catalogue: they only read it. The first audience a station creates sets up the 40 most used campaigns, which is not enough for a station with many campaigns.

It costs credits once per campaign (campaign titles only are sent to the AI), so check the estimate for large stations first.

Do it before step 3, because the recalculation is what turns the catalogue into the listeners' interests. If you refresh topics later, or the station edits a topic, the nightly run picks the change up by itself; run step 3 by hand to see it sooner.

Step 3. Run the recalculation

python jobs/nightly_recalculation.py <id>

The backfill saves the listeners. The recalculation is what makes them show up properly on the dashboard. It also runs by itself every night at 02:00 (South African time) for every station, so you only run it by hand after a backfill, to avoid waiting for the night.

For each listener it works out how recently and how often they were active, their age group, their segment (and notes a change of segment, which feeds the green and red arrows), their tags, and their free interests and product affinities from what they did and wrote. Then, for the station, it:

Step 4. Switch the plugin on

In live-core, turn on the segmentation plugin (route app.profiles.segmentation) for the station. From then on every new interaction reaches this service, and the station can open the dashboard.

Interactions that arrive between the backfill finishing and the plugin being switched on are not sent, so close the gap straight after:

Step 5. Check it

If you need to start over

python scripts/db/drop_company_data.py <id>

This deletes everything stored for the station: its listeners, history, topics, audiences, retarget bucket, saved recommendations, cached answers, backfill checkpoints, bulk jobs, consent audit trail, return-outlook runs and the search index. It asks you to type the station ID first (--yes skips the question). It also removes its AI credits, usage log and plan, and the shared place-name lookups (so the next backfill looks places up again, one a second); --keep-credits and --keep-locations leave those. It also deletes AI enrichment and anything the station corrected by hand, so never run it on a station that is already in use without a backup. Then repeat from step 1.


Endpoints

Base URL: https://segmentation.live.colonyhq.com


Health

GET /health — Public

{
  "status": "ok",
  "mongodb": "ok",
  "qdrant": "ok",
  "openai": "ok — model: gpt-4o-mini"
}

Segments

GET /api/v1/segments/{company_id}/summary

{
  "company_id": <company_id>,
  "total_listeners": 136348,
  "high_engagement_count": 513,
  "segment_counts": {
    "new_listener": 11135,
    "super_fan": 38,
    "dormant": 120529
  }
}
Status Scenario
200 Success. A station with no listener data yet gets zeros or empty lists, not a 404

GET /api/v1/segments/{company_id}

Full segment breakdown with average stats per segment.

{
  "company_id": <company_id>,
  "total_listeners": 107286,
  "segments": [
    {
      "segment": "dormant",
      "listener_count": 107279,
      "avg_recency_days": 94.2,
      "avg_interactions_30d": 0.0,
      "avg_distinct_channels": 1.1
    }
  ]
}
Status Scenario
200 Success. A station with no listener data yet gets zeros or empty lists, not a 404

GET /api/v1/segments/{company_id}/insights

Segment distribution with percentages and plain English explanations.

Status Scenario
200 Success. A station with no listener data yet gets zeros or empty lists, not a 404

GET /api/v1/segments/{company_id}/freshness

When the data was last updated, per-segment change times, and how listeners moved between segments. Powers the dashboard's "Last updated" line and the movement charts.

Parameter Description
days Window for per-segment moved_in / moved_out (default 7, max 90)
movement_days Window for the movement block (default 7, max 30)
{
  "company_id": <company_id>,
  "data_updated_at": "2026-10-11T00:14:03Z",
  "last_interaction_at": "2026-10-11T08:41:10Z",
  "listeners": 107286,
  "window_days": 7,
  "segments": {
    "at_risk": { "updated_at": "2026-10-11T00:14:03Z", "moved_in": 12, "moved_out": 4 }
  },
  "movement": {
    "window_days": 7,
    "since": "2026-10-05",
    "moved_up": 8,
    "moved_down": 2,
    "total": 10,
    "per_day": [{ "date": "2026-10-05", "up": 3, "down": 0 }],
    "segments": {
      "at_risk": {
        "came_up": 0,
        "came_down": 2,
        "left_up": 5,
        "left_down": 0,
        "per_day": [{ "date": "2026-10-05", "in": 1, "out": 2 }],
        "from": [{ "segment": "super_fan", "category": "High Engagement", "count": 2, "direction": "down" }],
        "to": [{ "segment": "occasional_engager", "category": "Active", "count": 5, "direction": "up" }],
        "from_categories": [{ "category": "High Engagement", "count": 2 }],
        "to_categories": [{ "category": "Active", "count": 5 }]
      }
    }
  }
}

movement is built from the segment history. A listener's first segment assignment is not a move. A move is up when the new segment ranks higher in this order: super_fan > show_loyalist > competition_chaser > occasional_engager > new_listener > at_risk > dormant. from_categories / to_categories sum the moves by segment category (New, High Engagement, Active, Re-engagement), which is what the dashboard shows. For a segment, came_up/came_down count listeners that joined from a weaker/stronger segment and left_up/left_down those that left to a stronger/weaker one.

Status Scenario
200 Success. A station with no listener data yet gets zeros or empty lists, not a 404

POST /api/v1/segments/{company_id}/refresh

Drops the station's saved dashboard results so the next requests are computed from live data. Saved AI segment insights are kept (they cost credits and have their own clear endpoint).

{ "company_id": <company_id>, "cleared": 6 }

GET /api/v1/segments/{company_id}/tags

Tag distribution per segment with counts, percentages and descriptions.

Status Scenario
200 Success. A station with no listener data yet gets zeros or empty lists, not a 404

GET /api/v1/segments/{company_id}/filter

Retargeting filter. Gender matching is case-insensitive (male/Male/female/Female).

Fields marked multi accept repeated parameters (segment=dormant&segment=at_risk) and match any of the values.

Parameter Description
segment multi Filter by segment key
tags Comma-separated — must have ALL
gender multi Declared gender — case-insensitive
age_group multi Declared age group
ethnicity multi Declared ethnicity
location multi Partial match, case-insensitive
language multi Declared language
email Partial match, case-insensitive
name Partial match, case-insensitive
originator Partial match on the originator
income_bracket, education, employment_status Declared values
inferred_gender AI-inferred gender — case-insensitive
inferred_age_group AI-inferred age group
inferred_location, inferred_language AI-inferred values
inferred_lsm multi AI-inferred LSM tier
inferred_interests Comma-separated — must have ALL
interests_any Comma-separated — must have ANY
intent_category multi Ready to hear from advertisers in ANY of these categories
intent_tier low, medium or high: at least this tier
channel_type multi Primary channel ID only
has_channel Channel ID used at any point (not just primary)
campaign_type multi Primary campaign type
timeslot_id multi Filter by show/timeslot
peak_time_of_day, primary_day_of_week, peak_month, peak_hour, public_holiday, weekday_pattern When they engage
last_interaction_after ISO datetime — engaged after this date
last_interaction_before ISO datetime — engaged before this date
opt_in, permission Marketing consent
profile_complete Only listeners whose declared profile is complete / incomplete
missing_fields multi Only listeners missing these declared fields
audience_id Only members of that saved audience (404 if it does not exist)
page Page number (default: 1)
page_size Results per page (default: 100, max: 1000)
/filter?segment=dormant&inferred_gender=male&inferred_interests=automotive
/filter?gender=female&language=English&opt_in=true
Status Scenario
200 Success — returns empty list if no matches

GET /api/v1/segments/{company_id}/intent

How many listeners are ready to hear from an advertiser, by tier and by category. Accepts the same filters as /filter.

{
  "total": 1200,
  "tiers": { "low": 300, "medium": 120, "high": 40, "none": 740 },
  "categories": {
    "insurance": { "low": 80, "medium": 30, "high": 12, "total": 122 }
  }
}

GET /api/v1/segments/{company_id}/impact

Did listeners become more active during a campaign? Compares the days listeners were active before, during and after a date range, per segment. Accepts the same filters as /filter.

Parameter Description
start, end The campaign period, as dates (2026-08-01). Up to 366 days.
campaign_id Optional: only listeners who took part in this campaign.

Before and after are as long as the campaign. Each segment gives active_listeners and active_days for the three periods, the change against before as during_lift and after_lift (percent, null when before had none), and directional: true under 30 listeners.


GET /api/v1/segments/{company_id}/campaign-summary

A summary of one campaign for its advertiser. campaign_id is required; other filters narrow the listeners.

Returns who took part (segments, genders, age_groups, locations, languages), how many show medium or high buying intent (buying_intent), how many can be contacted (contactable), and highlights: a few plain sentences to paste into an email. Gender, age, place and language shares are of the listeners where the value is known (known, coverage), not of everyone.


GET /api/v1/segments/{company_id}/send-times

When the filtered listeners are most active, so an advertiser knows when to send. Accepts the same filters as /filter.

Returns the share of activity per weekday (days) and per hour in SAST (hours), the named parts of the day (bands), the best two-hour window and two busiest days (best), and highlights. Days and hours are separate, so there is no "Friday at 8". enough_data is false under 30 listeners with timing.


GET, PUT, DELETE /api/v1/segments/{company_id}/intent/categories

The categories the buying-intent tiers use for this station. GET returns the station's own (custom: true) or the defaults, plus the defaults for reference. PUT replaces them with {"categories": {"name": ["topic", ...]}} (422 with a reason if they are not usable). DELETE goes back to the defaults. A change reaches the stored tiers at the next nightly recalculation.


GET /api/v1/agent/{company_id}/recommendations

The station's recent campaign recommendations: shown, used (the audience was exported from the recommender) and, 14 days after use, the change in the audience's active listeners against the 14 days before. POST /agent/{company_id}/recommendations/{id}/used with {"action": "export_audience" | "export_by_channel"} records the use. DELETE /agent/{company_id}/recommendations/{id} removes one from the history, with its result; it cannot be undone, 404s if it is not there and 409s while it is still being measured.


GET /api/v1/segments/{company_id}/aggregate

Aggregated breakdown counts for the full filtered dataset — not just a page. Accepts the same filters as /filter. Use this to power dashboard charts so totals reflect the true audience size regardless of pagination.

Parameter Description
(all /filter params supported) segment, gender, age_group, location, language, email, name, has_channel, timeslot_id, audience_id, last_interaction_after/before, etc.
/aggregate
/aggregate?segment=dormant
/aggregate?segment=super_fan&gender=Female
{
  "company_id": <company_id>,
  "total": 107286,
  "channel_counts": { "12": 33010, "9": 13664, "0": 14212 },
  "gender_counts": { "other": 107280, "male": 5, "female": 1 },
  "age_group_counts": { "Other": 107281, "35-49": 2 },
  "language_counts": { "other": 107278, "english": 8 },
  "location_counts": { "Other": 106621, "Johannesburg": 5 },
  "segment_counts": { "dormant": 107279, "new_listener": 6 },
  "momentum_counts": { "0": 107279, "1": 7 },
  "campaign_type_counts": { "message_board": 95945, "competition": 11193 }
}
Status Scenario
200 Success — returns empty list if no matches

GET /api/v1/segments/{company_id}/completeness

Returns declared-profile completeness statistics scoped to the active filter set. Completeness uses declared profile fields only and never falls back to inferred values. A profile is considered complete when all 9 declared fields are populated: mobile number, gender, age group, location, language, ethnicity, name, email and ID number.

Note: The endpoint supports the same filter parameters as /filter.

{
  "company_id": <company_id>,
  "total": 107286,
  "complete_count": 42150,
  "incomplete_count": 65136,
  "missing_field_counts": {
    "Mobile number": 120,
    "Gender": 24000,
    "Age group": 18000,
    "Location": 9500,
    "Language": 7000,
    "Ethnicity": 30000,
    "Name": 4000,
    "Email": 50000,
    "ID number": 62000
  }
}
Status Scenario
200 Success — returns completeness statistics for the filtered dataset
400 Invalid filter parameters

Gender and language keys are normalised to lowercase (Male/male merge into male). Location is capped at the top 20 by count.

Status Scenario
200 Success — counts are 0 if no matches

GET /api/v1/segments/{company_id}/export

Returns all matching listener records for a filter set — no pagination. Intended for bulk CSV export and campaign targeting.

Parameter Description
(all /filter params supported) segment, gender, location, opt_in, etc.
channel_pair Comma-separated pair of channel_type ints — e.g. 9,0 — returns only listeners active on both channels
include_unconsented true also returns listeners who have not opted in (default false; recorded when used)
/export?segment=dormant
/export?segment=super_fan&opt_in=true
/export?channel_pair=9,0

Listeners who have not opted in (opt_in not true) are left out unless include_unconsented=true.

{
  "company_id": <company_id>,
  "total": 1,
  "listeners": [
    {
      "originator": "27832005511",
      "originator_type": "mobile_number",
      "current_segment": "super_fan",
      "gender": "Male",
      "age_group": "18-24",
      "location": "Johannesburg",
      "language": "English",
      "primary_channel_type": 9,
      "opt_in": true,
      "permission": true,
      "tags": ["drive_time_listener", "campaign_loyal"],
      "recency_days": 0,
      "interactions_total": 5492,
      "inferred_lsm": null
    }
  ]
}
Status Scenario
200 Success — returns empty list if no matches
400 channel_pair malformed — must be two comma-separated integers

POST /api/v1/export/{company_id}

Listeners as rows of the columns the station picked. Powers the dashboard export dialog. Unknown field keys are ignored, so a request can never pull a column that is not offered. originator is always first.

{
  "fields": [
    "originator",
    "name",
    "mobile",
    "segment",
    "channel",
    "gender",
    "interests"
  ],
  "non_null": true,
  "filters": { "segment": ["dormant"], "opt_in": true },
  "audience_id": null,
  "group_keys": null,
  "channel_type": 9,
  "channel_pair": null,
  "include_unconsented": false,
  "requested_by": "Thandi M"
}
Field Description
fields Column keys, in the order wanted (see the catalogue below)
non_null true drops listeners that are missing any chosen column
filters A filter set using the same names as /filter
audience_id Narrows the export to one saved audience
group_keys Export these retarget bucket groups instead (an empty list means every group)
channel_type Keep listeners active on this channel
channel_pair "9,0" — keep listeners active on both channels
include_unconsented true also exports listeners who have not opted in. Default false; the override is recorded
requested_by Who asked, for the override record (optional)

Column catalogue

Group Keys
Identity originator, name, mobile, email, originator_type
Engagement segment, channel, channels, recency_days, last_interaction, first_interaction, interactions_total, interactions_30d, tags
Demographics gender, age_group, location, language, ethnicity, lsm
AI interests, return_likelihood
Consent opt_in, permission
Extra export_date (the day of export), group (labels of the retarget groups the listener is in; empty unless exporting groups)
{
  "company_id": <company_id>,
  "total": 1840,
  "returned": 1522,
  "truncated": false,
  "excluded": 318,
  "fields": [
    { "key": "originator", "label": "Originator" },
    { "key": "name", "label": "Name" },
    { "key": "segment", "label": "Segment" }
  ],
  "rows": [["27832005511", "Thandi", "dormant"]]
}

Each row is a list of strings in the same order as fields; missing values are empty strings. total is how many listeners matched; returned how many rows survived non_null; excluded how many were left out for not having opted in (0 with include_unconsented). The export is capped at 500,000 rows and truncated is true when it was cut.

Status Scenario
200 Success
400 Invalid filters or malformed channel_pair
404 Audience not found

POST /api/v1/export/{company_id}/check

Takes the same body as the export and returns how many listeners it would cover and how many of them have not opted in, without building anything.

{ "total": 107500, "without_opt_in": 107497 }

GET /api/v1/segments/{company_id}/cross-channel

Cross-channel co-engagement matrix. For every pair of channels, returns how many listeners are active on both, plus per-channel unique totals and percentages. Powers the Cross Platform Engagement grid.

Parameter Description
(all /filter params supported) segment, gender, location, opt_in, etc.
/cross-channel
/cross-channel?segment=super_fan
{
  "company_id": <company_id>,
  "total": 107286,
  "channels": [0, 9, 12],
  "uniques": { "9": 13664, "0": 14212, "12": 33010 },
  "matrix": { "9": { "0": 1200, "12": 800 }, "0": { "9": 1200 } },
  "percentages": { "9": { "0": 1.1, "12": 0.7 }, "0": { "9": 1.1 } }
}

Read matrix["9"]["0"] = 1200 as: 1,200 listeners are active on both WhatsApp (9) and SMS (0). percentages["9"]["0"] is that count as a percentage of the total filtered audience — use it for tooltips like "1.1% of your audience engaged on both WhatsApp and SMS."

Status Scenario
200 Success — empty matrix if no matches

GET /api/v1/segments/{company_id}/search

Semantic search. Qdrant finds by meaning — MongoDB narrows by demographics.

Parameter Description
q Natural language query (required)
min_score Minimum similarity score 0.0–1.0 (default: 0.45)
limit Max results (default: 100, max: 1000)
segment Filter by segment — applied in Qdrant
gender Filter by declared gender — applied in MongoDB
age_group Filter by declared age group — applied in MongoDB
location Filter by declared location — applied in MongoDB
language Filter by declared language — applied in MongoDB
/search?q=music lovers
/search?q=car enthusiasts&segment=dormant&min_score=0.65
Status Scenario
200 Success — returns empty list if no matches
400 Query parameter q is missing
503 Qdrant unavailable

Listeners

GET /api/v1/listeners/{company_id}/{originator}

Full behavioural profile including ORE-enriched demographics, the listener's interactions, linked_identifiers / linked_from (suggested identity links) and ai_conflicts (declared values the AI disagrees with at ≥ 0.70 confidence).

{
  "demographics": {
    "name": "Ozias Munyamela",
    "display_name": "Ozias Munyamela",
    "gender": "male",
    "age_group": "35-49",
    "location": "Johannesburg",
    "language": "English",
    "profile_image": "https://..."
  }
}
Status Scenario
200 Success
404 Listener not found

PATCH /api/v1/listeners/{company_id}/{originator}/linked-identifiers

A station's decision on a suggested identity link (for example a phone number or email a listener mentioned on another channel). Profiles are never merged — this only records the decision.

{ "type": "mobile_number", "value": "27832005511", "action": "confirm" }

type is one of the identifier types the listener carries under linked_identifiers (for example mobile_number, email, facebook_handle, instagram_handle, twitter_handle).

action Meaning
confirm These are the same person (the matched profile is stored with it)
dismiss They are not; the suggestion is hidden and not added again
reset Back to an unreviewed suggestion
{
  "originator": "27832005511",
  "type": "mobile_number",
  "value": "27832005511",
  "confirmed": true,
  "dismissed": false
}
Status Scenario
200 Decision recorded
404 Listener or linked identifier not found

DELETE /api/v1/listeners/{company_id}/{originator}

POPIA erasure. Clears all PII, keeps anonymised behavioural data. Cannot be undone.

The number, email, ID number and linked identifiers become one-way hashes everywhere the listener is named: the profile (including messages, USSD and survey answers and AI reasoning), the segment history, other profiles that link to them, saved audiences, retarget bucket groups and the consent override record. The search vector is deleted, and the station's cached results are dropped so none keep their name or number. Counts and segments stay right, because the hash stands in for the number.

{
  "erased": true,
  "originator_hash": "sha256:a3f9c2d1...",
  "erased_at": "2026-08-22T10:00:00Z"
}
Status Scenario
200 Successfully erased
400 Profile already erased
404 Listener not found

Artificial Intelligence (AI)

GET /api/v1/ai/segments/{company_id}/{segment_key}/insight

AI-written insight for one segment, on demand. Cached for 24 hours per segment — repeat calls are free and return "cached": true.

{
  "company_id": <company_id>,
  "segment_key": "at_risk",
  "listener_count": 5120,
  "avg_recency_days": 41.3,
  "avg_interactions_30d": 0.6,
  "top_tags": ["whatsapp_preferred"],
  "top_campaign_types": ["competition"],
  "top_channels": ["WhatsApp", "SMS"],
  "recency_buckets": [{ "label": "Last 7 days", "count": 120, "pct": 2 }],
  "momentum": { "growing": 310, "steady": 2100, "declining": 2710 },
  "opt_in_percent": 64,
  "insight": {
    "summary": "…",
    "what_it_means": "…",
    "return_outlook": {
      "headline": "Most of this group is unlikely to return without a nudge",
      "risk_level": "high",
      "confidence": "medium",
      "expected_return_percent": { "d30": 12, "d60": 19, "d90": 24 },
      "drivers": [{ "label": "Declining activity", "impact": "negative", "strength": 4 }],
      "best_action": "Send a WhatsApp reminder about the next competition"
    },
    "action_steps": ["…"],
    "industry_fit": ["Retail"],
    "industry_fit_reasoning": "…"
  },
  "cached": false
}

recency_buckets, momentum and opt_in_percent are real counts from the data. return_outlook is the AI's estimate: percentages are clamped to 0–100 and never decrease from 30 to 90 days, risk_level and confidence are low / medium / high, and at most four drivers are returned.

Status Scenario
200 Success
402 AI credits exhausted / paused
404 No listeners in the segment

DELETE /api/v1/ai/segments/{company_id}/{segment_key}/insight/cache

Forgets the saved insight for one segment. The next request asks the AI again and uses credits.

{ "cleared": true, "segment_key": "at_risk" }

GET /api/v1/ai/listeners/{company_id}/{originator}

AI Enrichment for one listener: demographic inference, interest tagging and a plain-words return outlook. Cached 30 days — no charge on repeat calls. Response includes "cached": true/false, consent_required and profiles_enriched_at.

A listener who has not given permission is not enriched: nothing runs and nothing is charged, and the reply has "consent_required": true. Send include_unconsented=true (and optionally requested_by) to enrich them anyway; that is recorded. Listeners already enriched are served from the cache either way.

Parameter Description
include_unconsented true enriches a listener without permission (default false)
requested_by Who asked, for the override record (optional)
Status Scenario
200 Success
402 AI credits exhausted / paused
404 Listener not found

PUT /api/v1/ai/listeners/{company_id}/{originator}/promote-demographics

Promotes AI-inferred to declared. Only where declared is null and confidence ≥ 0.70.

{
  "promoted": { "gender": "female", "age_group": "25-34" },
  "skipped": { "income_bracket": "confidence too low (0.60)" },
  "message": "2 field(s) promoted to declared demographics"
}
Status Scenario
200 Success — promoted may be empty if nothing eligible
404 Listener not found

PUT /api/v1/ai/listeners/{company_id}/{originator}/replace-demographic

Replaces a declared value with the AI's inference. Always an explicit station action, and only when the two disagree with confidence ≥ 0.70. A value stated by an ID number is never replaced. The previous value is kept under station_overrides and reprocessing history will not put it back.

Parameter Description
field Optional. One field to replace. Leave out to replace every field in conflict.
{
  "company_id": <company_id>,
  "originator": "27832005511",
  "field": "gender",
  "value": "female",
  "previous": "male",
  "replaced": [{ "field": "gender", "value": "female", "previous": "male" }]
}
Status Scenario
200 Success
400 field is not a replaceable field
404 Listener not found
409 Nothing is in conflict with a confident inference

POST /api/v1/ai/segments/{company_id}/search-filters

Turns a plain-English request into the dashboard's filter fields. Nothing is applied — the response is a filter set (and how many listeners match it) for the dashboard to show and let the station edit.

{ "prompt": "male listeners from Durban interested in dogs or pets" }
{
  "company_id": <company_id>,
  "prompt": "male listeners from Durban interested in dogs or pets",
  "filters": { "gender": ["male"], "location": ["Durban"], "interests_any": "dogs,pets" },
  "unsupported": [],
  "matched": 412
}

unsupported lists anything in the request that cannot be expressed as a filter.

Status Scenario
200 Success
400 Missing or too-long prompt
402 AI credits exhausted / paused
422 Could not turn that into filters

GET /api/v1/ai/enrich/{company_id}/preview

Before a bulk AI Enrichment: how many listeners in the chosen segments would be enriched and roughly what it costs. Listeners enriched in the last 30 days are skipped.

Parameter Description
segments Comma-separated segment keys. Optional when a filter is given
(all /filter params supported) Narrow the count to listeners who match, the same way they narrow a run
include_unconsented true counts listeners without permission too (default false)
{
  "segments": [
    {
      "segment": "at_risk",
      "listeners": 5120,
      "to_enrich": 4980,
      "without_permission": 112
    }
  ],
  "to_enrich": 4980,
  "without_permission": 112,
  "include_unconsented": false,
  "will_run": 1000,
  "max_per_job": 1000,
  "credits_each": 3.2,
  "credits_estimate": 3200.0,
  "credits_remaining": 8000.0,
  "paused": false,
  "job": null
}

without_permission is how many of the listeners who need enriching have not given permission. They are left out of to_enrich and will_run unless include_unconsented is true. credits_each is what recent enrichments cost this station (null until there is history). job is the station's latest bulk job, if any.


POST /api/v1/ai/enrich/{company_id}/bulk

Starts enriching the chosen segments in the background. Uses AI credits, so it only runs when the station explicitly confirms. One job per station at a time; at most 1,000 listeners per job, most recently active first. The job stops by itself if credits run out.

{
  "segments": ["at_risk", "dormant"],
  "limit": 500,
  "filters": { "gender": ["male"] },
  "include_unconsented": false,
  "requested_by": "Thandi M"
}

segments may be empty when filters is given (everyone who matches, in any segment); with both, listeners must be in the segments and match the filters. Listeners without permission are left out unless include_unconsented is true, which is recorded with how many were in the run.

{
  "job_id": "6710…",
  "status": "running",
  "segments": ["at_risk", "dormant"],
  "total": 500,
  "done": 0,
  "failed": 0,
  "credits_used": 0.0,
  "started_at": "2026-10-11T09:00:00Z",
  "finished_at": null
}
Status Scenario
200 Job started
402 AI credits exhausted / paused
404 Everyone in these segments is already enriched, or everyone left has not given permission
409 An enrichment is already running
422 No segment or filter chosen

GET /api/v1/ai/enrich/{company_id}/bulk/status

Progress of the station's latest bulk enrichment — same shape as above under job, or { "job": null } when there is none. status is running, done, stopped_credits, stopped_limit (this month's limit for bulk enrichment was reached), failed or interrupted (the worker died before finishing).


POST /api/v1/ai/segments/{company_id}/custom-segment

Find listeners using plain English. Stateless — use Audiences for persistence.

{
  "theme": "pet lovers",
  "description": "listeners who own dogs or cats",
  "limit": 200
}

Optional min_score (0.0–1.0, default 0.45) sets how closely a listener must match. The default keeps about 9 in 10 genuine matches on real station data; lower it for more listeners with looser matches.

Status Scenario
200 Success — returns empty list if no matches
402 AI credits exhausted / paused
404 No profiles found for company

Intelligence

GET /api/v1/intelligence/listeners/{company_id}/{originator}/churn-risk

{
  "company_id": <company_id>,
  "originator": "27832005511",
  "current_segment": "at_risk",
  "churn_risk": "high",
  "churn_risk_score": 75,
  "churn_signals": [
    "Engagement momentum is declining",
    "Last engaged 45 days ago"
  ],
  "explanation": {
    "status": "at_risk",
    "headline": "Likely to go quiet soon",
    "reasons": ["Last engaged 45 days ago", "Engagement trend is declining"],
    "evidence": {
      "last_seen_days": 45,
      "interactions_30d": 1,
      "interactions_prev_30d": 6,
      "interactions_90d": 14,
      "trend": "down",
      "interactions_total": 52
    },
    "pattern": { "channel": "WhatsApp", "time_of_day": "Evening", "days": "weekdays" },
    "responds_to": ["Competition", "Drive Time Giveaway"],
    "reachable": { "opt_in": true, "permission": true, "can_contact": true },
    "segment_change": { "from": "occasional_engager", "to": "at_risk", "at": "2026-10-08T00:14:03+00:00" },
    "context": ["Was active — 14 interactions in the last 90 days"],
    "suggested_action": "Re-engage on WhatsApp in the evening with a competition."
  },
  "prediction": {
    "likelihood": "low",
    "probability": 0.18,
    "basis": "…",
    "scored_at": "2026-10-11T00:30:00Z",
    "horizon_days": 90,
    "model": { "auc": 0.81, "recency_auc": 0.74, "base_rate": 0.22, "as_of": "2026-10-11", "horizon_days": 90 },
    "confidence": { "level": "high", "reason": "Based on this listener's own history, and the model has ranked returning listeners well on this station." }
  }
}

Risk levels: low (0–29) / medium (30–59) / high (60–100).

explanation is plain-words reasoning built from the listener's own data (no AI call, no credits). status is active, cooling, at_risk, inactive or unknown (too new to tell); suggested_action is null for active or unknown listeners. prediction is the nightly return-likelihood model: the chance the listener is active again within horizon_days, learned from this station's own history. It is a guide for planning, not a promise, and is null for listeners the model has not scored. confidence.level (low / medium / high) says how far to trust it: low for a listener with a single active day or a model that is barely better than guessing, high for a listener with their own history and a model with AUC ≥ 0.80.

Status Scenario
200 Success
404 Listener not found

GET /api/v1/intelligence/listeners/{company_id}/{originator}/similar

Behaviourally similar listeners via Qdrant cosine similarity.

/similar?limit=20&min_score=0.75&exclude_segment=dormant
Status Scenario
200 Success — returns empty list if no similar listeners
404 Listener not found

GET /api/v1/intelligence/forecast/{company_id}

Station-level expectation for the next period from the latest nightly run: how many listeners are expected to be active, by segment and likelihood band, and how well the model did on its last completed check.

{
  "company_id": <company_id>,
  "as_of": "2026-10-11",
  "horizon_days": 90,
  "forecast": {
    "listeners_scored": 52000,
    "expected_active": 18400.0,
    "bands": { "likely": 9100, "possible": 14000, "unlikely": 28900 },
    "by_segment": {
      "at_risk": { "listeners": 5120, "expected_active": 900.0, "likely": 100, "possible": 700, "unlikely": 4320 }
    }
  },
  "model": { "auc": 0.81, "recency_auc": 0.74, "base_rate": 0.22, "as_of": "2026-10-11", "horizon_days": 90 },
  "checked": { "as_of": "2026-07-13", "predicted_active": 17900, "realised_active": 18350, "realised_auc": 0.8 }
}
Status Scenario
200 Success
404 No forecast yet for company

GET /api/v1/intelligence/segments/{company_id}/{segment_key}/profile

Composite demographic and behavioural profile for a segment. Every listener in the segment is read, so the percentages describe the whole segment. Pass limit only to profile a sample.

Parameter Description
limit Optional. Profile only the first N listeners.
{
  "segment": "dormant",
  "total_in_segment": 120529,
  "profiled_from": 120529,
  "total_profiles": 120529,
  "demographics": {
    "gender": [{ "value": "male", "count": 41000, "pct": 34.0 }],
    "age_group": [{ "value": "25-34", "count": 22000, "pct": 18.3 }],
    "top_locations": [{ "value": "Johannesburg", "count": 5000 }]
  },
  "channels": {
    "primary": "USSD",
    "distribution": [{ "value": "USSD", "count": 60000, "pct": 49.8 }]
  },
  "interests": { "top_interests": [{ "value": "music", "count": 900 }] },
  "top_campaigns": [{ "title": "Parmalat", "total_interactions": 336 }]
}

The result is saved for 15 minutes (the dashboard's Refresh clears it), so reopening a segment is instant. Percentages are shares of the whole segment, so listeners with no known value for a field are simply not counted in that field's chart.

Status Scenario
200 Success
404 No listeners in segment

Agent

POST /api/v1/agent/{company_id}/recommend

AI campaign recommendation from an advertiser brief. Results cached 24 hours — same brief returns cached result instantly. Response includes "cached": true/false.

{
  "brief": "Caltex fuel advertiser targeting male drivers aged 25-49 in Gauteng",
  "sample_size": 500
}
Status Scenario
200 Success
404 No profiles found for company

POST /api/v1/agent/{company_id}/parse-brief

Parses an advertiser brief into structured targeting criteria.

{ "brief": "FMCG brand targeting female listeners aged 25-34 in Gauteng" }
Status Scenario
200 Success
422 Brief too vague to parse

Audiences

An audience is a saved search: a theme in plain English (for example "pet lovers"), optionally limited to one segment, that finds the listeners who match. The search is stored with the audience, so it can be re-run for free.

New listeners only join an audience when its search is run again. That happens when a station clicks Refresh, and also automatically every night for every active audience (free — no AI call, and the end date is not moved). When a station creates or refreshes an audience, doubtful matches are read by the AI once and the answer is kept, so the nightly refresh only reuses those answers.

Audience status

status is derived from the dates:

Status Meaning
scheduled starts_at is in the future
active Started, and expires_at has not passed
no_expiry Started and never_expires is true
expired expires_at has passed (not refreshed automatically)

POST /api/v1/audiences/{company_id}

Creates a named persistent custom audience. Uses AI credits (the AI turns the theme into a search strategy once).

{
  "name": "Colony Campaigns Pet Lovers",
  "theme": "pet lovers",
  "description": "listeners who own dogs or cats",
  "segment": null,
  "limit": 500,
  "min_score": 0.45,
  "expiry_days": 30,
  "starts_at": null,
  "expires_at": null,
  "never_expires": false,
  "auto_refresh": true
}
Field Description
name, theme Required
segment Optional. Only look inside this segment. Leave empty to search every segment.
limit Most listeners to keep (default 500)
min_score How closely a listener must match the description, 0.2–0.95 (default 0.45). Lower finds more listeners with looser matches; higher finds fewer, closer ones.
starts_at When it becomes active (default: now)
expires_at When it ends (default: expiry_days after the start)
never_expires Keep until deleted. Overrides expires_at.
auto_refresh Re-run the search every night (default true). Free.
target, target_unit Optional goal: a number of listeners (count, default) or a percent of this audience's own limit. With no target the audience is counted against its limit. Reads back target_count, target_reached and max_reached (the audience keeps filling after the target, up to limit). On edit, target: 0 clears it.

How members are found. In this order:

  1. AI interests. Listeners whose enriched interests match the theme (for example "dog ownership" for "dogs"). Already judged by the AI.
  2. Surveys and bot conversations that belong to a campaign about the topic (see Topics below), or whose own answers use the audience's words.
  3. The message search. Meaning-matching of what listeners wrote, against min_score.
  4. Campaigns about the topic, only when repeated (two different campaigns on it, or one entered three or more times).

Entering a campaign once is not enough on its own, because people enter competitions for the prize.

Only listeners with direct evidence. Send require_mention: true (create, or edit later) to keep only listeners with direct evidence: a matching AI interest, or their own survey answer, bot conversation or message about it. Campaigns are supporting evidence only and never qualify on their own. Default false. Turning it on or off rebuilds the members for free.

Words are matched using keywords from the AI strategy (the main word, synonyms, brands and local-language equivalents); audiences made before that fall back to the words of the theme. Matching tolerates normal endings ("dog" finds "dogs", "doggie") and typos in words of five letters or more ("huskey"), but not unrelated longer words ("pet" does not find "Petzer", "cat" does not find "category").

Why a listener is in an audience. GET /audiences/{company_id}/{audience_id} adds match_reason to every member, and GET /segments/{company_id}/filter?audience_id=… adds the same to each listener:

{
  "kind": "interest | survey | bot | message | campaign | similar",
  "mentioned": true,
  "text": "Survey about insurance",
  "sources": [
    {
      "source": "survey",
      "label": "Survey about insurance",
      "topic": "insurance",
      "title": "Insurance Survey",
      "whens": ["2024-03-01T08:12:00+00:00"]
    },
    {
      "source": "campaign",
      "label": "Interacted with a campaign about King Price",
      "topic": "insurance",
      "brand": "King Price",
      "title": "King Price Competition",
      "count": 4,
      "whens": []
    }
  ]
}

GET /audiences/{company_id}/{audience_id}/why returns the split without the member list:

{
  "audience_id": "3f1c…",
  "require_mention": false,
  "total": 184,
  "interest": 12,
  "survey": 20,
  "bot": 31,
  "message": 96,
  "campaign": 9,
  "similar": 16,
  "examples": [
    "Message mentioning dogs",
    "Bot conversation about pets",
    "AI interest: pets"
  ],
  "keywords": ["dog", "puppy"]
}

Topics

A station's campaign titles are classified once by the AI into short topics (and a brand, if one is named), then reused by audiences, enrichment and the listener view. It costs credits once per campaign, not per listener. Only campaign titles are sent to the AI, never what listeners said or answered.

Surveys and bot conversations are not classified separately: question text changes with every survey or bot, so each one takes the topic of the campaign it belongs to (every stored survey and bot conversation carries its campaign title). Show titles are not classified either; they are mostly presenter names.

Endpoint What it does
GET /api/v1/topics/{company_id}?status=&q=&topic=&limit= The catalogue of campaigns, most used first. status is with (has a topic), none (no topic), edited (set by the station) or ai; q searches the title and brand; topic keeps campaigns with that topic. The response also has counts (all, with, none, edited) and topic_counts for the whole catalogue.
POST /api/v1/topics/{company_id}/refresh Classifies campaigns not seen before (up to 40 per call, most used first). Uses credits. Call again while remaining is above 0.
PUT /api/v1/topics/{company_id}/rename Renames a topic on every campaign that has it, or removes it from all of them: {"topic": "running", "to": "run", "by": "Jane Smith"}. Leave to empty to remove. Changed campaigns become the station's own, so a later AI run does not put the topic back on them. Free.
PUT /api/v1/topics/{company_id}/bulk The same topics and/or brand for several campaigns at once (up to 500): {"keys": ["campaign:1", "campaign:2"], "topics": ["insurance"], "brand": "King Price", "by": "Jane Smith"}. Send only what should change: topics (an empty list clears them), brand (an empty string clears it), or both. Free.
PUT /api/v1/topics/{company_id}?key=campaign:… The station's own topics for one campaign: {"topics": ["insurance"], "brand": "King Price", "by": "Jane Smith"}. by is kept as edited_by so the list can show who set it. Free. Never overwritten by the AI.
{
  "audience_id": "3f1c…",
  "company_id": <company_id>,
  "name": "Colony Campaigns Pet Lovers",
  "theme": "pet lovers",
  "segment": null,
  "limit": 500,
  "member_count": 412,
  "members": ["27832005511"],
  "starts_at": "2026-10-11T09:00:00Z",
  "expires_at": "2026-11-10T09:00:00Z",
  "never_expires": false,
  "auto_refresh": true,
  "status": "active",
  "created_at": "2026-10-11T09:00:00Z",
  "refreshed_at": "2026-10-11T09:00:00Z"
}
Status Scenario
200 Success
402 AI credits exhausted / paused

PUT /api/v1/audiences/{company_id}/{audience_id}

Edits an audience. Only the fields sent are changed.

Change What happens Credits
name, description, dates, auto_refresh Saved Free
segment (use null for all segments) or limit The stored search is re-run and the members rebuilt Free
theme The AI writes a new search, then members are rebuilt Uses credits
never_expires: true End date cleared Free
never_expires: false on a no-expiry audience End date set 30 days after the start Free
{ "name": "Pet lovers — Gauteng", "segment": "dormant" }

Returns the audience (without members) plus rebuilt (members were re-run) and credits_used (a new theme asked the AI).

Status Scenario
200 Success
402 New theme but no credits
404 Audience not found
422 Empty name

GET /api/v1/audiences/{company_id}

Lists all custom audiences — member lists excluded for performance. Each audience carries status, member_count, dates and segment.

Status Scenario
200 Success — returns empty list if none

GET /api/v1/audiences/{company_id}/{audience_id}

Returns audience with full member list enriched with profile data. To page through the members as listeners, use GET /api/v1/segments/{company_id}/filter?audience_id={audience_id}.

Status Scenario
200 Success
404 Audience not found

PUT /api/v1/audiences/{company_id}/{audience_id}/refresh

Re-runs the stored search and updates members with the latest data. The AI also reads the text of doubtful matches (broad words found together, a clear word in a long message, or a match by meaning alone) and leaves out those that do not belong; each text is read once and the answer is kept, so a refresh uses only a little credit, and none when nothing is new. If credits run out nobody is dropped. The end date is never moved: refreshing finds new listeners, and an audience ends on the date the station set. An ended audience is not refreshed (HTTP 409); edit its end date to run it again.

{
  "audience_id": "3f1c…",
  "member_count": 431,
  "members": ["…"],
  "message": "Audience refreshed — 431 members found"
}
Status Scenario
200 Success
404 Audience not found

DELETE /api/v1/audiences/{company_id}/{audience_id}

Deletes a custom audience. Cannot be undone.

Status Scenario
200 Successfully deleted
404 Audience not found

Retarget Bucket

The bucket is where a station sets listeners aside to retarget — from a saved audience, a segment, a filtered list, a single listener, or a custom group. Listeners are kept in groups named after where they came from, and a group is stable per key: adding to the same key again only adds listeners that are not there yet, so the same listener is never counted twice in a group.

A listener can be in several groups; total counts them once. Use POST /api/v1/export/{company_id} with group_keys to export the bucket by channel.

POST /api/v1/retarget/{company_id}/add

Adds listeners to a group (created on first use). Give one of originators, audience_id or filters.

{
  "group": {
    "key": "audience:3f1c",
    "label": "Pet lovers",
    "kind": "audience"
  },
  "audience_id": "3f1c…"
}
Field Description
group.key Stable id for the source — re-using it adds to the same group
group.label Name shown to the station
group.kind audience, segment, filters, listener or custom
originators A list of listeners (for example one listener, or a selection)
audience_id Every member of a saved audience
filters A filter set (same names as /filter) — every matching listener
include_unconsented true also adds listeners who have not opted in (default false; recorded when used)
requested_by Who asked, for the override record (optional)
{
  "added": 120,
  "already_present": 12,
  "excluded": 7,
  "truncated": false,
  "group": {
    "group_key": "audience:3f1c",
    "label": "Pet lovers",
    "kind": "audience",
    "count": 431,
    "added": 120
  }
}

A group holds at most 500,000 listeners; truncated is true when the list was cut. already_present is how many of the listeners were already in the group. excluded is how many were left out for not having opted in.

Status Scenario
200 Success
400 Invalid filters
404 Audience not found, no listeners to add, or none of them have opted in
422 None of originators, audience_id, filters

POST /api/v1/retarget/{company_id}/check

Takes the same body as /add and returns how many listeners an add would cover and how many of them have not opted in, without adding anything.

{ "total": 431, "without_opt_in": 12 }

GET /api/v1/retarget/{company_id}

The groups in the bucket with their sizes and a per-channel breakdown.

{
  "total": 1840,
  "groups": [
    {
      "group_key": "audience:3f1c",
      "label": "Pet lovers",
      "kind": "audience",
      "count": 431,
      "full": true,
      "channels": { "9": 300, "0": 210 },
      "updated_at": "2026-10-11T09:00:00Z"
    }
  ]
}

full is true when the group was filled from a whole list (audience or filter set) rather than single listeners. channels counts listeners active on each channel (a listener can appear under several).


DELETE /api/v1/retarget/{company_id}/groups/{group_key}

Removes one group from the bucket.

Status Scenario
200 Removed
404 Group not found

DELETE /api/v1/retarget/{company_id}

Empties the bucket. Returns { "removed": <groups removed> }.


AI Credit Management

AI usage is managed per company. Colony admin users can load credits, monitor balances and usage, and pause or resume AI usage.

Credit Rate

Credits are charged from the actual tokens used by each AI call:

credits = (input tokens + output tokens) / 500
1 credit = R0.10

So the cost of one call depends on how much the AI had to read and write. Typical operations:

Operation (endpoint in the usage log) What it does
infer-demographics, infer-interests AI Enrichment of one listener (both are charged)
bulk-infer-demographics, bulk-infer-interests Bulk enrichment, once per listener (both are charged)
classify-topics Sorting campaigns into topics (first audience, or topics refresh)
segment-insight A segment insight and its Return Outlook
create-audience Turning an audience theme into a search
custom-segment Finding listeners from plain English
search-filters Turning a request into dashboard filters
recommend, parse-brief Campaign recommendation / brief parsing

Free (no AI call, no credits): the nightly audience refresh (it only reuses earlier checks), editing an audience without changing its theme, the return-likelihood model, churn explanations, exports, the retarget bucket, and everything that only reads data.

When credits are exhausted, AI usage is automatically paused and AI calls return 402. AI usage can also be manually paused or resumed.

POST /api/v1/agent/{company_id}/credits/load

Loads AI credits for a company. Admin-only endpoint.

{
  "credits": 1000,
  "note": "Monthly AI credit allocation",
  "loaded_by": "Colony Admin"
}
Field Type Required Description
credits number Yes Number of credits to load
note string No Optional note for the credit load
loaded_by string No Who loaded the credits, kept with the load for the record
{
  "company_id": <company_id>,
  "credits_loaded": 1000,
  "credits_remaining": 1000,
  "message": "1000 credits loaded successfully."
}
Status Scenario
200 Credits loaded successfully
400 Invalid credit amount
401 Missing or invalid authentication

GET /api/v1/agent/{company_id}/credits

Returns the current AI credit balance and pause status for a company.

{
  "company_id": <company_id>,
  "credits_loaded": 1000,
  "credits_used": 125,
  "credits_remaining": 875,
  "paused": false,
  "pause_reason": null,
  "last_updated": "2026-08-22T10:00:00Z",
  "status": { "key": "active", "label": "Active", "reason": "AI is available." }
}

status.key is the same as in the summary below (active, low, paused, exhausted or not_activated), so a client can warn before credits run out. The dashboard shows a banner for low, exhausted and paused.

Status Scenario
200 Success

GET /api/v1/agent/{company_id}/credits/usage

Returns AI credit usage history for a company.

Query Parameters

Parameter Description
from_date Optional ISO date for the start of the usage period
to_date Optional ISO date for the end of the usage period
limit Number of usage records to return (default: 100, max: 1000)
/credits/usage
/credits/usage?from_date=2026-08-01&to_date=2026-08-31
{
  "company_id": <company_id>,
  "total_calls": 25,
  "total_credits": 75.0,
  "total_cost_zar": 0.31,
  "logs": [
    {
      "company_id": <company_id>,
      "endpoint": "recommend",
      "model": "gpt-4o-mini",
      "input_tokens": 1800,
      "output_tokens": 700,
      "total_tokens": 2500,
      "credits_charged": 5.0,
      "cost_zar": 0.0097,
      "cached": false,
      "timestamp": "2026-08-22T10:00:00Z"
    }
  ]
}
Status Scenario
200 Success
400 Invalid date parameters

GET /api/v1/agent/{company_id}/credits/summary

Everything the dashboard's AI usage panel shows: balance and status, when AI was switched on, each credit load, what each part of the product has used (with its share and a rough number of uses left) and daily usage.

Parameter Description
days Days in the daily chart (default 30, max 90)
{
  "company_id": <company_id>,
  "balance": {
    "loaded": 3000.0,
    "used": 2250.0,
    "remaining": 750.0,
    "used_percent": 75.0,
    "remaining_percent": 25.0,
    "last_load": 1000,
    "last_loaded_at": "2026-09-20T08:00:00Z",
    "last_loaded_by": "Thandi Mokoena",
    "activated_by": "Sipho Khumalo",
    "load_count": 3
  },
  "status": { "key": "active", "label": "Active", "reason": "AI is available." },
  "activated_at": "2026-09-01T08:00:00Z",
  "last_updated": "2026-10-11T09:12:00Z",
  "loads": [{ "load_id": "a1b2c3d4e5f6", "credits": 500, "note": "Top-up", "loaded_by": "Thandi Mokoena", "loaded_at": "2026-09-20T08:00:00Z" }],
  "adjustments": [
    { "type": "removed_load", "at": "2026-10-02T09:00:00Z", "by": "Sipho Khumalo", "reason": "Loaded to the wrong station", "credits": 1000, "loaded_at": "2026-10-01T08:00:00Z" }
  ],
  "components": [
    {
      "key": "enrichment",
      "label": "AI Enrichment",
      "description": "Reading a listener or a whole segment with AI",
      "credits": 150.0,
      "percent": 60.0,
      "uses": 20,
      "average_credits": 7.5,
      "uses_left": 100,
      "last_used_at": "2026-10-11T08:40:00Z",
      "monthly_cap": 500,
      "used_this_month": 120.5,
      "cap_reached": false
    }
  ],
  "window_days": 30,
  "daily": [{ "date": "2026-10-11", "credits": 12.5 }],
  "cost_zar": 25.0
}

status.key is active, low (under 20% left or under 10 credits), paused (checked first, with the pause reason), exhausted or not_activated (nothing was ever loaded and AI is not paused). loads never includes removed loads. adjustments (removed loads and resets, newest first, with who and why) is for Colony staff: live-core-ex drops it for stations. components lists every part that can use AI, in this order: AI Enrichment, Segment insights, Audiences, Find listeners, Campaign recommender. A part not used yet has credits: 0. monthly_cap is the limit Colony set for the part (null for none), used_this_month what it has used since the 1st, and cap_reached whether that has hit the limit. uses_left is an estimate (credits remaining divided by what that part has cost per use so far) and is null until the part has been used. percent is the part's share of everything spent, all time. There is one balance per station: every load adds to it. balance.loaded is the running total of all loads, used is what has been taken from it, remaining is what is left, and the percentages and status (low included) are measured against that total. Each load is still listed, newest first, under loads.


POST /api/v1/agent/{company_id}/credits/loads/{load_id}/remove

Removes one credit load (a top-up made in error, say). Colony staff only — the dashboard enforces this and stations never see it. The load's credits are taken off the loaded total and the balance, and the balance never goes below zero. The load stays on record, marked removed with who removed it and why.

{ "reason": "Loaded to the wrong station", "by": "Thandi Mokoena" }

load_id is the load_id of an entry in loads from /credits/summary.

Status Scenario
200 { "removed": true, "credits": 1000.0 }
400 reason is empty
404 Load not found or already removed

POST /api/v1/agent/{company_id}/credits/reset

Sets the station's credits back to zero: loaded total, used, balance and load history. Colony staff only. The usage log and the figures that were there are kept on record (with who reset it and why); the station sees a clean start and usage is counted again from the reset.

{ "reason": "Test data cleared before go-live", "by": "Thandi Mokoena" }
Status Scenario
200 { "reset": true }
400 reason is empty

GET /api/v1/agent/{company_id}/credits/statement

A simple usage summary for one month: credits used per feature and their value at the credit rate, what was loaded that month, and the balance now. It is a summary, not a formal invoice (no VAT or tax details).

Parameter Description
month Required. The month as YYYY-MM
{
  "company_id": <company_id>,
  "month": "2026-10",
  "from": "2026-10-01",
  "to": "2026-10-31",
  "generated_at": "2026-10-12T09:00:00Z",
  "credit_rate_zar": 0.1,
  "credits_used": 250.0,
  "value_zar": 25.0,
  "components": [
    { "key": "enrichment", "label": "AI Enrichment", "credits": 150.0, "uses": 20, "percent": 60.0, "value_zar": 15.0 }
  ],
  "credits_loaded": 1000.0,
  "loads": [{ "credits": 1000, "note": "Top-up", "loaded_at": "2026-10-01T08:00:00Z" }],
  "balance_now": 750.0,
  "daily": [{ "date": "2026-10-01", "credits": 12.5 }]
}
Status Scenario
200 Success
400 month is not YYYY-MM

PATCH /api/v1/agent/{company_id}/credits/pause

Pauses or resumes AI usage for a company. Admin-only endpoint. When paused, AI calls are rejected and no credits are consumed.

{
  "paused": true,
  "reason": "AI budget temporarily paused"
}

To resume AI usage:

{
  "paused": false,
  "reason": null
}
Field Type Required Description
paused boolean Yes Whether AI usage should be paused
reason string No Reason for pausing or resuming
{
  "company_id": <company_id>,
  "paused": true,
  "message": "AI usage paused for company <company_id>."
}
Status Scenario
200 Pause state updated successfully
401 Missing or invalid authentication

PUT /api/v1/agent/{company_id}/credits/caps

Sets or removes the monthly limit for parts of the product. Admin-only endpoint (Colony staff). Once a part has used its limit for the calendar month, AI calls for that part return 429 until the 1st; everything else keeps working. The limit counts credits actually charged this month (and since a reset, if later).

{
  "caps": { "bulk_enrichment": 500, "topics": null, "find_listeners": 0 },
  "by": "Thandi M"
}
Field Type Required Description
caps object Yes Part key (a components[].key from the summary) to a number of credits. 0 switches the part off, null removes its limit. Parts not named are unchanged
by string No Who set them, for the record
{ "company_id": <company_id>, "caps": { "bulk_enrichment": 500, "find_listeners": 0 } }
Status Scenario
200 Limits updated
422 Unknown part, or a negative limit

The part keys are enrichment, bulk_enrichment, segment_insight, audiences, topics, find_listeners and campaigns.


AI Credit Consumption

AI credits are consumed only when an AI call is actually made. Cached responses (a segment insight saved within 24 hours, a listener enriched within 30 days) consume nothing. If the company has no credits or AI usage is paused, the AI operation is rejected with 402.

Endpoint Operation
GET /api/v1/ai/listeners/{company_id}/{originator} infer-demographics + infer-interests
POST /api/v1/ai/enrich/{company_id}/bulk bulk-infer-demographics + bulk-infer-interests, once per listener (stops when credits run out)
POST /api/v1/topics/{company_id}/refresh classify-topics
GET /api/v1/ai/segments/{company_id}/{segment_key}/insight segment-insight
DELETE …/{segment_key}/insight/cache none — but the next insight call is charged
POST /api/v1/ai/segments/{company_id}/custom-segment custom-segment
POST /api/v1/ai/segments/{company_id}/search-filters search-filters
POST /api/v1/audiences/{company_id} create-audience
PUT /api/v1/audiences/{company_id}/{audience_id} (new theme) create-audience
POST /api/v1/agent/{company_id}/recommend recommend
POST /api/v1/agent/{company_id}/parse-brief parse-brief

Channel Type Reference

channel_type Channel
0, 11, 15, 16, 17, 18 SMS
1 Email
2 Twitter
3 Facebook
8 USSD
9 WhatsApp
10 Instagram
12 Telegram
19 Survey
20 Data import
22 TikTok

Phased Roadmap

Phase 1 — Behaviour-led segmentation     ✓ Complete
Phase 2 — Semantic search                ✓ Complete
Phase 3 — AI inference layer             ✓ Complete
Phase 4 — Predictive intelligence        ✓ Complete
Phase 5 — AI agent layer                 ✓ Complete
Phase 6 — Full-dataset aggregation       ✓ Complete
Phase 7 — Retargeting workflow           ✓ Complete
          (audiences, retarget bucket, column-picked exports,
           bulk AI Enrichment, segment movement)