### Install IFBench Source: https://github.com/allenai/ifbench/blob/main/README.md Install the IFBench package using pip or uv. ```bash pip install ifbench # or uv add ifbench ``` -------------------------------- ### Minimal programmatic example using INSTRUCTION_DICT Source: https://github.com/allenai/ifbench Shows how to instantiate a verifier class from the registry by key, seed it with build_description, and check a response. The example uses the 'keywords:existence' verifier and asserts that a response containing 'cat' and 'dog' passes. ```python from ifbench import instructions_registry checker_cls = instructions_registry.INSTRUCTION_DICT["keywords:existence"] checker = checker_cls("keywords:existence") checker.build_description(keywords=["cat", "dog"]) assert checker.check_following("I saw a cat and a dog today.") is True ``` -------------------------------- ### Usage example for instructions_util helpers Source: https://github.com/allenai/ifbench Shows how to use count_words, count_sentences, and generate_keywords. Note that download_nltk_resources() runs at import, so a fresh environment triggers a silent first-time NLTK download. ```python from ifbench import instructions_util n = instructions_util.count_words("the quick brown fox jumps over the lazy dog") assert n == 9 assert instructions_util.count_sentences("Hello world. Bye.") == 2 kw = instructions_util.generate_keywords(num_keywords=2) assert len(kw) == 2 and all(k in instructions_util.WORD_LIST for k in kw) ``` -------------------------------- ### Sample .env.example for IFBench Source: https://github.com/allenai/ifbench Example environment file with API endpoint, key, model, and generation parameters. Note that MAX_TOKENS=8192 differs from the in-code default of 4096. ```bash API_BASE=https://some-openai-compatible-endpoint/v1 API_KEY=your-api-key-here MODEL=Qwen/Qwen3-VL-30B-A3B-Thinking-FP8 TEMPERATURE=0.6 MAX_TOKENS=8192 SEED=42 INPUT_FILE=data/IFBench_test.jsonl OUTPUT_FILE=data/responses.jsonl WORKERS=8 ``` -------------------------------- ### Verify release on PyPI Source: https://github.com/allenai/ifbench/blob/main/PUBLISHING.md Install the released version and check the registry count. Expect 83 or the new count. ```bash uv run --with "ifbench==0.3.0" python -c "from ifbench import instructions_registry; print(len(instructions_registry.INSTRUCTION_DICT))" ``` -------------------------------- ### Example usage of BenchmarkSettings and get_settings Source: https://github.com/allenai/ifbench Shows how to instantiate BenchmarkSettings with custom values and load settings from .env and environment using get_settings(). The get_settings() call is not memoized, so each call re-reads config. ```python from config import BenchmarkSettings, get_settings s = BenchmarkSettings(api_base="https://api.openai.com/v1", model="gpt-4o") s2 = get_settings() # loads .env + environment print(s2.api_base, s2.workers) ``` -------------------------------- ### Example usage of evaluation_lib Source: https://github.com/allenai/ifbench Shows how to read inputs and responses, score the first 20 examples loosely, compute accuracy, and print a report. ```python import evaluation_lib from ifbench import instructions_registry inputs = evaluation_lib.read_prompt_list("data/IFBench_test.jsonl") prompt2resp = evaluation_lib.read_prompt_to_response_dict("data/sample_output.jsonl") # Score the first 20 examples loosely results = [] for inp in inputs[:20]: results.append(evaluation_lib.test_instruction_following_loose(inp, prompt2resp)) accuracy = sum(o.follow_all_instructions for o in results) / len(results) print(f"loose accuracy: {accuracy}") evaluation_lib.print_report(results) ``` -------------------------------- ### data_path usage example Source: https://github.com/allenai/ifbench Shows how to call data_path() to get the path to the bundled IFBench_test.jsonl file and read it line by line. The helper is preferred over relative paths because the file lives inside the wheel's package data. ```python from pathlib import Path from ifbench import data_path path: Path = data_path() # -> .../ifbench/data/IFBench_test.jsonl alt = data_path("IFBench_multi-turn.jsonl") # would resolve if bundled for line in open(path, "r"): pass # consume jsonl rows ``` -------------------------------- ### Tag and push release tag Source: https://github.com/allenai/ifbench/blob/main/PUBLISHING.md Create a tag starting with 'v' and push it to trigger the release workflow. The tag must match the version in pyproject.toml. ```bash git tag v0.3.0 git push origin v0.3.0 ``` -------------------------------- ### Example usage of generate_response Source: https://github.com/allenai/ifbench Example showing how to call generate_response with an httpx.Client. Uses api_key=None and seed=42. Prints the returned text. ```python import httpx from generate_responses import generate_response with httpx.Client() as client: text = generate_response( client, "http://localhost:8000/v1", "gpt-4o-mini", "Hello", 0.0, 100, api_key=None, seed=42) print(text) ``` -------------------------------- ### write_outputs function Source: https://github.com/allenai/ifbench Serializes every OutputExample as one JSON line per example. Raises AssertionError if outputs is empty. ```python def write_outputs(output_jsonl_filename, outputs): """Writes outputs to jsonl.""" assert outputs ``` -------------------------------- ### write_outputs(output_jsonl_filename, outputs) Source: https://github.com/allenai/ifbench Serializes every OutputExample (all public dataclass fields) as one JSON line per example. Raises AssertionError if outputs is empty. ```APIDOC ## write_outputs(output_jsonl_filename, outputs) ### Description Writes outputs to jsonl. Serializes every OutputExample (all public dataclass fields) as one JSON line per example. Raises `AssertionError` if `outputs` is empty. ### Parameters - `output_jsonl_filename` (str) - Required - Path to the output jsonl file. - `outputs` (list[OutputExample]) - Required - List of OutputExample objects to write. ### Example ```python evaluation_lib.write_outputs("output.jsonl", results) ``` ``` -------------------------------- ### Example invocation with sample data Source: https://github.com/allenai/ifbench Runs evaluation on bundled test data and sample responses, writing eval results to the eval directory and printing accuracy reports. ```bash python -m run_eval \ --input_data=data/IFBench_test.jsonl \ --input_response_data=data/sample_output.jsonl \ --output_dir=eval ``` -------------------------------- ### OutputExample dataclass Source: https://github.com/allenai/ifbench Dataclass holding the scoring result for one example. Fields include instruction_id_list, prompt, response, follow_all_instructions, and follow_instruction_list. Produced by evaluation functions and consumed by write_outputs and print_report. ```python @dataclasses.dataclass class OutputExample: instruction_id_list: list[str] prompt: str response: str follow_all_instructions: bool follow_instruction_list: list[bool] ``` -------------------------------- ### data_path Source: https://github.com/allenai/ifbench Returns the filesystem path to a bundled data file inside the installed package's data directory. This helper is built on importlib.resources and should be preferred over relative paths. ```APIDOC ## [FUNCTION] data_path ### Description Returns the filesystem path to a bundled data file inside the installed package's data directory. This helper is built on importlib.resources and should be preferred over relative paths. ### Signature ```python def data_path(name: str = "IFBench_test.jsonl") -> Path: ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `name` | `str` | no | `"IFBench_test.jsonl"` | Name of the bundled data file. | ### Returns `pathlib.Path` — a `traversable` path into the wheel/installed package's `data/` directory. The wheel bundles `ifbench/data/IFBench_test.jsonl`. ### Example ```python from pathlib import Path from ifbench import data_path path: Path = data_path() # -> .../ifbench/data/IFBench_test.jsonl alt = data_path("IFBench_multi-turn.jsonl") # would resolve if bundled for line in open(path, "r"): pass # consume jsonl rows ``` ``` -------------------------------- ### Catch ValueError for invalid relation in NumberOfWords.build_description Source: https://github.com/allenai/ifbench Wrap the call to catch ValueError when relation is not 'less than' or 'at least'. The example passes relation='exactly' which triggers the error. ```python try: NumberOfWords("length_constraints:number_words").build_description( num_words=50, relation="exactly") # raises ValueError except ValueError: # relation must be "less than" or "at least" pass ``` -------------------------------- ### Run full test suite locally Source: https://github.com/allenai/ifbench/blob/main/PUBLISHING.md Synchronize dependencies and run the test suite to ensure everything passes before release. ```bash uv sync uv run python instructions_test.py ``` -------------------------------- ### download_nltk_resources() Source: https://github.com/allenai/ifbench Idempotently ensures required NLTK resources are available, downloading them quietly if missing. Called automatically at module import. ```APIDOC ## download_nltk_resources() ### Description Download 'punkt' and 'stopwords' if not already installed. No arguments, no return. ### Method Function call ### Endpoint `download_nltk_resources()` ### Parameters None ### Response None ``` -------------------------------- ### Clone and Sync IFBench for Development Source: https://github.com/allenai/ifbench/blob/main/README.md Clone the repository and synchronize dependencies using uv. ```bash git clone https://github.com/allenai/IFBench.git cd IFBench uv sync ``` -------------------------------- ### Instruction.build_description Source: https://github.com/allenai/ifbench Builds and returns the prompt description for the instruction. Stores parameters on the instance. Abstract method that raises NotImplementedError. ```APIDOC ## Instruction.build_description ### Description Builds and returns the prompt description for the instruction. Stores parameters on the instance. Abstract method that raises NotImplementedError. ### Method Method ### Signature `build_description(self, **kwargs)` ### Parameters - **kwargs** (dict) - Optional - Keyword arguments used to build the description. ### Returns `str` - The prompt description. ``` -------------------------------- ### Usage pattern for Instruction subclass Source: https://github.com/allenai/ifbench Shows how to implement a custom Instruction subclass with build_description, get_instruction_args, get_instruction_args_keys, and check_following, and how to instantiate and use it. ```python class MyChecker(Instruction): def build_description(self, *, n=None): self._n = n if n is not None else 3 return f"Use at least {self._n} words." def get_instruction_args(self): return {"n": self._n} def get_instruction_args_keys(self): return ["n"] def check_following(self, value): return len(value.split()) >= self._n c = MyChecker("my:key") c.build_description(n=5) assert c.get_instruction_args() == {"n": 5} assert c.check_following("one two three four five") is True ``` -------------------------------- ### Programmatic Use of IFBench Verifiers Source: https://github.com/allenai/ifbench/blob/main/README.md Use the instructions_registry to instantiate a verifier and check if a model response follows specific keyword constraints. ```python from ifbench import instructions_registry checker_cls = instructions_registry.INSTRUCTION_DICT["keywords:existence"] checker = checker_cls("keywords:existence") checker.build_description(keywords=["cat", "dog"]) checker.check_following("I saw a cat and a dog today.") # True ``` -------------------------------- ### Build and inspect wheel contents Source: https://github.com/allenai/ifbench/blob/main/PUBLISHING.md Build the package and list the wheel contents to confirm the data file is included. The command prints the names of all files in the wheel. ```bash uv build uv run python -c "import zipfile; z=zipfile.ZipFile('dist/ifbench-0.3.0-py3-none-any.whl'); print('\n'.join(z.namelist()))" ``` -------------------------------- ### Instruction.__init__ Source: https://github.com/allenai/ifbench Initializes an Instruction instance with a given instruction ID. Stores the ID as the instance attribute `id`. ```APIDOC ## Instruction.__init__ ### Description Initializes an Instruction instance with a given instruction ID. Stores the ID as the instance attribute `id`. ### Method Constructor ### Signature `__init__(self, instruction_id)` ### Parameters - **instruction_id** (str) - Required - The unique identifier for the instruction. ### Returns `None` ``` -------------------------------- ### test_instruction_following_strict(inp, prompt_to_response) → OutputExample Source: https://github.com/allenai/ifbench Scoring (strict): for each instruction id, instantiate the verifier from INSTRUCTION_DICT, call build_description(**inp.kwargs[index]) (dropping None values), and record instruction.check_following(response). If an arg dict contains "prompt", it re-calls build_description(prompt=inp.prompt). If no response exists, returns empty_output(inp). follow_all_instructions is True only if every instruction passed. ```APIDOC ## test_instruction_following_strict(inp, prompt_to_response) → OutputExample ### Description Scoring (strict): for each instruction id, instantiate the verifier from `INSTRUCTION_DICT`, call `build_description(**inp.kwargs[index])` (dropping `None` values), and record `instruction.check_following(response)`. If an arg dict contains `"prompt"`, it re-calls `build_description(prompt=inp.prompt)`. If no response exists, returns `empty_output(inp)`. `follow_all_instructions` is `True` only if every instruction passed. ### Parameters - `inp` (InputExample) - Required - Example to score. - `prompt_to_response` (dict[str, str]) - Required - Prompt→response lookup (from `read_prompt_to_response_dict`). ### Returns - `OutputExample` - The scoring result. ### Example ```python result = evaluation_lib.test_instruction_following_strict(inp, prompt2resp) ``` ``` -------------------------------- ### split_into_sentences(text) Source: https://github.com/allenai/ifbench Splits the input text into sentences using NLTK's sentence tokenizer. Returns a list of sentence strings. ```APIDOC ## split_into_sentences(text) ### Description Split the text into sentences using NLTK. ### Method Function call ### Endpoint `split_into_sentences(text)` ### Parameters #### Path Parameters - **text** (str) - Required - Text of ≥ 1 sentence. ### Response #### Success Response - Returns `list[str]` of sentences. ``` -------------------------------- ### generate_keywords(num_keywords) Source: https://github.com/allenai/ifbench Randomly samples a specified number of keywords from the WORD_LIST constant without replacement. Returns a list of keyword strings. ```APIDOC ## generate_keywords(num_keywords) ### Description Randomly generates a few keywords. ### Method Function call ### Endpoint `generate_keywords(num_keywords)` ### Parameters #### Path Parameters - **num_keywords** (int) - Required - Number of keywords to sample. ### Response #### Success Response - Returns `list[str]` sampled from `WORD_LIST` without replacement. ``` -------------------------------- ### WordCountRangeChecker: build_description and check_following Source: https://github.com/allenai/ifbench Builds a description requiring a word count between min_words and max_words, then verifies that a response with 60 words passes the check. ```python WordCountRangeChecker("count:word_count_range").build_description( min_words=50, max_words=100) # "The response must contain between 50 and 100 words." checker = WordCountRangeChecker("...") checker.build_description(min_words=50, max_words=100) assert checker.check_following("a b c d e " * 12) is True ``` -------------------------------- ### Instruction.get_instruction_args Source: https://github.com/allenai/ifbench Returns the concrete parameters used by `build_description`, or `None` if no parameters were set. Abstract method that raises NotImplementedError. ```APIDOC ## Instruction.get_instruction_args ### Description Returns the concrete parameters used by `build_description`, or `None` if no parameters were set. Abstract method that raises NotImplementedError. ### Method Method ### Signature `get_instruction_args(self)` ### Returns `Optional[Dict[str, ...]]` - The parameters used by `build_description`, or `None`. ``` -------------------------------- ### read_prompt_list(input_jsonl_filename) → list[InputExample] Source: https://github.com/allenai/ifbench Reads the IFBench test jsonl file and maps each line to an InputExample. Each line must contain 'key', 'instruction_id_list', 'prompt', and 'kwargs' keys. ```APIDOC ## read_prompt_list(input_jsonl_filename) → list[InputExample] ### Description Reads the IFBench test jsonl. Each line must contain `key`, `instruction_id_list`, `prompt`, `kwargs` keys, mapped onto `InputExample` (`key` is loaded as `int` via `example["key"]`). Returns `list[InputExample]`. ### Parameters - `input_jsonl_filename` (str) - Required - Path to the input jsonl file. ### Returns - `list[InputExample]` - List of InputExample objects. ### Example ```python inputs = evaluation_lib.read_prompt_list("data/IFBench_test.jsonl") ``` ``` -------------------------------- ### download_nltk_resources() function definition Source: https://github.com/allenai/ifbench Idempotently ensures NLTK resources 'punkt', 'punkt_tab', 'stopwords', and 'averaged_perceptron_tagger_eng' are available, downloading via nltk.download(..., quiet=True) on LookupError. Called once at module load; no arguments, no return. ```python def download_nltk_resources(): """Download 'punkt' and 'stopwords' if not already installed""" ``` -------------------------------- ### Usage: Access INSTRUCTION_DICT and instantiate a checker Source: https://github.com/allenai/ifbench Shows how to import the shared registry, retrieve a verifier class by its stable key, instantiate it with the same key, and call its methods. Accessing a key not present in the registry raises KeyError. ```python from ifbench import instructions_registry checker_cls = instructions_registry.INSTRUCTION_DICT["keywords:existence"] checker = checker_cls("keywords:existence") # instantiate with its registry key checker.build_description(keywords=["cat", "dog"]) checker.check_following("I saw a cat and a dog today.") # True ``` -------------------------------- ### INSTRUCTION_DICT Source: https://github.com/allenai/ifbench A module-level dictionary mapping stable string keys to verifier classes. It contains 83 entries: 25 classic IFEval keys and 58 IFBench OOD keys. Accessing a key not present raises KeyError. ```APIDOC ## INSTRUCTION_DICT ### Description A module-level `dict[str, type[Instruction]]` that maps stable string keys to verifier classes. It is built literally and contains 83 entries: 25 classic IFEval keys and 58 IFBench OOD keys. Accessing a key not present raises `KeyError`. ### Usage ```python from ifbench import instructions_registry checker_cls = instructions_registry.INSTRUCTION_DICT["keywords:existence"] checker = checker_cls("keywords:existence") # instantiate with its registry key checker.build_description(keywords=["cat", "dog"]) checker.check_following("I saw a cat and a dog today.") # True ``` ### Keys #### Classic keys (25) | Key | Class | |-----|-------| | `keywords:existence` | `classic_instructions.KeywordChecker` | | `keywords:frequency` | `classic_instructions.KeywordFrequencyChecker` | | `keywords:forbidden_words` | `classic_instructions.ForbiddenWords` | | `keywords:letter_frequency` | `classic_instructions.LetterFrequencyChecker` | | `language:response_language` | `classic_instructions.ResponseLanguageChecker` | | `length_constraints:number_sentences` | `classic_instructions.NumberOfSentences` | | `length_constraints:number_paragraphs` | `classic_instructions.ParagraphChecker` | | `length_constraints:number_words` | `classic_instructions.NumberOfWords` | | `length_constraints:nth_paragraph_first_word` | `classic_instructions.ParagraphFirstWordCheck` | | `detectable_content:number_placeholders` | `classic_instructions.PlaceholderChecker` | | `detectable_content:postscript` | `classic_instructions.PostscriptChecker` | | `detectable_format:number_bullet_lists` | `classic_instructions.BulletListChecker` | | `detectable_format:constrained_response` | `classic_instructions.ConstrainedResponseChecker` | | `detectable_format:number_highlighted_sections` | `classic_instructions.HighlightSectionChecker` | | `detectable_format:multiple_sections` | `classic_instructions.SectionChecker` | | `detectable_format:json_format` | `classic_instructions.JsonFormat` | | `detectable_format:title` | `classic_instructions.TitleChecker` | | `combination:two_responses` | `classic_instructions.TwoResponsesChecker` | | `combination:repeat_prompt` | `classic_instructions.RepeatPromptThenAnswer` | | `startend:end_checker` | `classic_instructions.EndChecker` | | `change_case:capital_word_frequency` | `classic_instructions.CapitalWordFrequencyChecker` | | `change_case:english_capital` | `classic_instructions.CapitalLettersEnglishChecker` | | `change_case:english_lowercase` | `classic_instructions.LowercaseLettersEnglishChecker` | | `punctuation:no_comma` | `classic_instructions.CommaChecker` | | `startend:quotation` | `classic_instructions.QuotationChecker` | #### IFBench OOD keys (58) Not listed in the source; refer to the registry for the full list. ``` -------------------------------- ### Instruction.get_instruction_args_keys Source: https://github.com/allenai/ifbench Returns an ordered list of keys for the args dictionary. Abstract method that raises NotImplementedError. ```APIDOC ## Instruction.get_instruction_args_keys ### Description Returns an ordered list of keys for the args dictionary. Abstract method that raises NotImplementedError. ### Method Method ### Signature `get_instruction_args_keys(self)` ### Returns `list[str]` - Ordered key list for the args dict. ``` -------------------------------- ### generate_keywords(num_keywords) function definition Source: https://github.com/allenai/ifbench Randomly samples num_keywords keywords from WORD_LIST without replacement using random.sample. Returns a list of strings. ```python def generate_keywords(num_keywords): """Randomly generates a few keywords.""" return random.sample(WORD_LIST, k=num_keywords) ``` -------------------------------- ### Instruction.check_following Source: https://github.com/allenai/ifbench Checks whether a response string satisfies the instruction's constraint. Abstract method that raises NotImplementedError. ```APIDOC ## Instruction.check_following ### Description Checks whether a response string satisfies the instruction's constraint. Abstract method that raises NotImplementedError. ### Method Method ### Signature `check_following(self, value)` ### Parameters - **value** (str) - Required - The response string to check. ### Returns `bool` - `True` if the response satisfies the constraint, `False` otherwise. ``` -------------------------------- ### test_instruction_following_strict function Source: https://github.com/allenai/ifbench Scoring (strict): for each instruction id, instantiate the verifier from INSTRUCTION_DICT, call build_description(**inp.kwargs[index]) (dropping None values), and record instruction.check_following(response). If an arg dict contains 'prompt', it re-calls build_description(prompt=inp.prompt). If no response exists, returns empty_output(inp). follow_all_instructions is True only if every instruction passed. ```python def test_instruction_following_strict( inp, prompt_to_response, ): ``` -------------------------------- ### empty_output(inp) → OutputExample Source: https://github.com/allenai/ifbench Builds a failing OutputExample with an empty response and all instruction flags set to False when no response exists for a prompt. ```APIDOC ## empty_output(inp) → OutputExample ### Description Builds a failing OutputExample (response="", all flags False) when no response exists for a prompt. ### Parameters - `inp` (InputExample) - Required - The input example for which to build the failed output. ### Returns - `OutputExample` - An OutputExample with empty response and all follow flags set to False. ### Example ```python failed_output = evaluation_lib.empty_output(inp) ``` ``` -------------------------------- ### SettingsConfigDict for BenchmarkSettings Source: https://github.com/allenai/ifbench Configuration for pydantic-settings BaseSettings, loading from .env file with utf-8 encoding and ignoring extra fields. ```python SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", extra="ignore", ) ``` -------------------------------- ### build_description Source: https://github.com/allenai/ifbench Fill in or randomize the instruction parameters and return the instruction description string. This method is part of the template-method interface. ```APIDOC ## build_description(**kwargs) ### Description Build the instruction description by filling in or randomizing parameters. Returns the description string. ### Method Method (Python) ### Endpoint `Instruction.build_description(**kwargs)` ### Parameters - **kwargs** (dict) - Optional - Parameters to fill in the instruction template. ### Returns - **description** (str) - The instruction description string. ### Request Example ```python checker.build_description(keywords=["cat", "dog"]) ``` ``` -------------------------------- ### Run Evaluation Source: https://github.com/allenai/ifbench/blob/main/README.md Execute the evaluation script using uv, providing the test data and model response data. ```bash uv run python -m run_eval --input_data=IFBench_test.jsonl --input_response_data=sample_output.jsonl --output_dir=eval ``` -------------------------------- ### KeywordChecker: required keywords Source: https://github.com/allenai/ifbench Builds a description for the 'keywords:existence' instruction and checks that all required keywords are present. Returns False as soon as any keyword is missing. ```python from ifbench.classic_instructions import KeywordChecker c = KeywordChecker("keywords:existence") c.build_description(keywords=["cat", "dog"]) assert c.check_following("I saw a cat and a dog today.") is True assert c.check_following("I saw neither.") is False ``` -------------------------------- ### get_settings function definition Source: https://github.com/allenai/ifbench Defines get_settings() which returns a BenchmarkSettings instance populated from .env and environment variables. It takes no arguments and is not memoized. ```python def get_settings() -> BenchmarkSettings: """Load settings from environment and .env file.""" return BenchmarkSettings() ``` -------------------------------- ### count_sentences(text) Source: https://github.com/allenai/ifbench Counts the number of sentences in the given text using a cached English Punkt tokenizer. Returns an integer count. ```APIDOC ## count_sentences(text) ### Description Count the number of sentences. ### Method Function call ### Endpoint `count_sentences(text)` ### Parameters #### Path Parameters - **text** (str) - Required - Text to count. ### Response #### Success Response - Returns `int` — number of sentences via the cached English Punkt tokenizer. ``` -------------------------------- ### main() Source: https://github.com/allenai/ifbench Argparse CLI entry point that generates responses for a set of prompts. Validates required arguments, loads prompts, and uses a thread pool to generate responses concurrently. ```APIDOC ## main() ### Description Argparse CLI entry point that generates responses for a set of prompts. Validates required arguments, loads prompts, and uses a thread pool to generate responses concurrently. ### Usage ``` python generate_responses.py --model=... [--api-base=...] [--input-file=...] [--output-file=...] [--temperature=...] [--max-tokens=...] [--seed=...] [--api-key=...] [--workers=...] [--resume] ``` ### Behavior 1. Validates `model` and `api_base` (calls `parser.error` → exit non-zero if missing). 2. `load_prompts(input_file)`; default `output_file` = `data/{model with "/" → "-"}-responses.jsonl`. 3. If `--resume` and the output file exists, loads prior rows, skipping already completed prompts. 4. Uses `ThreadPoolExecutor(max_workers=workers)` with one shared `httpx.Client` and `tqdm` progress. Per-request failures are caught, recorded in `errors`, and written as a row with `"response": ""` so evaluation can still run. 5. Incrementally saves every 10 results; final save writes the full list, prints a summary and the follow-on `run_eval` command. ### Exit Codes / errors - Missing `--model` or `--api-base` → `parser.error` (SystemExit, non-zero). - HTTP failures inside `generate_response` are surfaced as exceptions caught by `main` and stored as error rows. ``` -------------------------------- ### empty_output function Source: https://github.com/allenai/ifbench Builds a failing OutputExample with empty response and all False flags when no response exists for a prompt. ```python def empty_output(inp): """Builds a failed output for prompts with no generated response.""" return OutputExample( instruction_id_list=inp.instruction_id_list, prompt=inp.prompt, response="", follow_all_instructions=False, follow_instruction_list=[False] * len(inp.instruction_id_list), ) ``` -------------------------------- ### get_instruction_args_keys Source: https://github.com/allenai/ifbench Return the ordered list of parameter keys used for the instruction. ```APIDOC ## get_instruction_args_keys() ### Description Return the ordered list of parameter keys used for the instruction. ### Method Method (Python) ### Endpoint `Instruction.get_instruction_args_keys()` ### Returns - **list** - Ordered list of parameter keys. ``` -------------------------------- ### check_following Source: https://github.com/allenai/ifbench Check whether a response string satisfies the instruction constraint. Returns True if the response follows the instruction, False otherwise. ```APIDOC ## check_following(value) ### Description Evaluate a response string against the instruction constraint. Returns a boolean indicating whether the response follows the instruction. ### Method Method (Python) ### Endpoint `Instruction.check_following(value)` ### Parameters - **value** (str) - Required - The response string to check. ### Returns - **bool** - True if the response follows the instruction, False otherwise. ### Request Example ```python assert checker.check_following("I saw a cat and a dog today.") is True ``` ``` -------------------------------- ### load_prompts(input_file: str) -> list[dict] Source: https://github.com/allenai/ifbench Loads prompts from an IFBench test file. Reads jsonl rows, each must contain 'key' and 'prompt', and returns a list of dictionaries with those fields. ```APIDOC ## load_prompts(input_file: str) -> list[dict] ### Description Loads prompts from an IFBench test file. Reads jsonl rows, each must contain `key` and `prompt`, and returns a list of dictionaries with `{"key": ..., "prompt": ...}`. ### Parameters - `input_file` (str) - Required - Path to the input jsonl file. ### Returns - `list[dict]` - List of dictionaries with `key` and `prompt` fields. ``` -------------------------------- ### count_words(text) Source: https://github.com/allenai/ifbench Counts the number of words in the given text using a regex tokenizer that matches word characters. Returns an integer count. ```APIDOC ## count_words(text) ### Description Counts the number of words. ### Method Function call ### Endpoint `count_words(text)` ### Parameters #### Path Parameters - **text** (str) - Required - Text to count. ### Response #### Success Response - Returns `int` — number of `\w+` tokens. ``` -------------------------------- ### Module graph Source: https://github.com/allenai/ifbench Shows the dependency structure of the ifbench package: the top-level __init__.py exposes data_path and the four submodules, with instructions_util as the common dependency for the verifier modules. ```text ifbench/__init__.py ├── data_path() ├── ifbench/instructions.py (Instruction base + 58 OOD checkers) │ └── ifbench/instructions_util.py ├── ifbench/classic_instructions.py (25 classic checkers) │ └── ifbench/instructions.py (Instruction) → instructions_util └── ifbench/instructions_registry.py └── classic_instructions, instructions ``` -------------------------------- ### _get_sentence_tokenizer() private cached helper Source: https://github.com/allenai/ifbench Private cached point-sentence tokenizer using functools.lru_cache. Loads the English Punkt tokenizer from NLTK data. Not part of the public surface. ```python @functools.lru_cache(maxsize=None) def _get_sentence_tokenizer(): return nltk.data.load("nltk:tokenizers/punkt/english.pickle") ``` -------------------------------- ### Commit and push version bump Source: https://github.com/allenai/ifbench/blob/main/PUBLISHING.md Stage the pyproject.toml change, commit with a message, and push to the remote. ```bash git add pyproject.toml git commit -m "Bump version to 0.3.0" git push ``` -------------------------------- ### Instruction constructor Source: https://github.com/allenai/ifbench Instantiate an instruction verifier with a unique instruction ID. The constructor stores the ID for later use. ```APIDOC ## Instruction(instruction_id) ### Description Create a new instruction verifier instance. The constructor stores the provided instruction ID. ### Method Constructor (Python) ### Endpoint `Instruction.__init__(instruction_id)` ### Parameters - **instruction_id** (str) - Required - The unique identifier for the instruction. ### Returns - **Instruction** - An instance of the verifier. ### Request Example ```python checker = checker_cls("keywords:existence") ``` ``` -------------------------------- ### generate_responses CLI Source: https://github.com/allenai/ifbench Command-line entry point for generating model responses from an OpenAI-compatible endpoint. Produces a response jsonl for later evaluation. ```APIDOC ## python generate_responses.py ### Description Generate model responses using an OpenAI-compatible endpoint. The output jsonl can be used as input to run_eval. ### Method CLI ### Endpoint `python generate_responses.py --model=... --api-base=...` ### Parameters - **--model** (str) - Required - The model identifier to use. - **--api-base** (str) - Required - The base URL of the OpenAI-compatible API. ### Request Example ```bash python generate_responses.py --model=gpt-4 --api-base=https://api.openai.com/v1 ``` ``` -------------------------------- ### run_eval CLI Source: https://github.com/allenai/ifbench Command-line entry point for running evaluation. Reads a data jsonl and a response jsonl, instantiates verifiers, and computes scores. ```APIDOC ## python -m run_eval ### Description Run the evaluation CLI. It reads a data jsonl and a response jsonl, instantiates each listed verifier by key, seeds it via build_description, and calls check_following on each response. ### Method CLI ### Endpoint `python -m run_eval --input_data=... --input_response_data=... --output_dir=...` ### Parameters - **--input_data** (str) - Required - Path to the data jsonl file. - **--input_response_data** (str) - Required - Path to the response jsonl file. - **--output_dir** (str) - Required - Directory to write evaluation outputs. ### Request Example ```bash python -m run_eval --input_data=data.jsonl --input_response_data=responses.jsonl --output_dir=results/ ``` ``` -------------------------------- ### test_instruction_following_loose(inp, prompt_to_response) → OutputExample Source: https://github.com/allenai/ifbench Scoring (loose / upper bound): builds 8 candidate variants of the response and marks an instruction followed if any variant passes: response, response.removeprefix(first_line), response.removesuffix(last_line), response minus both first and last lines, and each of those with "*" stripped out. Otherwise the flow mirrors the strict variant. ```APIDOC ## test_instruction_following_loose(inp, prompt_to_response) → OutputExample ### Description Scoring (loose / upper bound): builds 8 candidate variants of the response and marks an instruction followed if **any** variant passes: `response`, `response.removeprefix(first_line)`, `response.removesuffix(last_line)`, `response` minus both first and last lines, and each of those with `"*"` stripped out. Otherwise the flow mirrors the strict variant. ### Parameters - `inp` (InputExample) - Required - Example to score. - `prompt_to_response` (dict[str, str]) - Required - Prompt→response lookup (from `read_prompt_to_response_dict`). ### Returns - `OutputExample` - The scoring result. ### Example ```python result = evaluation_lib.test_instruction_following_loose(inp, prompt2resp) ``` ``` -------------------------------- ### Citation Source: https://github.com/allenai/ifbench/blob/main/README.md BibTeX citation for the IFBench paper. ```bibtex @misc{pyatkin2025generalizing, title={Generalizing Verifiable Instruction Following}, author={Valentina Pyatkin and Saumya Malik and Victoria Graf and Hamish Ivison and Shengyi Huang and Pradeep Dasigi and Nathan Lambert and Hannaneh Hajishirzi}, year={2025}, journal={Advances in Neural Information Processing Systems}, volume={38}, year={2025} } ``` -------------------------------- ### OptionsResponseChecker: strict vs loose matching Source: https://github.com/allenai/ifbench Shows strict exact match when options follow the multi-choice pattern (e.g., "a), b), c), d)") and loose matching with punctuation stripped and lowercasing for other options (e.g., "yes/no/maybe"). ```python c = OptionsResponseChecker("format:options") c.build_description(options="a), b), c), d)") assert c.check_following("b)") is True # strict exact match c2 = OptionsResponseChecker("format:options") c2.build_description(options="yes/no/maybe") assert c2.check_following("No.") is True # punctuation stripped → "no" matches option ``` -------------------------------- ### read_prompt_list function Source: https://github.com/allenai/ifbench Reads inputs from a jsonl file. Each line must contain 'key', 'instruction_id_list', 'prompt', 'kwargs' keys, mapped onto InputExample. Returns a list of InputExample. ```python def read_prompt_list(input_jsonl_filename): """Read inputs from jsonl.""" ``` -------------------------------- ### BenchmarkSettings class definition Source: https://github.com/allenai/ifbench Defines the BenchmarkSettings class using pydantic-settings. It reads from .env and environment variables, with extra='ignore' to drop unknown vars. All fields have defaults, and the constructor requires no arguments. ```python class BenchmarkSettings(BaseSettings): """Settings for running IFBench benchmarks.""" model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", extra="ignore", ) api_base: str = Field(default="http://localhost:8000/v1", ...) api_key: str | None = Field(default=None, ...) model: str = Field(default="", ...) temperature: float = Field(default=0.6, ...) max_tokens: int = Field(default=4096, ...) seed: int | None = Field(default=42, ...) input_file: str = Field(default="data/IFBench_test.jsonl", ...) output_file: str = Field(default="data/responses.jsonl", ...) workers: int = Field(default=8, ...) ``` -------------------------------- ### INSTRUCTION_DICT registry lookup Source: https://github.com/allenai/ifbench Access the verifier class registry by key and instantiate a verifier to check instruction following. ```APIDOC ## INSTRUCTION_DICT[key] ### Description Retrieve a verifier class from the registry by its stable key (e.g., "keywords:existence"). The returned class can be instantiated and used to check whether a response follows the instruction. ### Method Registry access (Python attribute) ### Endpoint `ifbench.instructions_registry.INSTRUCTION_DICT[key]` ### Parameters - **key** (str) - Required - The registry key for the verifier class (e.g., "keywords:existence"). ### Returns - **verifier_class** (type) - The verifier class bound to the key. ### Request Example ```python from ifbench import instructions_registry checker_cls = instructions_registry.INSTRUCTION_DICT["keywords:existence"] ``` ``` -------------------------------- ### print_report(outputs) Source: https://github.com/allenai/ifbench Prints to stdout: prompt-level accuracy, instruction-level accuracy, then per-prefix (tier-0, group before :) accuracy and per-instruction (tier-1, full key) accuracy, each sorted. ```APIDOC ## print_report(outputs) ### Description Prints to stdout: `prompt-level` accuracy, `instruction-level` accuracy, then per-prefix (tier-0, group before `:`) accuracy and per-instruction (tier-1, full key) accuracy, each sorted. ### Parameters - `outputs` (list[OutputExample]) - Required - List of OutputExample objects to report on. ### Example ```python evaluation_lib.print_report(results) ``` ``` -------------------------------- ### count_stopwords(text) Source: https://github.com/allenai/ifbench Counts the number of English stopwords in the given text, case-insensitively. Returns an integer count. ```APIDOC ## count_stopwords(text) ### Description Counts the number of stopwords. ### Method Function call ### Endpoint `count_stopwords(text)` ### Parameters #### Path Parameters - **text** (str) - Required - Text to count. ### Response #### Success Response - Returns `int` — number of English stopword tokens (case-insensitive). ``` -------------------------------- ### get_response_for_prompt(inp, prompt_to_response) → Optional[str] Source: https://github.com/allenai/ifbench Looks up inp.prompt; if absent, falls back to prompt_to_response.get(inp.prompt.strip()). Returns the response string or None. ```APIDOC ## get_response_for_prompt(inp, prompt_to_response) → Optional[str] ### Description Looks up `inp.prompt`; if absent, falls back to `prompt_to_response.get(inp.prompt.strip())`. Returns the response string or `None`. ### Parameters - `inp` (InputExample) - Required - The input example containing the prompt. - `prompt_to_response` (dict[str, str]) - Required - Prompt→response lookup. ### Returns - `Optional[str]` - The response string or None if not found. ### Example ```python response = evaluation_lib.get_response_for_prompt(inp, prompt2resp) ``` ``` -------------------------------- ### InputExample dataclass Source: https://github.com/allenai/ifbench Dataclass describing one benchmark row read from the IFBench test jsonl. Fields include key, instruction_id_list, prompt, and kwargs. Produced by evaluation_lib.read_prompt_list and consumed by evaluation functions. ```python @dataclasses.dataclass class InputExample: key: int instruction_id_list: list[str] prompt: str kwargs: list[Dict[str, Optional[Union[str, int]]]] ``` -------------------------------- ### CLI usage for generate_responses.py Source: https://github.com/allenai/ifbench Shows the command-line invocation for the main() function. Defaults come from get_settings(). Requires --model and --api-base; other flags are optional. ```bash python generate_responses.py --model=... [--api-base=...] [--input-file=...] [--output-file=...] [--temperature=...] [--max-tokens=...] [--seed=...] [--api-key=...] [--workers=...] [--resume] ``` -------------------------------- ### get_response_for_prompt function Source: https://github.com/allenai/ifbench Looks up inp.prompt; if absent, falls back to prompt_to_response.get(inp.prompt.strip()). Returns the response string or None. ```python def get_response_for_prompt(inp, prompt_to_response): """Returns a prompt response, tolerating harmless leading/trailing spaces.""" ``` -------------------------------- ### ResponseLanguageChecker: check language response Source: https://github.com/allenai/ifbench Builds a description for the 'language:response_language' instruction and checks if a response matches the expected language. Detection failures are logged and return True. ```python from ifbench.classic_instructions import ResponseLanguageChecker c = ResponseLanguageChecker("language:response_language") c.build_description(language="en") assert c.check_following("The quick brown fox jumps.") is True # langdetect "en" assert c.check_following("Le renard brun saute.") is False # detected "fr" ``` -------------------------------- ### RepeatSpanChecker: error path and valid usage Source: https://github.com/allenai/ifbench Raises ValueError when prompt_to_repeat is missing; with prompt_to_repeat set, checks that a substring within the repeat span passes. ```python try: RepeatSpanChecker("repeat:repeat_span").build_description() # raises ValueError("prompt_to_repeat must be set.") except ValueError as e: pass c = RepeatSpanChecker("repeat:repeat_span") c.build_description(prompt_to_repeat="a b c d e", n_start=1, n_end=3) assert c.check_following("b c d") is True ``` -------------------------------- ### Set NLTK_DATA before importing NLTK Source: https://github.com/allenai/ifbench Sets the NLTK_DATA environment variable to a local .nltk_data directory before NLTK is imported, creating the directory if it does not exist. ```python _nltk_data_dir = Path(__file__).parent / ".nltk_data" _nltk_data_dir.mkdir(exist_ok=True) os.environ.setdefault("NLTK_DATA", str(_nltk_data_dir)) ``` -------------------------------- ### test_instruction_following_loose function Source: https://github.com/allenai/ifbench Scoring (loose / upper bound): builds 8 candidate variants of the response and marks an instruction followed if any variant passes: response, response.removeprefix(first_line), response.removesuffix(last_line), response minus both first and last lines, and each of those with '*' stripped out. Otherwise the flow mirrors the strict variant. ```python def test_instruction_following_loose( inp, prompt_to_response, ): ``` -------------------------------- ### read_prompt_to_response_dict(input_jsonl_filename) → dict[str, str] Source: https://github.com/allenai/ifbench Reads the response jsonl, mapping each line's prompt to response. Also registers the stripped prompt as a key (both .strip()-equal forms map to the same response). ```APIDOC ## read_prompt_to_response_dict(input_jsonl_filename) → dict[str, str] ### Description Reads the response jsonl, mapping each line's `prompt` → `response`. Also registers the stripped prompt as a key (both `.strip()`-equal forms map to the same response). ### Parameters - `input_jsonl_filename` (str) - Required - Path to the response jsonl file. ### Returns - `dict[str, str]` - Dictionary mapping prompts to responses. ### Example ```python prompt2resp = evaluation_lib.read_prompt_to_response_dict("data/sample_output.jsonl") ``` ``` -------------------------------- ### split_into_sentences(text) function definition Source: https://github.com/allenai/ifbench Splits text into sentences using nltk.sent_tokenize. Accepts a string of at least one sentence and returns a list of sentences. ```python def split_into_sentences(text): """Split the text into sentences using NLTK.""" return nltk.sent_tokenize(text) ```