Building a Small Evaluation Dataset

Ma Mahalakshmi V Updated 19 Sep 2026
7 min read ·Lesson 169 of 224

Recalling the Basics, Applying Them to New Ground

Unit 13, Lesson 2 introduced the core anatomy of an evaluation dataset: a collection of inputs, each paired with an expected output or grading criteria, used to measure how well a model-driven task performs. That lesson built a dataset around grading free-form model responses. This lesson applies the same underlying idea to a different, equally common situation: evaluating a classification-style task — one where the model's job is to pick a label from a fixed set — which is exactly the kind of task that shows up constantly in real applications (support ticket routing, content moderation, intent detection) and which pairs naturally with the tool-calling and structured-output testing from the last two lessons.

The dataset-building principles carry over directly: realistic inputs, a clear notion of "correct," enough examples to be meaningful, and deliberate coverage of edge cases — but the shape of the dataset and the way it gets used differs enough from Unit 13's example to be worth building from scratch here.

Defining the Task Precisely

Before writing a single example, the task needs an unambiguous definition, because an evaluation dataset is only as good as the labels in it. Consider a support-ticket triage task: given the text of a customer message, classify it into exactly one of billing, technical, account, or other.

VALID_CATEGORIES = {"billing", "technical", "account", "other"}


def is_valid_category(label: str) -> bool:
    return label in VALID_CATEGORIES

This tiny function is worth writing and testing on its own, independent of the model: it defines the boundary of what counts as a valid answer at all, and every dataset example and every grading step will rely on it. Skipping this step and leaving the category set implicit is a common source of disagreement later, when two people labeling data disagree about whether a billing question that also mentions a login problem is billing or account.

Structuring the Dataset

A small evaluation dataset is typically stored as a list of records, each with an input and the expected label, often persisted as JSON Lines (.jsonl) — one JSON object per line — because it is easy to append to, easy to diff in version control, and easy to stream without loading the whole file into memory.

import json

TRIAGE_DATASET = [
    {
        "id": "triage-001",
        "input": "I was charged twice for my subscription this month, can you refund one?",
        "expected_category": "billing",
    },
    {
        "id": "triage-002",
        "input": "The app crashes every time I try to upload a photo larger than 5MB.",
        "expected_category": "technical",
    },
    {
        "id": "triage-003",
        "input": "I can't log in anymore, it says my email isn't recognized.",
        "expected_category": "account",
    },
    {
        "id": "triage-004",
        "input": "Do you have a mobile app for Android?",
        "expected_category": "other",
    },
    {
        "id": "triage-005",
        "input": "My card on file expired and now I can't access premium features.",
        "expected_category": "billing",
    },
]


def save_dataset_as_jsonl(dataset: list[dict], path: str) -> None:
    with open(path, "w", encoding="utf-8") as f:
        for record in dataset:
            f.write(json.dumps(record) + "\n")


def load_dataset_from_jsonl(path: str) -> list[dict]:
    records = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                records.append(json.loads(line))
    return records

Each record carries a stable id, which matters more than it might first appear: an id lets you track a specific example's pass/fail status across runs and across model or prompt versions (used heavily in the regression-testing lesson later in this unit), rather than only knowing an aggregate pass rate that could hide the fact that the same three examples fail every single time. save_dataset_as_jsonl and load_dataset_from_jsonl are ordinary, fully deterministic functions — worth unit testing themselves, using the fakes-and-mocks-free techniques from Lesson 1, since a bug in how the dataset is read or written silently corrupts every evaluation built on top of it.

Sizing a Small Dataset and Deciding What "Small" Means

A dataset with five examples, as shown above, is enough to illustrate structure and mechanics, but not enough to draw a reliable conclusion about real-world accuracy — five examples can be memorized by chance or misjudged by an unlucky sample. A genuinely useful small evaluation dataset for a task like ticket triage typically starts in the range of 30 to 100 examples: large enough that a percentage score (like 92% accuracy) is statistically meaningful rather than noise from one or two lucky or unlucky examples, but small enough to build and review by hand without requiring a data-labeling team.

The right size depends on how many distinct behaviors you need to distinguish. If the categories are well separated (a billing complaint reads very differently from a technical bug report), fewer examples are needed to get a stable signal than if the categories overlap heavily (a message that is both a login problem and a billing complaint). As a rule of thumb, deliberately include several examples of the hardest real cases — the ones that could plausibly belong to more than one category — because those are exactly the cases where a model's actual behavior diverges most from what a naive test would reveal.

Covering Edge Cases Deliberately

A dataset built only from clean, obvious examples measures the easiest 80% of the problem and tells you almost nothing about the hard 20% that causes real support escalations. Building in edge cases on purpose is what turns a dataset from a demo into a useful tool.

EDGE_CASE_EXAMPLES = [
    {
        "id": "triage-edge-001",
        "input": "",  # empty input
        "expected_category": "other",
    },
    {
        "id": "triage-edge-002",
        "input": "I can't pay my bill because I can't log in to update my card.",
        "expected_category": "account",  # ambiguous: billing + account, but the blocker is login
    },
    {
        "id": "triage-edge-003",
        "input": "asdkjaslkdj",  # gibberish / non-language input
        "expected_category": "other",
    },
    {
        "id": "triage-edge-004",
        "input": "Please cancel my account and stop billing me immediately.",
        "expected_category": "billing",  # cancellation framed as a billing action
    },
]

FULL_TRIAGE_DATASET = TRIAGE_DATASET + EDGE_CASE_EXAMPLES

triage-edge-002 is deliberately ambiguous — a reasonable person could argue for either billing or account — and the dataset resolves that ambiguity explicitly by picking one label and documenting the reasoning in a comment. This is an important discipline: every ambiguous example in a real dataset should have its resolution justified somewhere (a comment, a labeling guideline document, or a note field), because without that, disagreements resurface every time someone reviews the dataset later, and the dataset's "correct" answers start to look arbitrary.

triage-edge-001 (empty input) and triage-edge-003 (gibberish) test something different from category-boundary ambiguity: they test whether the task handles degenerate input gracefully at all, which matters because real user input is messier than any curated dataset naturally suggests.

Splitting Dataset-Building From Grading

Notice that nothing in this dataset itself calls the model or computes a score — it is pure data. This separation is intentional and mirrors the design principle from earlier lessons: keep deterministic, testable pieces (the dataset structure, the loading/saving code, the validity check) separate from the piece that involves the model. The next lesson uses this exact dataset to compute accuracy, consistency, and failure-rate metrics; keeping the dataset itself free of any model-calling logic means it can be unit tested, version controlled, and reused across many different evaluation runs — including regression tests that compare two different prompts or model versions against the identical set of examples, which only works cleanly if the dataset does not change between runs.

Common Mistakes

  • Building a dataset with only easy, unambiguous examples. A model can score 100% on such a dataset while still failing regularly in production, because production input distribution always includes messier cases than a hastily assembled dataset does.
  • Leaving ambiguous labels undocumented. When two team members disagree about what the "correct" label should have been for an ambiguous example, and there is no recorded justification, the dataset's reliability as a ground truth erodes over time.
  • Conflating the dataset with the grading logic. Embedding scoring logic directly alongside the data (for example, hardcoding a comparison function next to each record) makes the dataset harder to reuse across different evaluation approaches, such as exact-match grading versus a model-graded rubric.

Best Practices

  • Give every example a stable, unique ID so results can be tracked per example across multiple evaluation runs, not just as an aggregate score.
  • Deliberately include edge cases and ambiguous examples, and document why each one was assigned its expected label, rather than relying only on clear-cut cases.
  • Keep the dataset as plain, model-agnostic data (for example, JSON Lines) separate from any grading or model-calling code, so the same dataset can support multiple different evaluation runs, prompts, or model versions.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Building a Small Evaluation Dataset and get answers drawn from it.

Signed-in readers only.