Table of Contents


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 trials

The 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/&lt;model&gt;.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"]
  1. 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.
  2. Persistence — each raw answer is saved as answers/<model>.md (colons in model names become dashes, e.g. qwen3.5-2b.md).
  3. Judge chain — assembles the prompt exactly like the manual workflow:
    judge_instructions + #start of user_question/right_answer/system_answer blocks + model answer, then parses total_rating:N/20 (reasoning tags stripped, values > 20 clamped, unparseable → 0/20 with parsed=false).
  4. 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.txt

Usage

Run with the defaults from config.yaml:

python benchmark.py

Override quiz, models or judge on the CLI:

python benchmark.py --quiz brute_force --models qwen3.5:2b qwen3.5:4b --judge openai/gpt-oss-120b

Point to another config file:

python benchmark.py --config /path/to/other-config.yaml

Test without OpenRouter by judging with a local model — set in config.yaml:

judge:
  provider: ollama       # openrouter | ollama
  model: llama3.2:latest

Changing the bug program

Each quiz is a self-contained folder under quizzes/ — no code changes needed:

  1. Create quizzes/<my_quiz>/.
  2. Add question.md (question text incl. the buggy code), right_answer.md (correct explanation + fix) and judge_instructions.md (the 0–20 rubric, without the #start of ... markers — the script injects those).
  3. 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):

columnmeaning
modelOllama model name (e.g. qwen3.5:2b)
total_ratingjudge verdict as N/20, or n/a on failure
total durationanswer wall-clock seconds (e.g. 23.585874811s)
eval rategeneration speed from Ollama metadata (e.g. 88.12 tokens/s), blank if unavailable
quizquiz folder name
judge_modeljudge used for the rating
parsedtrue/false — was total_rating found in the judge output
errorempty, 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 a Runnable; the pipe creates a new Runnable whose 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’s AIMessage. A small RunnableLambda middleware sits between the LLM and the parser to capture Ollama’s eval_count/eval_duration metadata 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 with max_concurrency=1 because Ollama serves one model at a time.
  • OpenAI-compatible endpoints — ChatOpenAI with base_url=https://openrouter.ai/api/v1 and default_headers (HTTP-Referer, X-Title) talks to OpenRouter’s OpenAI-compatible API, exactly like the plain openai client in RAG_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. Use provider: ollama while 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).