Metadata-Version: 2.4
Name: personasurvey
Version: 0.2.4
Summary: Reusable async persona survey simulations
License-Expression: MIT
Project-URL: Homepage, https://github.com/Japulgarin/personasurvey
Project-URL: Repository, https://github.com/Japulgarin/personasurvey
Project-URL: Issues, https://github.com/Japulgarin/personasurvey/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas>=2.0
Requires-Dist: httpx>=0.25
Requires-Dist: openai>=1.0
Requires-Dist: tqdm>=4.0
Provides-Extra: gemini
Requires-Dist: google-genai>=1.0; extra == "gemini"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40; extra == "anthropic"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# personasurvey

Run reproducible persona surveys from a Pandas DataFrame. The public workflow is deliberately small:

```python
run_simulation(...)
continue_simulation(...)
```

There is no `await` in notebook or script code. The package manages its asynchronous requests internally.

## Install

Install the published package:

```bash
pip install personasurvey
```

Install test dependencies too:

```bash
pip install "personasurvey[dev]"
```

## Load an example dataset

The repository includes 100 fictional personas with demographic columns and one individual English description per person. Load it directly:

```python
import pandas as pd

DATASET_URL = "https://raw.githubusercontent.com/Japulgarin/personasurvey/main/examples/fictional_personas_100.csv"
df = pd.read_csv(DATASET_URL)

print(df.iloc[0])
```

Example row:

```text
persona_id                                                        P001
name                                                    Avery Morgan
age                                                                 25
region                                                           North
occupation                                                    Teacher
community_priority                                             jobs
persona_description  Avery Morgan is a fictional teacher in Riverton...
```

## Define a prompt and see the exact input

```python
from personasurvey import PersonaPrompt, ResponseSchema

schema = ResponseSchema.probabilities(["Candidate A", "Candidate B"])

prompt = PersonaPrompt(
    demographic_cols=["age", "region", "city", "education", "occupation", "community_priority"],
    persona_detail_cols=["persona_description", "hobby"],
    scenario="""Fictional candidate propositions:
- Candidate A: expand local health clinics and fund apprenticeships.
- Candidate B: lower prescription costs and expand tenant protections.

How would this person divide support between Candidate A and Candidate B?""",
    response_schema=schema,
)

prompt.validate(df)
print(prompt.preview(df.iloc[0]))
```

## Run and inspect input/output

Use a local LM Studio server, RunPod, OpenRouter, OpenAI, Gemini, or Anthropic provider. This example runs a small local LM Studio job:

```python
from personasurvey import OpenAIProvider, run_simulation

provider = OpenAIProvider(
    base_url="http://127.0.0.1:1234/v1",
    model="google/gemma-4-e2b",
    api_key="lm-studio",
    structured_output=True,
)

run = run_simulation(
    df=df,
    prompt=prompt,
    provider=provider,
    id_col="persona_id",
    checkpoint="example_run.jsonl",
    n=10,
    concurrency=1,
    max_tokens=300,
    temperature=0,
)

row = run.results.iloc[0]
print("INPUT SENT TO THE MODEL:\n", row["input"])
print("\nRAW MODEL OUTPUT:\n", row["output"])
print("\nPARSED RESPONSE:")
print(row[["Candidate A", "Candidate B", "reason", "in_tok", "out_tok"]])
```

`run.results` always includes:

- `input`: the complete prompt sent for that row.
- `output`: the raw model response.
- parsed fields such as `Candidate A`, `Candidate B`, and `reason` when a schema is used.
- `in_tok`, `out_tok`, `endpoint`, `provider`, `status`, and `error`.

If a model stops before completing JSON, the row is saved as an error and `error` explains whether it likely reached `max_tokens`. Increase `max_tokens` and use `continue_simulation(...)`; successful rows are not sent again.

## Concurrency

`concurrency` is optional and belongs to `run_simulation` or `continue_simulation`, not to `RunPodProvider`.

```python
# Let the package choose its internal default.
run = run_simulation(...)

# Limit a real test to three simultaneous requests in total.
run = run_simulation(..., concurrency=3)
```

`concurrency` is the total number of requests that the runner may keep in flight. With one endpoint, `concurrency=3` means three requests. With two RunPod endpoints, `concurrency=800` means 400 workers per endpoint (800 total), not 800 per endpoint.

`endpoint_balance="dynamic"` is the default. Both endpoints draw from one shared queue, so the faster pod automatically completes more rows. Use `endpoint_balance="even"` only when an exact 50/50 split is required.

For a large RunPod experiment, begin with `concurrency=100` total, confirm the pods are stable, then increase gradually to `300`, `500`, or `800`. The runner configures each endpoint's HTTP pool to its share. Use a higher total only when the pods sustain it without growing latency, retries, or timeouts.

```python
large_run = continue_simulation(
    df=df, prompt=prompt, provider=runpod, id_col="persona_id",
    checkpoint="country_trial_01.jsonl", n=200_000,
    concurrency=800, endpoint_balance="dynamic", max_tokens=800, temperature=0,
    retries=3, timeout=180, stall_timeout=300,
)
```

## Continue safely

Stop the notebook, change provider settings, or add endpoints. Continue with the same JSONL file and successful IDs will not be sent again:

```python
from personasurvey import continue_simulation

results = continue_simulation(
    df=df,
    prompt=prompt,
    provider=provider,
    id_col="persona_id",
    checkpoint="example_run.jsonl",
)
```

## Providers

The prompt, DataFrame, schema, checkpoint, result columns, and `run_simulation` call stay the same.

```python
from personasurvey import (
    AnthropicProvider, GeminiProvider, OpenAIProvider,
    OpenRouterProvider, RunPodProvider,
)

# LM Studio or any local OpenAI-compatible server.
provider = OpenAIProvider(
    base_url="http://127.0.0.1:1234/v1",
    model="google/gemma-4-e2b",
    api_key="lm-studio",
    structured_output=True,
)

# One or more RunPod/vLLM endpoints. Pending work is split evenly between them.
provider = RunPodProvider(
    urls=["https://your-pod-1.proxy.runpod.net/", "https://your-pod-2.proxy.runpod.net/"],
    model="openai/gpt-oss-20b",
)

# OpenRouter reads OPENROUTER_API_KEY from the environment.
provider = OpenRouterProvider(model="openai/gpt-oss-20b")

# Official OpenAI reads OPENAI_API_KEY from the environment.
provider = OpenAIProvider(model="gpt-4.1-mini")

# Gemini: pip install "personasurvey[gemini]"; reads GEMINI_API_KEY.
provider = GeminiProvider(model="gemini-2.5-flash")

# Anthropic: pip install "personasurvey[anthropic]"; reads ANTHROPIC_API_KEY.
provider = AnthropicProvider(model="claude-sonnet-4-5")
```

## Change provider and continue the same checkpoint

This is the usual recovery or scale-up workflow. Start with a small local run, then change only `provider` and call `continue_simulation` with the identical checkpoint path. Successful IDs are skipped; failures and pending IDs are retried.

## Compare prompt variants for the same personas

When several experiments used the same IDs, compare their completed JSONL files without re-sending any request. Supply the numeric response fields from your own experiment; candidates and countries are never hardcoded.

```python
from personasurvey import compare_checkpoints

comparison = compare_checkpoints(
    {
        "demographic": "usa_demographic.jsonl",
        "cultural": "usa_cultural.jsonl",
        "persona": "usa_persona.jsonl",
    },
    metrics=["Donald Trump", "Kamala Harris"],
    baseline="demographic",
)

comparison.data.head()  # Same successful _id values in every experiment.
comparison.summary()  # Mean, median, standard deviation and range of every change.
comparison.largest_changes("Donald Trump", "persona", n=20)
comparison.winner_flips(["Donald Trump", "Kamala Harris"], "persona")
```

```python
# First: ten local requests.
local = OpenAIProvider(
    base_url="http://127.0.0.1:1234/v1",
    model="google/gemma-4-e2b",
    api_key="lm-studio",
    structured_output=True,
)
first = run_simulation(
    df=df, prompt=prompt, provider=local, id_col="persona_id",
    checkpoint="country_trial_01.jsonl", n=10, concurrency=1,
    max_tokens=600, temperature=0,
)

# Later: continue the same rows with two RunPod workers.
runpod = RunPodProvider(
    urls=["https://your-pod-1.proxy.runpod.net/", "https://your-pod-2.proxy.runpod.net/"],
    model="openai/gpt-oss-20b",
)
final = continue_simulation(
    df=df, prompt=prompt, provider=runpod, id_col="persona_id",
    checkpoint="country_trial_01.jsonl", n=200_000, concurrency=3,
    max_tokens=800, temperature=0, json_mode=True,
)

print(final.results[["_id", "provider", "endpoint", "status", "input", "output"]].head())
```

Credentials are supplied as provider arguments or environment variables. Do not put API keys in notebooks, source files, checkpoints, or GitHub.

## Included examples

- `examples/fictional_personas_100.csv`: loadable fictional input dataset.
- `examples/fictional_results_100.json`: completed example results.
- `examples/walkthrough.ipynb`: a step-by-step notebook.
