> ## Documentation Index
> Fetch the complete documentation index at: https://arizeai-433a7140.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Test Prompts at Scale

> Run a prompt on a labeled dataset, measure its accuracy, and use an LLM evaluator to find the most frequent errors.

In Part 1, you fixed one wrong classification. One trace shows one mistake. A dataset shows the patterns across many mistakes.

In this part, you run the `support-classifier` prompt on a dataset of support queries. At the end, you have a baseline accuracy score and a new instruction that fixes the most frequent type of error.

You do these tasks:

1. Upload a dataset of support queries.
2. Run an experiment with the current prompt.
3. Score each output and generate feedback with evaluators.
4. Analyze the results to find the most frequent error type.

> [!NOTE]
>
> **Follow along with code**: This guide has a companion notebook with runnable code examples. Find it [here](https://github.com/Arize-ai/phoenix/blob/main/tutorials/prompts/phoenix_prompt_tutorial.ipynb), and go to Part 2: Test Prompts at Scale.

**1. Load Dataset of Inputs**

Upload a dataset of support queries. Each row has a query and its correct class.

> [tab] UI
>
> 1. Download `support_queries.csv` [here](https://storage.googleapis.com/arize-phoenix-assets/assets/images/support_queries.csv).
> 2. Go to **Datasets and Experiments**. Click **Create Dataset** and upload the file.
> 3. For **Input keys**, select `query`. This is the input column.
> 4. For **Output keys**, select `ground_truth`. This is the correct output.
> 5. Click **Create Dataset**. Open the new dataset.
>
>    <video src="https://storage.googleapis.com/arize-phoenix-assets/assets/images/upload_dataset.mp4" width="100%" height="100%" controls autoPlay muted loop />
>
>    Upload dataset to Phoenix

> [tab] Python
>
> ```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> import pandas as pd
> from phoenix.client import Client
>
> #load our support query dataset
> support_query_csv_url = "https://storage.googleapis.com/arize-phoenix-assets/assets/images/support_queries.csv"
> support_query_df = pd.read_csv(support_query_csv_url)
>
> #upload dataset to Phoenix
> px_client = Client()
> support_query_dataset = px_client.datasets.create_dataset(
>     dataframe=support_query_df,
>     name="support-query-dataset",
>     input_keys=["query"],
>     output_keys=["ground_truth"],
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> import { createDataset } from "@arizeai/phoenix-client/datasets";
> import { parse } from "csv-parse/sync";
>
> // 1. Fetch CSV from URL
> const csvUrl = "https://storage.googleapis.com/arize-phoenix-assets/assets/images/support_queries.csv";
> const response = await fetch(csvUrl);
> const csvText = await response.text();
>
> // 2. Parse CSV into rows
> const rows = parse(csvText, { 
>   columns: true, 
>   relax_quotes: true,
>   relax_column_count: true,
> }) as Record<string, string>[];
>
> // 3. Convert to Example[] format (input_keys=["query"], output_keys=["ground_truth"])
> const examples = rows.map((row) => ({
>   input: { query: row.query },
>   output: { ground_truth: row.ground_truth },
> }));
>
> // 4. Create dataset
> const { datasetId } = await createDataset({
>   name: "support-query-dataset",
>   description: "Support query dataset",
>   examples,
> });
> ```

**2. Run Experiment with Our Current Prompt**

Run the current prompt on all the examples in the dataset. The result is your baseline accuracy.

### Define Task Function

Define a **task** function. The task generates an output for each input in the dataset. Here, the task asks the LLM to classify a support query.

> [tab] Python
>
> ```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> ## Feel free to use any LLM provider. To run experiments asynchronously, use an async client.
> from openai import AsyncOpenAI
> from phoenix.client import Client
>
> async_openai_client = AsyncOpenAI()
> px_client = Client()
>
> prompt = px_client.prompts.get(prompt_identifier="support-classifier")
> model = prompt._model_name
> messages = prompt._template["messages"]
>
> # let's edit the user prompt to match our dataset input key, "query"
> messages[1]["content"][0]["text"] = "{{query}}"
>
> async def task(input):
>     response = await async_openai_client.chat.completions.create(
>         model=model,
>         messages=messages,
>     )
>     return response.choices[0].message.content
> ```

> [tab] TypeScript
>
> ```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> import OpenAI from "openai";
> import { getPrompt, toSDK } from "@arizeai/phoenix-client/prompts";
>
> const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
>
> // Get prompt from Phoenix
> const prompt = await getPrompt({
>   prompt: { name: "support-classifier" },
> });
>
> // Access model and template
> const model = prompt.model_name;
> const messages = prompt.template.messages;
>
> // Modify template to match dataset input key "query"
> messages[1].content[0].text = "{{query}}";
>
> // Define async task
> const task = async (input: { input: { query: string } }) => {
>   const openAIParams = toSDK({
>     prompt,
>     sdk: "openai",
>     variables: { query: input.input.query },
>   });
>
>   const response = await openai.chat.completions.create({
>     ...openAIParams,
>     model: model || "gpt-4o",
>   });
>
>   return response.choices[0]?.message?.content || "";
> };
> ```

### Define Evaluators

Define **evaluators**. An evaluator scores each output and can explain why the output is correct or incorrect.

Use two evaluators:

* **`ground_truth_evaluator`** – Checks if the predicted class matches the ground truth.
* **`output_evaluator`** – Uses an LLM to analyze each classification. It returns these fields:
  * **`explanation`** – Why the classification is correct or incorrect.
  * **`confusion_reason`** – If incorrect, why the model might have made the wrong choice.
  * **`error_type`** – If incorrect, what kind of error occurred (`broad_vs_specific`, `keyword_bias`, `multi_intent_confusion`, `ambiguous_query`, `off_topic`, `paraphrase_gap`, or `other`).
  * **`evidence_span`** – The exact phrase in the query that supports the correct classification.
  * **`prompt_fix_suggestion`** – An instruction to add to the classifier prompt to prevent this type of error.

The code uses `analysis_evaluator_template`. Copy the full template from the "Define Evaluators" section of the notebook.

> [tab] Python
>
> ```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> def normalize(label):
>     return label.strip().strip('"').strip("'").lower()
>
> async def ground_truth_evaluator(expected, output):
>     return normalize(expected.get("ground_truth")) == normalize(output)
>
> from phoenix.evals import create_evaluator
> from phoenix.evals.llm import LLM
>
> llm = LLM(provider="openai", model="gpt-4.1")
>
> SCHEMA = {
>     "type": "object",
>     "properties": {
>         "correctness": {"type": "string", "enum": ["correct", "incorrect"]},
>         "explanation": {"type": "string"},
>         "confusion_reason": {"type": "string"},
>         "error_type": {"type": "string"},
>         "evidence_span": {"type": "string"},
>         "prompt_fix_suggestion": {"type": "string"},
>     },
>     "required": [
>         "correctness",
>         "explanation",
>         "confusion_reason",
>         "error_type",
>         "evidence_span",
>         "prompt_fix_suggestion",
>     ],
>     "additionalProperties": False,
> }
>
> @create_evaluator(name="output_evaluator", source="llm")
> def output_evaluator(query: str, ground_truth: str, output: str):
>     template = analysis_evaluator_template
>
>     prompt = (
>         template.replace("{query}", query)
>             .replace("{ground_truth}", ground_truth)
>             .replace("{output}", output)
>     )
>     obj = llm.generate_object(prompt=prompt, schema=SCHEMA)
>     correctness = obj["correctness"]
>     score = 1.0 if correctness == "correct" else 0.0
>     explanation = (
>         f'correctness: {correctness}; '
>         f'explanation: {obj.get("explanation","")}; '
>         f'confusion_reason: {obj.get("confusion_reason","")}; '
>         f'error_type: {obj.get("error_type","")}; '
>         f'evidence_span: {obj.get("evidence_span","")}; '
>         f'prompt_fix_suggestion: {obj.get("prompt_fix_suggestion","")};'
>     )
>     return {"score": score, "label": correctness, "explanation": explanation}
>
> ```

> [tab] TypeScript

### Run Experiment

Run the experiment with the task and the two evaluators.

> [tab] Python
>
> ```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> from phoenix.client.experiments import async_run_experiment
>
> experiment = await async_run_experiment(
>     dataset=support_query_dataset,
>     task=task,
>     evaluators=[ground_truth_evaluator, output_evaluator],
> )
> ```
>
> The output is similar to this:
>
> ```
> running tasks |██████████| 154/154 (100.0%) | ⏳ 00:47<00:00 |  3.21it/s
> ✅ Task runs completed.
> 🧠 Evaluation started.
> running experiment evaluations |██████████| 308/308 (100.0%) | ⏳ 03:46<00:00 | 1.36it/s
> Experiment completed: 154 task runs, 2 evaluator runs, 308 evaluations
> ```

> [tab] TypeScript
>
> ```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
> import { runExperiment } from "@arizeai/phoenix-client/experiments";
>
> const experiment = await runExperiment({
>   dataset: { datasetId: dataset.id },
>   task,
>   evaluators: [groundTruthEvaluator, analysisEvaluator],
> });
> ```

**3. Analyze Experiment Results**

Find the most frequent type of error in the results.

Go to **Datasets and Experiments** and open the support query dataset. The experiment shows in the dataset.

The `ground_truth_evaluator` score is 0.53. This means that 53% of the classifications match the ground truth.

The `output_evaluator` also gives feedback in natural language for each output. Use this feedback to find the errors.

To show only the incorrect classifications, use this filter:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
evals["output_evaluator"].score == 0
```

Hover over the `output_evaluator` score to see the feedback. This is one example:

```
input: "downgraded me mid-billing cycle"
ground_truth: Subscription Upgrade/Downgrade
LLM classification: Billing Inquiry

correctness: incorrect
explanation: The predicted classification 'Billing Inquiry' is incorrect because the user's query is specifically about a change in subscription status ('downgraded') rather than a general billing question. The correct classification is 'Subscription Upgrade/Downgrade' as it directly addresses changes in subscription level during a billing cycle.
confusion_reason: The model likely focused on the word 'billing' and interpreted the issue as a general billing question, missing the more specific context of a subscription change. This is a classic case of confusing a broad category (Billing Inquiry) with a more specific one (Subscription Upgrade/Downgrade).
error_type: broad_vs_specific → The model picked a broader category instead of the more specific correct one.
evidence_span: downgraded me mid-billing cycle
prompt_fix_suggestion: Instruct the classifier to prefer more specific classes (like 'Subscription Upgrade/Downgrade') over broader categories (like 'Billing Inquiry') when a query mentions subscription changes.
```

This is the same broad-versus-specific error that you fixed in Part 1. To show all rows with the `broad_vs_specific` error type, use this filter:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
'broad_vs_specific' in evals["output_evaluator"].explanation
```

The filter shows 30 rows. `broad_vs_specific` is the most frequent error type.

Write down this instruction to fix `broad_vs_specific` errors. You add it to the prompt in Part 3.

```
When classifying user queries, always prefer the most specific applicable category over a broader one. If a query mentions a clear, concrete action or object (e.g., subscription downgrade, invoice, profile name), classify it under that specific intent rather than a general one (e.g., Billing Inquiry, General Feedback).
```

## Summary

**You tested your prompt on a full dataset.**\
You have a baseline accuracy of 53%. An LLM evaluator explained each failure, so you did not read every input and output pair. You found the most frequent error type and wrote an instruction to fix it.

## Next Steps

In [Compare Prompt Versions](https://arizeai-433a7140.mintlify.site/docs/phoenix/prompt-engineering/tutorial/compare-prompt-versions.md), you add the new instruction to the prompt and change the model parameters. Then you run experiments with the new versions and compare them with the baseline.
