diff --git a/CHANGELOG.md b/CHANGELOG.md index e6427d98..f256f9bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,18 @@ For auto-generated release notes, see [GitHub Releases](https://github.com/DataV ### Added +- **Population packs and `althing.population`.** A population pack is a + persona pack whose personas carry structured attributes (`country`). + The bundled `global-respondents` pack has one minimal respondent persona + per country (107 countries). `allocate_population` splits a sample budget + across population members, weighting repeated members, deterministically + per seed; `filter_personas` narrows a pack by attribute. + `althing panel run --population "country=France,Japan"` filters a panel. + `country`, `gender`, and `region` persona attributes are now stated in + the persona system prompt (no bundled pack set them before, so existing + prompts are unchanged). Used by SynthBench's `--persona-pack` option for + GlobalOpinionQA. + - **Subscription CLI providers: `claude-code:` and `codex:`.** Completions can now run through a locally installed, signed-in Claude Code (`claude -p`) or Codex (`codex exec`) CLI, drawing on the user's diff --git a/README.md b/README.md index be2b216a..b73f7b3e 100644 --- a/README.md +++ b/README.md @@ -783,7 +783,7 @@ searching for one: become resolvable by name like a builtin. See [docs/registry.md](docs/registry.md) for URI forms, verification, offline cache, and the submission flow. -### Builtin persona packs (14, 232 personas total) +### Builtin persona packs (15, 339 personas total) | Pack | Personas | |------|----------| @@ -793,6 +793,7 @@ searching for one: | `enterprise-ai-buyers` | 18 | | `enterprise-buyer` | 15 | | `general-consumer` | 15 | +| `global-respondents` | 107 (population pack, one per country) | | `healthcare-patient` | 15 | | `job-seekers` | 15 | | `market-research-critics` | 16 | @@ -807,6 +808,29 @@ user-saved packs. Picking the right pack for your task? See [docs/task-recommendations.md](docs/task-recommendations.md) for the task → pack → model-config matrix with copy/paste commands. +### Population packs + +A population pack is a persona pack whose personas carry structured +attributes such as `country`. `global-respondents` has one minimal +respondent persona per country (107 countries, plain names) and no other +demographics. + +Narrow a panel to part of the population: + +```bash +althing panel run --personas global-respondents --population "country=France,Japan" --instrument survey.yaml +``` + +Benchmarks use `althing.population.allocate_population` to split a sample +budget across a list of population members. Each member gets an equal +share and a member listed twice gets twice the share, so the pooled +answers match a ground truth that averages over those groups. SynthBench's +`--persona-pack global-respondents` uses this for GlobalOpinionQA, where +each question's target is the average over the countries that answered it. + +`country`, `gender`, and `region` attributes are stated in the persona's +system prompt. + ### Builtin instrument packs (8, all v3 branching) `churn-diagnosis`, `feature-prioritization`, `general-survey`, diff --git a/docs/agent-quickstart.md b/docs/agent-quickstart.md index 1e7a73b6..fa748ba5 100644 --- a/docs/agent-quickstart.md +++ b/docs/agent-quickstart.md @@ -132,7 +132,7 @@ them with `--personas-merge` (duplicate names are de-duped, later file wins, and a warning names every drop): ```bash -althing pack list # 14 bundled packs, with counts +althing pack list # 15 bundled packs, with counts althing pack export product-research -o pr.yaml # 20 personas althing pack export broad-professionals -o bp.yaml # 20 personas diff --git a/docs/registry.md b/docs/registry.md index 737836e2..69ba7255 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -7,9 +7,10 @@ to find one: - **Builtin packs** ship inside the `althing` wheel. They are resolvable by name the moment `pip install althing` finishes — no `pack import`, no - network, no registry lookup. The SDK currently bundles **14 persona packs** - (232 personas total: `ai-eval-buyers`, `broad-professionals`, `developer`, + network, no registry lookup. The SDK currently bundles **15 persona packs** + (339 personas total: `ai-eval-buyers`, `broad-professionals`, `developer`, `enterprise-ai-buyers`, `enterprise-buyer`, `general-consumer`, + `global-respondents`, `healthcare-patient`, `job-seekers`, `market-research-critics`, `product-research`, `recruiters-talent`, `skeptical-executives`, `startup-founder`, `students`) and **8 v3 branching diff --git a/server.json b/server.json index 6d841eb4..2c33b9f5 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.DataViking-Tech/althing", "title": "Althing", "description": "Run synthetic focus groups using AI personas. 12 MCP tools for single prompts, full panel runs, and v3 branching (adaptive) instruments across any LLM provider (Claude, OpenAI, Gemini, xAI).", - "version": "1.7.0", + "version": "1.8.0", "repository": { "url": "https://github.com/DataViking-Tech/Althing", "source": "github" @@ -14,7 +14,7 @@ "registryType": "pypi", "registryBaseUrl": "https://pypi.org", "identifier": "althing", - "version": "1.7.0", + "version": "1.8.0", "runtimeHint": "uvx", "runtimeArguments": [ { diff --git a/site/.well-known/mcp/server-card.json b/site/.well-known/mcp/server-card.json index bd6abc0d..ba3b1390 100644 --- a/site/.well-known/mcp/server-card.json +++ b/site/.well-known/mcp/server-card.json @@ -3,7 +3,7 @@ "name": "io.github.DataViking-Tech/althing", "title": "Althing", "description": "Run synthetic focus groups using AI personas. 12 MCP tools for single prompts, full panel runs, and v3 branching (adaptive) instruments across any LLM provider (Claude, OpenAI, Gemini, xAI).", - "version": "1.7.0", + "version": "1.8.0", "websiteUrl": "https://althing.dev", "repository": { "url": "https://github.com/DataViking-Tech/Althing", @@ -11,7 +11,7 @@ }, "serverInfo": { "name": "althing", - "version": "1.7.0" + "version": "1.8.0" }, "capabilities": { "tools": { "listChanged": false }, @@ -23,7 +23,7 @@ "registryType": "pypi", "registryBaseUrl": "https://pypi.org", "identifier": "althing", - "version": "1.7.0", + "version": "1.8.0", "runtimeHint": "uvx", "runtimeArguments": [ { "type": "named", "name": "--from", "value": "althing[mcp]" } diff --git a/site/index.html b/site/index.html index 37d4c5d3..7ab6c5ed 100644 --- a/site/index.html +++ b/site/index.html @@ -45,7 +45,7 @@ "applicationCategory": "DeveloperApplication", "applicationSubCategory": "Research Tool", "operatingSystem": "Cross-platform", - "softwareVersion": "1.7.0", + "softwareVersion": "1.8.0", "dateModified": "", "license": "https://opensource.org/licenses/MIT", "codeRepository": "https://github.com/DataViking-Tech/Althing", @@ -122,7 +122,7 @@ class="mb-4 inline-flex items-center gap-2 rounded-full border border-emerald-400/30 bg-emerald-400/5 px-3 py-1 text-xs font-medium text-emerald-300" > - v1.7.0 — public beta + v1.8.0 — public beta

class="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-800 py-6 text-xs text-slate-400" > - © 2026 DataViking · MIT-licensed · v1.7.0 · + © 2026 DataViking · MIT-licensed · v1.8.0 · int: ] personas = merged + # --population narrows the panel to personas matching attribute values + # (population packs such as global-respondents; see althing.population). + population_spec = getattr(args, "population", None) + if population_spec: + from althing.population import PopulationError, filter_personas, parse_population + + try: + personas = filter_personas(personas, parse_population(population_spec)) + except PopulationError as exc: + print(f"Error: --population: {exc}", file=sys.stderr) + return 1 + # synthbench#261 / sy-2ag: when --model was NOT given and the # auto-resolved default is a known-slow router (openrouter/auto), a # ≥10-persona panel can hang for many minutes. Swap the default for a diff --git a/src/althing/cli/parser.py b/src/althing/cli/parser.py index 232c7bd6..005dbb7f 100644 --- a/src/althing/cli/parser.py +++ b/src/althing/cli/parser.py @@ -146,6 +146,16 @@ def build_parser() -> argparse.ArgumentParser: "case the original personas path is recovered from the checkpoint." ), ) + panel_run_parser.add_argument( + "--population", + default=None, + metavar="KEY=VALUES", + help=( + "Keep only personas whose attributes match, e.g. " + "'country=France,Japan' or 'country=Brazil;gender=female'. " + "Use with a population pack such as global-respondents." + ), + ) panel_run_parser.add_argument( "--personas-merge", dest="personas_merge", diff --git a/src/althing/packs/global-respondents.yaml b/src/althing/packs/global-respondents.yaml new file mode 100644 index 00000000..421c8657 --- /dev/null +++ b/src/althing/packs/global-respondents.yaml @@ -0,0 +1,333 @@ +name: Global Survey Respondents +version: "1" +description: > + Population pack: one minimal survey-respondent persona per country, + keyed by the `country` attribute. Built for population conditioning + (althing.population): a caller passes the countries a question was asked + in and samples are split across the matching personas. Covers every + country in GlobalOpinionQA (Pew Global Attitudes and World Values + Survey), using plain country names. Personas carry no other + demographics, so a run measures country conditioning alone. + +personas: + - name: "Respondent from Albania" + country: "Albania" + background: "Lives in Albania" + - name: "Respondent from Andorra" + country: "Andorra" + background: "Lives in Andorra" + - name: "Respondent from Angola" + country: "Angola" + background: "Lives in Angola" + - name: "Respondent from Argentina" + country: "Argentina" + background: "Lives in Argentina" + - name: "Respondent from Armenia" + country: "Armenia" + background: "Lives in Armenia" + - name: "Respondent from Australia" + country: "Australia" + background: "Lives in Australia" + - name: "Respondent from Austria" + country: "Austria" + background: "Lives in Austria" + - name: "Respondent from Azerbaijan" + country: "Azerbaijan" + background: "Lives in Azerbaijan" + - name: "Respondent from Bangladesh" + country: "Bangladesh" + background: "Lives in Bangladesh" + - name: "Respondent from Belarus" + country: "Belarus" + background: "Lives in Belarus" + - name: "Respondent from Belgium" + country: "Belgium" + background: "Lives in Belgium" + - name: "Respondent from Bolivia" + country: "Bolivia" + background: "Lives in Bolivia" + - name: "Respondent from Bosnia and Herzegovina" + country: "Bosnia and Herzegovina" + background: "Lives in Bosnia and Herzegovina" + - name: "Respondent from Brazil" + country: "Brazil" + background: "Lives in Brazil" + - name: "Respondent from Bulgaria" + country: "Bulgaria" + background: "Lives in Bulgaria" + - name: "Respondent from Burkina Faso" + country: "Burkina Faso" + background: "Lives in Burkina Faso" + - name: "Respondent from Canada" + country: "Canada" + background: "Lives in Canada" + - name: "Respondent from Chile" + country: "Chile" + background: "Lives in Chile" + - name: "Respondent from China" + country: "China" + background: "Lives in China" + - name: "Respondent from Colombia" + country: "Colombia" + background: "Lives in Colombia" + - name: "Respondent from Croatia" + country: "Croatia" + background: "Lives in Croatia" + - name: "Respondent from Cyprus" + country: "Cyprus" + background: "Lives in Cyprus" + - name: "Respondent from Czechia" + country: "Czechia" + background: "Lives in Czechia" + - name: "Respondent from Denmark" + country: "Denmark" + background: "Lives in Denmark" + - name: "Respondent from Ecuador" + country: "Ecuador" + background: "Lives in Ecuador" + - name: "Respondent from Egypt" + country: "Egypt" + background: "Lives in Egypt" + - name: "Respondent from El Salvador" + country: "El Salvador" + background: "Lives in El Salvador" + - name: "Respondent from Estonia" + country: "Estonia" + background: "Lives in Estonia" + - name: "Respondent from Ethiopia" + country: "Ethiopia" + background: "Lives in Ethiopia" + - name: "Respondent from Finland" + country: "Finland" + background: "Lives in Finland" + - name: "Respondent from France" + country: "France" + background: "Lives in France" + - name: "Respondent from Georgia" + country: "Georgia" + background: "Lives in Georgia" + - name: "Respondent from Germany" + country: "Germany" + background: "Lives in Germany" + - name: "Respondent from Ghana" + country: "Ghana" + background: "Lives in Ghana" + - name: "Respondent from Great Britain" + country: "Great Britain" + background: "Lives in Great Britain" + - name: "Respondent from Greece" + country: "Greece" + background: "Lives in Greece" + - name: "Respondent from Guatemala" + country: "Guatemala" + background: "Lives in Guatemala" + - name: "Respondent from Honduras" + country: "Honduras" + background: "Lives in Honduras" + - name: "Respondent from Hong Kong" + country: "Hong Kong" + background: "Lives in Hong Kong" + - name: "Respondent from Hungary" + country: "Hungary" + background: "Lives in Hungary" + - name: "Respondent from Iceland" + country: "Iceland" + background: "Lives in Iceland" + - name: "Respondent from India" + country: "India" + background: "Lives in India" + - name: "Respondent from Indonesia" + country: "Indonesia" + background: "Lives in Indonesia" + - name: "Respondent from Iran" + country: "Iran" + background: "Lives in Iran" + - name: "Respondent from Iraq" + country: "Iraq" + background: "Lives in Iraq" + - name: "Respondent from Israel" + country: "Israel" + background: "Lives in Israel" + - name: "Respondent from Italy" + country: "Italy" + background: "Lives in Italy" + - name: "Respondent from Ivory Coast" + country: "Ivory Coast" + background: "Lives in Ivory Coast" + - name: "Respondent from Japan" + country: "Japan" + background: "Lives in Japan" + - name: "Respondent from Jordan" + country: "Jordan" + background: "Lives in Jordan" + - name: "Respondent from Kazakhstan" + country: "Kazakhstan" + background: "Lives in Kazakhstan" + - name: "Respondent from Kenya" + country: "Kenya" + background: "Lives in Kenya" + - name: "Respondent from Kuwait" + country: "Kuwait" + background: "Lives in Kuwait" + - name: "Respondent from Kyrgyzstan" + country: "Kyrgyzstan" + background: "Lives in Kyrgyzstan" + - name: "Respondent from Latvia" + country: "Latvia" + background: "Lives in Latvia" + - name: "Respondent from Lebanon" + country: "Lebanon" + background: "Lives in Lebanon" + - name: "Respondent from Libya" + country: "Libya" + background: "Lives in Libya" + - name: "Respondent from Lithuania" + country: "Lithuania" + background: "Lives in Lithuania" + - name: "Respondent from Macau" + country: "Macau" + background: "Lives in Macau" + - name: "Respondent from Malaysia" + country: "Malaysia" + background: "Lives in Malaysia" + - name: "Respondent from Maldives" + country: "Maldives" + background: "Lives in Maldives" + - name: "Respondent from Mali" + country: "Mali" + background: "Lives in Mali" + - name: "Respondent from Mexico" + country: "Mexico" + background: "Lives in Mexico" + - name: "Respondent from Mongolia" + country: "Mongolia" + background: "Lives in Mongolia" + - name: "Respondent from Montenegro" + country: "Montenegro" + background: "Lives in Montenegro" + - name: "Respondent from Morocco" + country: "Morocco" + background: "Lives in Morocco" + - name: "Respondent from Myanmar" + country: "Myanmar" + background: "Lives in Myanmar" + - name: "Respondent from Netherlands" + country: "Netherlands" + background: "Lives in Netherlands" + - name: "Respondent from New Zealand" + country: "New Zealand" + background: "Lives in New Zealand" + - name: "Respondent from Nicaragua" + country: "Nicaragua" + background: "Lives in Nicaragua" + - name: "Respondent from Nigeria" + country: "Nigeria" + background: "Lives in Nigeria" + - name: "Respondent from North Macedonia" + country: "North Macedonia" + background: "Lives in North Macedonia" + - name: "Respondent from Northern Ireland" + country: "Northern Ireland" + background: "Lives in Northern Ireland" + - name: "Respondent from Norway" + country: "Norway" + background: "Lives in Norway" + - name: "Respondent from Pakistan" + country: "Pakistan" + background: "Lives in Pakistan" + - name: "Respondent from Palestinian territories" + country: "Palestinian territories" + background: "Lives in Palestinian territories" + - name: "Respondent from Peru" + country: "Peru" + background: "Lives in Peru" + - name: "Respondent from Philippines" + country: "Philippines" + background: "Lives in Philippines" + - name: "Respondent from Poland" + country: "Poland" + background: "Lives in Poland" + - name: "Respondent from Portugal" + country: "Portugal" + background: "Lives in Portugal" + - name: "Respondent from Puerto Rico" + country: "Puerto Rico" + background: "Lives in Puerto Rico" + - name: "Respondent from Romania" + country: "Romania" + background: "Lives in Romania" + - name: "Respondent from Russia" + country: "Russia" + background: "Lives in Russia" + - name: "Respondent from Senegal" + country: "Senegal" + background: "Lives in Senegal" + - name: "Respondent from Serbia" + country: "Serbia" + background: "Lives in Serbia" + - name: "Respondent from Singapore" + country: "Singapore" + background: "Lives in Singapore" + - name: "Respondent from Slovakia" + country: "Slovakia" + background: "Lives in Slovakia" + - name: "Respondent from Slovenia" + country: "Slovenia" + background: "Lives in Slovenia" + - name: "Respondent from South Africa" + country: "South Africa" + background: "Lives in South Africa" + - name: "Respondent from South Korea" + country: "South Korea" + background: "Lives in South Korea" + - name: "Respondent from Spain" + country: "Spain" + background: "Lives in Spain" + - name: "Respondent from Sweden" + country: "Sweden" + background: "Lives in Sweden" + - name: "Respondent from Switzerland" + country: "Switzerland" + background: "Lives in Switzerland" + - name: "Respondent from Taiwan" + country: "Taiwan" + background: "Lives in Taiwan" + - name: "Respondent from Tajikistan" + country: "Tajikistan" + background: "Lives in Tajikistan" + - name: "Respondent from Tanzania" + country: "Tanzania" + background: "Lives in Tanzania" + - name: "Respondent from Thailand" + country: "Thailand" + background: "Lives in Thailand" + - name: "Respondent from Tunisia" + country: "Tunisia" + background: "Lives in Tunisia" + - name: "Respondent from Turkey" + country: "Turkey" + background: "Lives in Turkey" + - name: "Respondent from Uganda" + country: "Uganda" + background: "Lives in Uganda" + - name: "Respondent from Ukraine" + country: "Ukraine" + background: "Lives in Ukraine" + - name: "Respondent from United States" + country: "United States" + background: "Lives in United States" + - name: "Respondent from Uruguay" + country: "Uruguay" + background: "Lives in Uruguay" + - name: "Respondent from Uzbekistan" + country: "Uzbekistan" + background: "Lives in Uzbekistan" + - name: "Respondent from Venezuela" + country: "Venezuela" + background: "Lives in Venezuela" + - name: "Respondent from Vietnam" + country: "Vietnam" + background: "Lives in Vietnam" + - name: "Respondent from Zimbabwe" + country: "Zimbabwe" + background: "Lives in Zimbabwe" diff --git a/src/althing/population.py b/src/althing/population.py new file mode 100644 index 00000000..28352f3f --- /dev/null +++ b/src/althing/population.py @@ -0,0 +1,120 @@ +"""Population conditioning: pick and weight personas to match a target population. + +A *population pack* is an ordinary persona pack whose personas carry +structured attributes (``country: France``). A *population* is a +specification of who should answer, in one of two shapes: + +* a filter, ``{"country": ["France", "Japan"]}`` — keep the personas whose + attribute is one of the listed values (:func:`filter_personas`); used by + ``althing panel run --population``; +* a member list, ``["Brazil", "Brazil", "Japan"]`` on one attribute — each + entry is one unit of the target population, repeats included, and + :func:`allocate_population` splits a sample budget across them. This is + how a benchmark reproduces a ground truth that averages over groups: + each group gets an equal share of samples, and a group listed twice gets + twice the share. + +Allocation is deterministic for a given seed, so a benchmark question +always conditions on the same personas. +""" + +from __future__ import annotations + +import random +from collections import Counter +from typing import Any + + +class PopulationError(ValueError): + """Raised when a population cannot be matched to a pack's personas.""" + + +def parse_population(spec: str) -> dict[str, list[str]]: + """Parse ``"country=France,Japan;gender=female"`` into a filter dict.""" + population: dict[str, list[str]] = {} + for clause in spec.split(";"): + clause = clause.strip() + if not clause: + continue + key, sep, values = clause.partition("=") + key = key.strip() + vals = [v.strip() for v in values.split(",") if v.strip()] + if not sep or not key or not vals: + raise PopulationError(f"Invalid population clause {clause!r}; expected KEY=VALUE[,VALUE...]") + population.setdefault(key, []).extend(vals) + if not population: + raise PopulationError("Population spec is empty") + return population + + +def _attr(persona: dict[str, Any], key: str) -> str | None: + value = persona.get(key) + return None if value is None else str(value) + + +def filter_personas(personas: list[dict[str, Any]], population: dict[str, list[str]]) -> list[dict[str, Any]]: + """Keep personas whose attributes match every key in *population*. + + Matching is case-insensitive on the attribute value. A persona without + the attribute never matches. Raises :class:`PopulationError` when + nothing matches, naming the values the pack does not cover. + """ + wanted = {k: {v.casefold() for v in vals} for k, vals in population.items()} + kept = [p for p in personas if all((_attr(p, k) or "").casefold() in vals for k, vals in wanted.items())] + if not kept: + missing = { + k: sorted(v for v in vals if all((_attr(p, k) or "").casefold() != v.casefold() for p in personas)) + for k, vals in population.items() + } + raise PopulationError(f"No personas match population {population}; values not in pack: {missing}") + return kept + + +def allocate_population( + personas: list[dict[str, Any]], + *, + key: str, + members: list[str], + n_samples: int, + seed: str | int | None = None, +) -> list[tuple[dict[str, Any], int]]: + """Split *n_samples* across population *members* and resolve them to personas. + + Each member (repeats included) is resolved to the persona whose *key* + attribute equals it (case-insensitive). Members are shuffled with + *seed* and dealt samples round-robin, so every member gets + ``n // m`` or ``n // m + 1`` samples; when there are more members than + samples, the shuffle decides which are drawn. Samples landing on the + same persona are summed. + + Returns ``(persona, n)`` pairs, persona order following first draw. + Raises :class:`PopulationError` if any member has no matching persona. + """ + if not members: + raise PopulationError("Population has no members") + by_value: dict[str, dict[str, Any]] = {} + for p in personas: + value = _attr(p, key) + if value is not None: + by_value.setdefault(value.casefold(), p) + unknown = sorted({m for m in members if m.casefold() not in by_value}) + if unknown: + raise PopulationError(f"No persona with {key} matching: {unknown}") + + order = sorted(members) + random.Random(seed).shuffle(order) + totals: Counter[int] = Counter() + first_seen: list[dict[str, Any]] = [] + for i in range(n_samples): + persona = by_value[order[i % len(order)].casefold()] + if id(persona) not in totals: + first_seen.append(persona) + totals[id(persona)] += 1 + return [(p, totals[id(p)]) for p in first_seen] + + +def load_pack_personas(pack_id: str) -> list[dict[str, Any]]: + """Load and validate the personas of a bundled or installed pack.""" + from althing.mcp.data import get_persona_pack, validate_persona_pack + + return validate_persona_pack(get_persona_pack(pack_id).get("personas", [])) diff --git a/src/althing/prompts.py b/src/althing/prompts.py index ea1d3d86..f76ba39b 100644 --- a/src/althing/prompts.py +++ b/src/althing/prompts.py @@ -66,6 +66,10 @@ def persona_system_prompt(persona: dict[str, Any]) -> str: parts = [f"You are role-playing as {persona.get('name', 'an anonymous person')}."] if persona.get("age"): parts.append(f"Age: {persona['age']}.") + # Demographic attributes used by population packs (althing.population). + for key in ("gender", "country", "region"): + if persona.get(key): + parts.append(f"{key.capitalize()}: {persona[key]}.") if persona.get("occupation"): parts.append(f"Occupation: {persona['occupation']}.") if persona.get("background"): diff --git a/tests/test_mcp_data.py b/tests/test_mcp_data.py index 02197ace..1268ebff 100644 --- a/tests/test_mcp_data.py +++ b/tests/test_mcp_data.py @@ -50,7 +50,8 @@ def test_list_includes_bundled(self): # imposed by the original five packs. sp-b8y47x added students. # sy-a0i / gh-476 added four canonical packs for common agent # research jobs (skeptical-executives, market-research-critics, - # broad-professionals, enterprise-ai-buyers). + # broad-professionals, enterprise-ai-buyers). global-respondents is + # the first population pack (althing.population). assert names == { "developer", "enterprise-buyer", @@ -66,8 +67,9 @@ def test_list_includes_bundled(self): "market-research-critics", "broad-professionals", "enterprise-ai-buyers", + "global-respondents", } - assert len(builtin) == 14 + assert len(builtin) == 15 def test_sp_6wbm_scaleup_packs_load(self): """sp-6wbm: each new scale-up pack loads, has a non-empty diff --git a/tests/test_population.py b/tests/test_population.py new file mode 100644 index 00000000..83a2fead --- /dev/null +++ b/tests/test_population.py @@ -0,0 +1,109 @@ +"""Tests for population conditioning (althing.population) and the global-respondents pack.""" + +from __future__ import annotations + +from collections import Counter + +import pytest + +from althing.population import ( + PopulationError, + allocate_population, + filter_personas, + load_pack_personas, + parse_population, +) +from althing.prompts import persona_system_prompt + +PERSONAS = [ + {"name": "Respondent from Brazil", "country": "Brazil"}, + {"name": "Respondent from France", "country": "France", "gender": "female"}, + {"name": "Respondent from Japan", "country": "Japan"}, + {"name": "No country"}, +] + + +def test_parse_population(): + assert parse_population("country=France, Japan;gender=female") == { + "country": ["France", "Japan"], + "gender": ["female"], + } + + +@pytest.mark.parametrize("spec", ["", "country", "country=", "=France"]) +def test_parse_population_rejects_bad_specs(spec): + with pytest.raises(PopulationError): + parse_population(spec) + + +def test_filter_personas_matches_all_keys_case_insensitively(): + kept = filter_personas(PERSONAS, {"country": ["france", "JAPAN"]}) + assert [p["country"] for p in kept] == ["France", "Japan"] + kept = filter_personas(PERSONAS, {"country": ["France", "Japan"], "gender": ["female"]}) + assert [p["country"] for p in kept] == ["France"] + + +def test_filter_personas_names_missing_values(): + with pytest.raises(PopulationError, match="Atlantis"): + filter_personas(PERSONAS, {"country": ["Atlantis"]}) + + +def test_allocate_population_even_split(): + alloc = allocate_population(PERSONAS, key="country", members=["Brazil", "France", "Japan"], n_samples=30, seed="q1") + assert sum(n for _, n in alloc) == 30 + assert {p["country"]: n for p, n in alloc} == {"Brazil": 10, "France": 10, "Japan": 10} + + +def test_allocate_population_weights_repeated_members(): + alloc = allocate_population( + PERSONAS, key="country", members=["Brazil", "Brazil", "France", "Japan"], n_samples=40, seed="q1" + ) + assert {p["country"]: n for p, n in alloc} == {"Brazil": 20, "France": 10, "Japan": 10} + + +def test_allocate_population_more_members_than_samples(): + personas = [{"name": f"P{i}", "country": f"C{i:02d}"} for i in range(50)] + alloc = allocate_population(personas, key="country", members=[f"C{i:02d}" for i in range(50)], n_samples=30, seed=7) + assert len(alloc) == 30 + assert all(n == 1 for _, n in alloc) + + +def test_allocate_population_is_deterministic_per_seed(): + personas = [{"name": f"P{i}", "country": f"C{i:02d}"} for i in range(50)] + members = [p["country"] for p in personas] + + def draw(seed): + alloc = allocate_population(personas, key="country", members=members, n_samples=10, seed=seed) + return [p["country"] for p, _ in alloc] + + assert draw("a") == draw("a") + assert draw("a") != draw("b") + + +def test_allocate_population_rejects_unknown_members(): + with pytest.raises(PopulationError, match="Atlantis"): + allocate_population(PERSONAS, key="country", members=["Brazil", "Atlantis"], n_samples=4) + + +def test_persona_prompt_states_demographic_attributes(): + prompt = persona_system_prompt({"name": "Respondent from France", "country": "France", "gender": "female"}) + assert "Country: France." in prompt + assert "Gender: female." in prompt + + +def test_persona_prompt_unchanged_without_attributes(): + persona = {"name": "Sarah", "age": 34, "occupation": "PM", "background": "Works at a SaaS company"} + assert persona_system_prompt(persona) == ( + "You are role-playing as Sarah. Age: 34. Occupation: PM. Background: Works at a SaaS company. " + "Answer questions in character. Be authentic to this persona's perspective, experiences, " + "and communication style. Give concise, direct answers." + ) + + +def test_global_respondents_pack(): + personas = load_pack_personas("global-respondents") + countries = [p["country"] for p in personas] + assert len(countries) == len(set(countries)) >= 100 + assert {"United States", "Great Britain", "South Korea", "Brazil", "Japan"} <= set(countries) + assert all(set(p) == {"name", "country", "background"} for p in personas) + assert Counter(p["name"] for p in personas).most_common(1)[0][1] == 1