Table of Contents
- The quiz — find the bug
- How it works
- Prerequisites
- Setup
- Usage
- Outputs
- LangChain concepts used
- File layout
- Notes
The pipeline is built with LangChain LCEL Runnables (prompt | llm | parser), one candidate chain per Ollama model fanned out with RunnableParallel, followed by a judge chain calling OpenRouter through the OpenAI-compatible API (same approach as RAG_Introduction.ipynb).
The quiz — find the bug
The question (quizzes/brute_force/question.md) shows a brute-force password simulator and asks:
Why does the python program fail to match the ‘Average tries’ with ‘Expected average guesses’?
The bug: attempts = 0 is initialized before the trials loop, so the counter accumulates across trials instead of restarting each trial. average_tries therefore grows far above the expected N^L / 2 (half of all combinations, per the password-entropy formula).
attempts = 0 # BUG: outside the loop
for _ in tqdm(range(trials)):
...
tries_list.append(attempts) # keeps summing across trialsThe fix (from the #start of right_answer block of judge_python_question.md, copied verbatim into quizzes/brute_force/right_answer.md): move attempts = 0 inside the for loop.
In the 2026 manual runs, models like qwen3.5:4b confidently blamed hardware, RNG or statistical variance without spotting the reset issue.
Why judging against a right answer matters
A plausible-sounding wrong explanation is still a wrong answer. The judge chain compares the model’s answer to a reference one, so eloquence alone never scores.
How it works
flowchart TD Q["Quiz pack<br/>quizzes/brute_force/<br/>question.md · right_answer.md · judge_instructions.md"] --> C C["Candidate chain (LCEL)<br/>ChatPromptTemplate | ChatOllama | StrOutputParser"] --> P P["RunnableParallel fan-out<br/>one branch per model, sequential<br/>(max_concurrency=1)"] --> A A["results/<run_ts>/answers/<model>.md<br/>frontmatter + raw answer"] --> J J["Judge chain (LCEL)<br/>ChatOpenAI → OpenRouter (or ChatOllama for testing)"] --> R R["parse_rating<br/>strip reasoning tags → total_rating regex → clamp 0–20"] --> CSV CSV["results/<run_ts>/results.csv"]
- Candidate chains — one LCEL chain per model; wall-clock duration is recorded per branch and the token rate is extracted from the Ollama response metadata (
eval_count/eval_duration) when present. - Persistence — each raw answer is saved as
answers/<model>.md(colons in model names become dashes, e.g.qwen3.5-2b.md). - Judge chain — assembles the prompt exactly like the manual workflow:
judge_instructions + #start of user_question/right_answer/system_answer blocks + model answer, then parsestotal_rating:N/20(reasoning tags stripped, values > 20 clamped, unparseable →0/20withparsed=false). - Results — one CSV row per model in the 2025 format, plus traceability columns.
Prerequisites
- Ollama installed and the candidate models pulled:
ollama pull qwen3.5:4b ollama pull qwen3.5:2b ollama pull qwen2.5-coder:7b - Python ≥ 3.11
- An OpenRouter API key for the judge:
export OPENROUTER_API_KEY='sk-or-...'
Setup
cd langchain-benchmark
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtUsage
Run with the defaults from config.yaml:
python benchmark.pyOverride quiz, models or judge on the CLI:
python benchmark.py --quiz brute_force --models qwen3.5:2b qwen3.5:4b --judge openai/gpt-oss-120bPoint to another config file:
python benchmark.py --config /path/to/other-config.yamlTest without OpenRouter by judging with a local model — set in config.yaml:
judge:
provider: ollama # openrouter | ollama
model: llama3.2:latestChanging the bug program
Each quiz is a self-contained folder under quizzes/ — no code changes needed:
- Create
quizzes/<my_quiz>/. - Add
question.md(question text incl. the buggy code),right_answer.md(correct explanation + fix) andjudge_instructions.md(the 0–20 rubric, without the#start of ...markers — the script injects those). - Run with
--quiz my_quiz.
Changing the judge
Any OpenRouter model works via --judge <model> or config.yaml (openai/gpt-oss-120b by default, the same model used in RAG_Introduction.ipynb). provider: ollama routes the judge to a local model instead — useful for testing without spending API credits.
Outputs
Each run creates a timestamped folder so previous runs are never clobbered:
results/
└── 20261111-201500/
├── answers/
│ ├── qwen3.5-2b.md # YAML frontmatter (model, quiz, duration, tokens/s) + raw answer
│ └── qwen2.5-coder-7b.md
└── results.csv
results.csv columns (2025 format plus traceability):
| column | meaning |
|---|---|
model | Ollama model name (e.g. qwen3.5:2b) |
total_rating | judge verdict as N/20, or n/a on failure |
total duration | answer wall-clock seconds (e.g. 23.585874811s) |
eval rate | generation speed from Ollama metadata (e.g. 88.12 tokens/s), blank if unavailable |
quiz | quiz folder name |
judge_model | judge used for the rating |
parsed | true/false — was total_rating found in the judge output |
error | empty, or the per-model error (model not pulled, timeout, judge failure) |
A model that fails (e.g. not pulled) produces a graceful n/a row and the run continues.
LangChain concepts used
- LCEL composition (
|) — chains are built by piping runnables:prompt | llm | parser. Each piece is aRunnable; the pipe creates a newRunnablewhose steps run in sequence. ChatPromptTemplate— renders the question / judge prompt into chat messages. The text is passed as an input variable ({"question": ...}), so{braces}inside the quiz code are never mistaken for template variables.StrOutputParser— extracts the plain string content from the model’sAIMessage. A smallRunnableLambdamiddleware sits between the LLM and the parser to capture Ollama’seval_count/eval_durationmetadata before it is discarded.RunnableParallel— fans one input out to many branches (one per model) and merges the results into a dict keyed by branch name. Invoked withmax_concurrency=1because Ollama serves one model at a time.- OpenAI-compatible endpoints —
ChatOpenAIwithbase_url=https://openrouter.ai/api/v1anddefault_headers(HTTP-Referer,X-Title) talks to OpenRouter’s OpenAI-compatible API, exactly like the plainopenaiclient inRAG_Introduction.ipynb— a LangChain chain can swap providers without changing the pipeline shape.
File layout
langchain-benchmark/
├── README.md
├── requirements.txt
├── config.yaml # default run configuration
├── benchmark.py # single entry point
├── quizzes/
│ └── brute_force/
│ ├── question.md # question text incl. buggy code
│ ├── right_answer.md # correct explanation + fix
│ └── judge_instructions.md # 0–20 rubric + output format
└── results/
└── <run timestamp>/
├── answers/<model>.md
└── results.csv
Notes
Judge calls cost money
Every run makes one OpenRouter API call per candidate model;
timeout_s(default 600) applies to the judge request. Useprovider: ollamawhile testing to avoid spending API credits.
- Judge output may start with reasoning/thinking tags; the parser strips them before extracting the rating.
- Out of scope by design: charts (make them manually from the CSV) and multi-quiz batch runs (loop externally with
--quiz).