Contents1What it teaches2How to run it3What changed and whyAlanggraph_router.pyBprompt_evals_inventory.pyCrag_evals_inventory.pyDtool_evals_inventory.pyEannotator + judge_agreement↔Link to the lecture!Known limits✎Exercises★Glossary{}Full source
By Shivank Agarwal · code explainer · 07-agent-evals/code folder (4 eval files + a review screen)

Component evals in code: score an inventory agent's router, prompt, search and tools, then check the judge against a human

One warehouse "reorder advisor", evaluated part by part. Each file builds a small test set with known good answers, runs the agent on it, scores every answer, and prints a report you can read at a glance. A review screen and a short script then check whether the LLM judge agrees with a person.

OpenAI gpt-6-lunatext-embedding-3-smallLangChainLangGraphpandas
1

What the folder teaches

FilePart of the agentHow it's scoredLecture slides
langgraph_router.pyRouter: which specialist answers?Route per question (slide 4 adds an accuracy test)4, 6
prompt_evals_inventory.pySystem prompt, Version 1 vs 2LLM judge: Accuracy, Clarity, Completeness (pass/fail)2, 5, 6, 8
rag_evals_inventory.pySearch + answer (RAG)Recall@k, plus judge: Relevance, Groundedness, Correctness6, 18, 20
tool_evals_inventory.pyTool callingPrecision, recall, calls per task, success, latency, cost6
annotator.htmlHuman review screenYou click 👍 / 👎 and write why9
judge_agreement.pyThe judge itselfCohen's kappa between judge and human13–15
Test setquestions + good answers
→
Run the agent partrouter / prompt / RAG / tools
→
Score each answerrules or LLM judge
→
Report + CSV
→
Human reviewannotator → kappa
Every eval file follows the same four steps; the last step checks the scorer itself.
2

How to run it

  1. Install the packages: pip install -r requirements.txt
  2. Copy .env.example to .env and put your key in it: OPENAI_API_KEY=sk-...
  3. Run any file: python langgraph_router.py, python prompt_evals_inventory.py, python rag_evals_inventory.py, python tool_evals_inventory.py
  4. Open annotator.html in a browser (double-click it; no server needed), upload a results CSV, review, download the feedback, then python judge_agreement.py prompt_eval_results_feedback.csv
requirements.txt (complete file)
openai>=2.0
langchain>=1.0
langchain-openai>=1.0
langgraph>=1.0
numpy>=2.0
pandas>=2.0
python-dotenv>=1.0

Running all four eval files makes about 100 short model calls (plus 16 embedding calls). At gpt-6-luna's list prices ($0.10 per million input tokens, $0.50 per million output tokens) that's well under 5 cents in total.

3

What changed from the original, and why

Same tests, same data, same teaching order. Here's everything that's different.

#OriginalNowWhy
1Groq: llama-3.1-8b-instant and llama-3.3-70b-versatile, temperature=0 / 0.3OpenAI gpt-6-luna with reasoning_effort="none" everywhereOne provider, one key. "none" makes the model answer straight away.
2HuggingFace all-MiniLM-L6-v2; all 12 passages re-embedded for every questiontext-embedding-3-small; the 12 passages are embedded once, in one callNo large local download. The original repeated the same 12 passage embeddings on every search (180 wasted across the 15 runs); now it is one batch at the start plus one per question.
3Judge replies parsed with a regex (Accuracy: X); anything unreadable silently scored 0JSON mode, plus a one-line Reason from the judgeA formatting slip no longer looks like a failed answer. The reason is what you read during error analysis, and it's saved to the CSV.
4LangChain 0.2 AgentExecutor + create_tool_calling_agent, verbose=TrueLangChain 1.x create_agent; tool calls read from the message history; one clean trace per scenarioThe old classes aren't in current LangChain. The verbose chain log buried the results.
5Token counts read from result.llm_outputReal counts from each reply's usage_metadataA real bug. The result is a dictionary, so that check was always false: tokens were always 0 and the LLM cost was always $0.
6Made-up prices ($0.0005 / $0.001 per 1K tokens, $0.001 per tool call)gpt-6-luna list prices; local tools cost $0 (one setting to change)Cost numbers you can trust and update.
7execution_time_ms stored the whole task's time on every tool callOne latency per task, reported as Avg LatencyThe old number looked like tool latency but wasn't. Latency is the lecture's "System" metric.
8Attribution: "do any of the tool output's first 5 words appear in the answer?""Does the tool's main number appear in the answer?"Words like "=" or "units" appear in almost any answer, so the old check passed nearly everything.
9RAG: docs_needed counts only (with the doc numbers in comments)relevant_docs lists, and a new Recall@k columnA retrieval metric that needs no model, and it explains why k=1 does badly.
10RAG file read GROQ_API_KEY without load_dotenv()load_dotenv() in every fileThe original RAG file never read the .env file, so the key was often "missing".
11Plain {'Accuracy': 1, ...} dictionaries printed per question✅/❌ tables with the judge's reason, text bar charts, and a CSV of every answerReadable at a glance in class, and the CSV feeds the review screen.
12No human-review stepNew annotator.html and judge_agreement.pyThe lecture's slide 9 task and slides 13–15, built and connected to the eval files.
13Router ran its demo on importif __name__ == "__main__":The router can be imported and tested on its own (lecture slide 4).
14pyproject.toml with Groq, sentence-transformers, pinned LangChain 0.2, pdbpprequirements.txt, .env.example, README.mdFewer, lighter, current packages.
The agent's parts

Four components, four evals

A

langgraph_router.py: send each question to the right specialist

One model call decides the category; a second call, with a specialist's system prompt, writes the answer.

__start__ router reorder forecast supplier __end__
Dashed arrows = conditional edges (only one is taken). Drawn from the graph LangGraph itself reports, shown at the end of this section.

1. The router: the model must pick exactly one of three labels

langgraph_router.py · lines 31–32
class Route(BaseModel):
    category: Literal["reorder", "forecast", "supplier"]
langgraph_router.py · lines 35–35
router_llm = llm.with_structured_output(Route)       # the reply is parsed into a Route object
langgraph_router.py · lines 44–52
def router(state):
    decision = router_llm.invoke([
        SystemMessage(content="Route the inventory query to one of: reorder, forecast, or supplier.\n"
                              "- reorder: reorder point, EOQ, safety stock, when to order\n"
                              "- forecast: demand prediction, adjusting forecasts\n"
                              "- supplier: comparing suppliers, lead times, vendor costs"),
        HumanMessage(content=state["query"]),
    ])
    return {"category": decision.category}

with_structured_output(Route) makes the reply a Route object whose category can only be "reorder", "forecast" or "supplier". No text parsing, and no chance of a fourth made-up label.

2. Three specialists: same model, different instructions

langgraph_router.py · lines 25–27
def ask(system, user):
    """One model call with a system prompt; returns the reply as plain text."""
    return llm.invoke([SystemMessage(content=system), HumanMessage(content=user)]).text
langgraph_router.py · lines 56–59
def reorder_node(state):
    answer = ask("You are an inventory reorder specialist. Answer concisely using inventory "
                 "principles like ROP, EOQ, and safety stock.", state["query"])
    return {"response": answer}

The forecast and supplier nodes are identical except for the system prompt. A "specialist" here is just a focused instruction.

3. Wiring the graph

langgraph_router.py · lines 77–92
# ---------- 3. Wire the graph ----------
graph = StateGraph(State)
graph.add_node("router", router)
graph.add_node("reorder", reorder_node)
graph.add_node("forecast", forecast_node)
graph.add_node("supplier", supplier_node)

graph.set_entry_point("router")
graph.add_conditional_edges("router", route_edge,
                            {"reorder": "reorder", "forecast": "forecast", "supplier": "supplier"})
graph.add_edge("reorder", END)
graph.add_edge("forecast", END)
graph.add_edge("supplier", END)

app = graph.compile()

add_conditional_edges reads the label with route_edge and follows the matching arrow. Every specialist then goes to END.

4. Run it

langgraph_router.py · lines 100–107
if __name__ == "__main__":
    for i, q in enumerate(queries, start=1):
        result = app.invoke({"query": q, "category": "", "response": ""})
        print(f"\n[{i}] {q}")
        print(f"    route  → {result['category']}")
        answer = result["response"].strip().replace("\n", "\n" + " " * 13)   # keep long answers indented
        print(f"    answer → {answer}")
        print("-" * 70)
Example output (what you would see; exact text and numbers vary)
[1] We have 300 units on hand and sell 30 a day with a 5-day lead time. Should we reorder?
    route  → reorder
    answer → Not yet. Reorder point (ROP) = 30 units/day × 5 days = 150 units, plus any safety stock. With 300 on hand you have about 10 days of stock, so you'll reach the ROP in roughly 5 days.
             Place the order when stock falls to 150 units (or 150 + your safety stock), not today.
----------------------------------------------------------------------

[2] Demand spiked 60% last week. How should I adjust my forecast?
    route  → forecast
    answer → Don't move the forecast up by the full 60% yet. First check the cause: a promotion, a festival, a one-off bulk order?
             Then use a rolling average (e.g. the last 4–8 weeks), which lifts the forecast only partly.
             If demand stays high for 2–3 more weeks, treat it as a trend and update the baseline.
----------------------------------------------------------------------

[3] Supplier A is cheaper but takes 30 days. Supplier B costs more but delivers in 5 days. Which is better?
    route  → supplier
    answer → Compare total cost, not unit price. Supplier A's 30-day lead time needs much more safety stock (roughly √(30/5) ≈ 2.4× as much), which adds holding cost and stockout risk.
             For fast-moving or volatile items, Supplier B usually wins; for stable, cheap-to-store items, A can still be cheaper.
             Also check each supplier's on-time delivery record.
----------------------------------------------------------------------
The graph, as LangGraph describes it (real output of app.get_graph().draw_mermaid())
---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	router(router)
	reorder(reorder)
	forecast(forecast)
	supplier(supplier)
	__end__([<p>__end__</p>]):::last
	__start__ --> router;
	router -.-> forecast;
	router -.-> reorder;
	router -.-> supplier;
	forecast --> __end__;
	reorder --> __end__;
	supplier --> __end__;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc

Paste that text into mermaid.live to see the same picture as the diagram above.

⚠️ This file shows the router; it doesn't score it

Three questions, three correct routes, proves little. The slide explainer's slide 4 adds s04_router_eval.py: 9 labelled questions, a routing accuracy and a confusion table. That's the router's eval.

B

prompt_evals_inventory.py: is prompt Version 2 really better?

Nine tricky warehouse questions, two system prompts, and an LLM judge that marks every answer pass or fail on three criteria.

1. The golden dataset: questions with hidden traps

prompt_evals_inventory.py · lines 66–70
dataset = [
    {
        "q": "Our safety stock formula says reorder at 200 units. We have 210 units on hand and a PO arriving tomorrow. Should we reorder now?",
        "a": "No. On-hand (210) is above reorder point (200) AND incoming stock will arrive tomorrow. Reordering now creates overstock. Must account for in-transit inventory in the reorder calculation.",
    },

Each question hides a wrong assumption (here: ignoring stock that arrives tomorrow). The "a" field lists the key points a correct answer must make. That's the answer key, which makes this a reference-based eval.

2. The two prompts being compared

prompt_evals_inventory.py · lines 105–116
prompts = {
    "Version 1": "You are an inventory management advisor. Answer the question.",
    "Version 2": """You are an inventory management advisor for warehouse operations teams.

    When answering questions:
    1. State the core inventory principle or formula first (e.g., EOQ, ROP, safety stock)
    2. Explain BOTH the textbook/ideal case AND the real-world complication if they differ
    3. Explicitly correct any common misconception embedded in the question
    4. Use concrete numbers from the question to illustrate your answer

    Always address the specific edge case or nuance — managers ask these questions because they have a hidden assumption that may be wrong.""",
}

3. The agent under test, and the judge

prompt_evals_inventory.py · lines 53–63
def inventory_advisor(system_prompt, question):
    """The agent under test: answers an inventory question using the given system prompt."""
    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": question},
        ],
    )
    return response.choices[0].message.content
prompt_evals_inventory.py · lines 25–50
def evaluate_response(question, expected_answer, actual_response):
    """LLM-as-judge: strict binary scores (0 = Fail, 1 = Pass) plus a one-line reason."""
    eval_prompt = f"""Evaluate this inventory reorder advisor response with STRICT binary scoring (0=Fail, 1=Pass).

    Question: {question}
    Expected Key Points: {expected_answer}
    Actual Response: {actual_response}

    Be STRICT. Only give 1 if the criterion is fully met:
    - Accuracy: Is the reorder recommendation correct with NO errors or misleading statements? (0 or 1)
    - Clarity: Would a warehouse manager act on this WITHOUT further questions? (0 or 1)
    - Completeness: Does it address the SPECIFIC edge case or nuance in the question? (0 or 1)

    Respond ONLY with JSON in this exact shape:
    {{"Accuracy": 0 or 1, "Clarity": 0 or 1, "Completeness": 0 or 1, "Reason": "one short sentence"}}"""

    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        response_format={"type": "json_object"},     # JSON mode: the reply is always valid JSON
        messages=[{"role": "user", "content": eval_prompt}],
    )
    verdict = json.loads(response.choices[0].message.content)
    scores = {m: 1 if verdict.get(m) in (1, "1", True) else 0 for m in METRICS}
    scores["Reason"] = str(verdict.get("Reason", ""))
    return scores

💡 How the judge works

  • It gets the question, the key points and the actual answer, and three strict yes/no questions. Yes/no is easier to apply consistently than a 1–10 score.
  • response_format={"type": "json_object"} forces valid JSON, so json.loads never fails.
  • The Reason is one sentence explaining the verdict. Without it you'd know that an answer failed, but not why.

4. Run everything and print the report

prompt_evals_inventory.py · lines 128–174
if __name__ == "__main__":
    # ---------- Step 1: look at one question side by side ----------
    q1 = dataset[0]["q"]
    print(f"\nQUESTION 1:\n{q1}\n")
    print("=" * 70)
    for prompt_name in prompts:
        print(f"\n{prompt_name} ANSWER:")
        print("-" * 30)
        print(inventory_advisor(prompts[prompt_name], q1))

    # ---------- Step 2: run every question through both prompts and judge each answer ----------
    results = {name: {m: [] for m in METRICS} for name in prompts}
    rows = []
    for prompt_name, prompt in prompts.items():
        print(f"\n{'=' * 70}\nEvaluating: {prompt_name}\n{'=' * 70}")
        print(f"  {'#':<4}{'Acc':^6}{'Clar':^6}{'Comp':^6}  Judge's reason")
        for i, item in enumerate(dataset, start=1):
            response = inventory_advisor(prompt, item["q"])
            scores = evaluate_response(item["q"], item["a"], response)
            for m in METRICS:
                results[prompt_name][m].append(scores[m])
            print(f"  Q{i:<3}{mark(scores['Accuracy']):^5}{mark(scores['Clarity']):^5}"
                  f"{mark(scores['Completeness']):^5}  {scores['Reason']}")
            rows.append({"prompt_version": prompt_name, "question": item["q"], "expected": item["a"],
                         "response": response, **{m.lower(): scores[m] for m in METRICS},
                         "judge_reason": scores["Reason"]})

    # ---------- Step 3: pass rates ----------
    print("\n" + "=" * 70)
    print("PASS RATES BY PROMPT VERSION")
    print("=" * 70)
    for prompt_name in prompts:
        print(f"\n{prompt_name.upper()}:")
        total_pass = total_tests = 0
        for m in METRICS:
            passed, total = sum(results[prompt_name][m]), len(results[prompt_name][m])
            total_pass, total_tests = total_pass + passed, total_tests + total
            print(f"  {m:<13} {bar(passed, total)} {passed}/{total} ({100 * passed / total:.0f}%)")
        print(f"  {'Overall':<13} {bar(total_pass, total_tests)} {total_pass}/{total_tests} "
              f"({100 * total_pass / total_tests:.0f}%)")

    # ---------- Step 4: save every answer for human review (the annotator reads this file) ----------
    with open(RESULTS_CSV, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"\nSaved {len(rows)} judged answers to {RESULTS_CSV}")
Example output (what you would see; exact text and numbers vary)
QUESTION 1:
Our safety stock formula says reorder at 200 units. We have 210 units on hand and a PO arriving tomorrow. Should we reorder now?

======================================================================

Version 1 ANSWER:
------------------------------
No, you don't need to reorder yet. Your on-hand stock (210 units) is still above the reorder point of 200 units, so wait until inventory drops to 200 or below before placing a new order.

Version 2 ANSWER:
------------------------------
Principle: reorder when your inventory position (on-hand + on-order) falls to the reorder point.

Textbook check: 210 on hand > 200 ROP, so no order is due.

Real-world complication: the PO arriving tomorrow adds to your position, which puts you even further above 200. Reordering now would double-order and create overstock.

Misconception: comparing only on-hand stock with the ROP ignores in-transit inventory.

Action: don't reorder. Re-check after tomorrow's delivery is received.

======================================================================
Evaluating: Version 1
======================================================================
  #    Acc   Clar  Comp   Judge's reason
  Q1    ✅    ✅    ❌    Correct, but ignores the PO arriving tomorrow (in-transit stock).
  Q2    ✅    ❌    ❌    Too vague to act on; no rolling-average guidance.
  Q3    ✅    ✅    ✅    Correct direction, explained with the EOQ formula.
  Q4    ❌    ✅    ❌    Wrongly confirms a reorder point without safety stock.
  Q5    ❌    ✅    ❌    Misses the shelf-life risk and FEFO.
  Q6    ❌    ✅    ❌    Ignores that a cheap C item can be critical.
  Q7    ✅    ✅    ✅    Mentions total cost including holding cost.
  Q8    ✅    ❌    ✅    Right idea, but doesn't say how to set safety stock.
  Q9    ✅    ✅    ✅    Correct reorder point and no safety stock.

======================================================================
Evaluating: Version 2
======================================================================
  #    Acc   Clar  Comp   Judge's reason
  Q1    ✅    ✅    ✅    Accounts for in-transit stock and gives a clear action.
  Q2    ✅    ✅    ✅    Recommends a rolling 4–8 week average before changing the ROP.
  Q3    ✅    ✅    ✅    Correct formula, numbers and action.
  Q4    ✅    ✅    ✅    Adds safety stock with a worked example.
  Q5    ✅    ❌    ✅    Correct, but the action is buried in a long answer.
  Q6    ✅    ✅    ✅    Separates value from criticality.
  Q7    ✅    ✅    ✅    Explains total cost and the lead-time effect.
  Q8    ✅    ✅    ✅    Explains service level and the cost trade-off.
  Q9    ✅    ✅    ✅    Correct, and flags the real-world check.

======================================================================
PASS RATES BY PROMPT VERSION
======================================================================

VERSION 1:
  Accuracy      █████████████░░░░░░░ 6/9 (67%)
  Clarity       ████████████████░░░░ 7/9 (78%)
  Completeness  █████████░░░░░░░░░░░ 4/9 (44%)
  Overall       █████████████░░░░░░░ 17/27 (63%)

VERSION 2:
  Accuracy      ████████████████████ 9/9 (100%)
  Clarity       ██████████████████░░ 8/9 (89%)
  Completeness  ████████████████████ 9/9 (100%)
  Overall       ███████████████████░ 26/27 (96%)

Saved 18 judged answers to /home/learner/07-agent-evals/code/prompt_eval_results.csv

💡 What to point out

  • The biggest jump is Completeness (44% → 100%): Version 2 explicitly asks the model to "correct any misconception embedded in the question", and that's exactly what the trick questions test.
  • Version 1 isn't wrong most of the time (67% accuracy); it's shallow. Without an eval you'd probably never notice.
  • Version 2's one miss is Clarity on the perishable question: a correct but long answer. Better prompts can bring new problems, which is why you rerun every metric.
C

rag_evals_inventory.py: which search setup answers best?

Twelve policy passages, three RAG configurations, and two kinds of score: did we fetch the right passages, and is the answer right and grounded?

1. The knowledge base: some passages only make sense together

rag_evals_inventory.py · lines 70–80
documents = [
    # Doc 0: Reorder point basics
    "A reorder point (ROP) is the inventory level that triggers a new purchase order. "
    "It is calculated as: ROP = average daily demand × lead time in days.",

    # Doc 1: Safety stock (needs Doc 0 for full picture)
    "Safety stock is extra inventory held to guard against demand spikes and lead-time variability. "
    "The full reorder point formula is: ROP = (average demand × lead time) + safety stock. "
    "Without safety stock the formula only works when demand and lead time are perfectly constant.",

    # Doc 2: EOQ definition

Passage 0 gives the basic reorder formula; passage 1 adds safety stock. A question about "the reorder point formula" needs both, so fetching just one passage gives an incomplete answer. The dataset is built around pairs like this.

2. Search: embed once, compare by meaning

rag_evals_inventory.py · lines 132–134
def embed(texts):
    response = client.embeddings.create(model=EMBED_MODEL, input=texts)
    return np.array([item.embedding for item in response.data])
rag_evals_inventory.py · lines 137–137
doc_embeddings = embed(documents)                    # shape: (12, 1536)
rag_evals_inventory.py · lines 140–144
def retrieve(query, k=2):
    """Return the numbers of the k passages closest in meaning to the query."""
    q = embed([query])[0]
    sims = doc_embeddings @ q / (np.linalg.norm(doc_embeddings, axis=1) * np.linalg.norm(q))
    return [int(i) for i in np.argsort(sims)[::-1][:k]]      # highest cosine similarity first

Each passage becomes a list of 1,536 numbers that captures its meaning. For a question, we embed it the same way and pick the k passages with the highest cosine similarity (closest in meaning). doc_embeddings @ q scores all 12 passages in one line.

3. The RAG agent and the three configurations

rag_evals_inventory.py · lines 171–181
def rag_agent(question, k=2, prompt_template=PROMPT_MINIMAL):
    """RAG agent: retrieve k passages, then answer from them."""
    doc_ids = retrieve(question, k=k)
    context = "\n---\n".join(documents[i] for i in doc_ids)
    prompt = prompt_template.format(context=context, question=question)
    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        messages=[{"role": "user", "content": prompt}],
    )
    return {"doc_ids": doc_ids, "context": context, "answer": response.choices[0].message.content}
rag_evals_inventory.py · lines 237–241
rag_configs = {
    "Config A: k=1, minimal":    {"k": 1, "prompt": PROMPT_MINIMAL},
    "Config B: k=2, structured": {"k": 2, "prompt": PROMPT_STRUCTURED},
    "Config C: k=3, grounded":   {"k": 3, "prompt": PROMPT_GROUNDED},
}

Config A fetches 1 passage with a bare prompt; B fetches 2 with a "use the context" prompt; C fetches 3 with a strict "answer ONLY from the context, say what's missing" prompt (the three prompt templates are in the full source).

4. Two kinds of score

rag_evals_inventory.py · lines 184–189
eval_dataset = [
    {
        "question": "What is the reorder point formula and when should safety stock be included?",
        "reference": "ROP = average demand × lead time. Safety stock must be added when demand or lead time vary: ROP = (avg demand × lead time) + safety stock.",
        "relevant_docs": [0, 1],
    },
rag_evals_inventory.py · lines 244–246
def recall_at_k(retrieved, relevant):
    """Share of the needed passages that were actually retrieved (1.0 = all of them)."""
    return len(set(retrieved) & set(relevant)) / len(relevant)

Recall@k needs no model: we know which passages each question needs (relevant_docs), so we just check how many were fetched. The LLM judge then scores three things: was the context enough (Relevance), does every claim come from the context (Groundedness), and does the answer match the reference (Correctness).

5. Run it

rag_evals_inventory.py · lines 253–304
if __name__ == "__main__":
    print(f"Corpus: {len(documents)} passages, embedded with {EMBED_MODEL}")
    print(f"Evaluation dataset: {len(eval_dataset)} questions (running the first {NUM_QUESTIONS})")
    print("RAG configurations:")
    for name, cfg in rag_configs.items():
        print(f"  {name} (retrieves {cfg['k']} passage(s))")

    test_data = eval_dataset[:NUM_QUESTIONS]
    results = {name: {m: [] for m in METRICS + ["Recall@k"]} for name in rag_configs}
    rows = []

    for config_name, config in rag_configs.items():
        print(f"\n{'=' * 78}\nEvaluating: {config_name}\n{'=' * 78}")
        print(f"  {'#':<4}{'needed':<9}{'retrieved':<12}{'Recall':>7}  {'Rel':^5}{'Grd':^5}{'Cor':^5}  Judge's reason")
        for i, item in enumerate(test_data, start=1):
            out = rag_agent(item["question"], k=config["k"], prompt_template=config["prompt"])
            recall = recall_at_k(out["doc_ids"], item["relevant_docs"])
            scores = evaluate_rag_response(item["question"], out["context"], out["answer"], item["reference"])
            for m in METRICS:
                results[config_name][m].append(scores[m])
            results[config_name]["Recall@k"].append(recall)
            print(f"  Q{i:<3}{str(item['relevant_docs']):<9}{str(out['doc_ids']):<12}{recall:>7.0%}  "
                  f"{mark(scores['Context Relevance']):^4}{mark(scores['Answer Groundedness']):^4}"
                  f"{mark(scores['Answer Correctness']):^4}  {scores['Reason']}")
            rows.append({"config": config_name, "question": item["question"], "reference": item["reference"],
                         "relevant_docs": item["relevant_docs"], "retrieved_docs": out["doc_ids"],
                         "recall_at_k": round(recall, 2), "response": out["answer"],
                         **{m.lower().replace(" ", "_"): scores[m] for m in METRICS},
                         "judge_reason": scores["Reason"]})

    print("\n" + "=" * 78)
    print(f"RAG EVALUATION RESULTS ({NUM_QUESTIONS} questions per configuration)")
    print("=" * 78)
    print(f"{'Configuration':<28}{'Recall@k':>10}{'Relevant':>10}{'Grounded':>10}{'Correct':>10}{'Overall':>10}")
    print("-" * 78)
    best_config, best_score = None, -1
    for config_name in rag_configs:
        r = results[config_name]
        avg = {m: sum(v) / len(v) for m, v in r.items()}
        overall = (avg["Context Relevance"] + avg["Answer Groundedness"] + avg["Answer Correctness"]) / 3
        print(f"{config_name:<28}{avg['Recall@k']:>10.0%}{avg['Context Relevance']:>10.0%}"
              f"{avg['Answer Groundedness']:>10.0%}{avg['Answer Correctness']:>10.0%}{overall:>10.0%}")
        if overall > best_score:
            best_score, best_config = overall, config_name
    print("-" * 78)
    print(f"Best: {best_config} ({best_score:.0%})")

    with open(RESULTS_CSV, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"\nSaved {len(rows)} judged answers to {RESULTS_CSV}")
Example output (what you would see; exact text and numbers vary)
Corpus: 12 passages, embedded with text-embedding-3-small
Evaluation dataset: 10 questions (running the first 5)
RAG configurations:
  Config A: k=1, minimal (retrieves 1 passage(s))
  Config B: k=2, structured (retrieves 2 passage(s))
  Config C: k=3, grounded (retrieves 3 passage(s))

==============================================================================
Evaluating: Config A: k=1, minimal
==============================================================================
  #   needed   retrieved    Recall   Rel  Grd  Cor   Judge's reason
  Q1  [0, 1]   [1]             50%   ✅   ✅   ✅    Passage 1 alone has both versions of the formula.
  Q2  [2, 3]   [3]             50%   ❌   ❌   ✅    Context lacks the EOQ formula; the answer adds it from memory.
  Q3  [4, 5]   [5]             50%   ❌   ✅   ❌    Context misses the ABC basics, so the answer is incomplete.
  Q4  [6, 1]   [6]             50%   ✅   ❌   ✅    Answer adds 'negotiate a shorter lead time', which isn't in the context.
  Q5  [7, 1]   [7]             50%   ✅   ✅   ❌    Answer drops the safety stock formula from the reference.

==============================================================================
Evaluating: Config B: k=2, structured
==============================================================================
  #   needed   retrieved    Recall   Rel  Grd  Cor   Judge's reason
  Q1  [0, 1]   [1, 0]         100%   ✅   ✅   ✅    Both formulas retrieved and used correctly.
  Q2  [2, 3]   [3, 2]         100%   ✅   ✅   ✅    Formula and sensitivity both in context and answer.
  Q3  [4, 5]   [5, 4]         100%   ✅   ✅   ✅    Explains value vs criticality from the context.
  Q4  [6, 1]   [6, 7]          50%   ✅   ❌   ✅    Answer adds a payment-terms point not in the context.
  Q5  [7, 1]   [7, 1]         100%   ✅   ✅   ✅    Service level and formula both covered.

==============================================================================
Evaluating: Config C: k=3, grounded
==============================================================================
  #   needed   retrieved    Recall   Rel  Grd  Cor   Judge's reason
  Q1  [0, 1]   [1, 0, 11]     100%   ✅   ✅   ✅    Complete and fully grounded.
  Q2  [2, 3]   [3, 2, 7]      100%   ✅   ✅   ✅    Complete and fully grounded.
  Q3  [4, 5]   [5, 4, 8]      100%   ✅   ✅   ✅    Complete; uses both ABC passages.
  Q4  [6, 1]   [6, 7, 1]      100%   ✅   ✅   ✅    Total cost explained only from the context.
  Q5  [7, 1]   [7, 1, 11]     100%   ✅   ✅   ✅    Complete and fully grounded.

==============================================================================
RAG EVALUATION RESULTS (5 questions per configuration)
==============================================================================
Configuration                 Recall@k  Relevant  Grounded   Correct   Overall
------------------------------------------------------------------------------
Config A: k=1, minimal             50%       60%       60%       60%       60%
Config B: k=2, structured          90%      100%       80%      100%       93%
Config C: k=3, grounded           100%      100%      100%      100%      100%
------------------------------------------------------------------------------
Best: Config C: k=3, grounded (100%)

Saved 15 judged answers to /home/learner/07-agent-evals/code/rag_eval_results.csv

💡 What to point out

  • With k=1, Recall@k can never be above 50% for a question that needs two passages. The ceiling is set by the configuration, before the model writes a word.
  • Config B fetched both passages more often, yet one answer added "payment terms" that weren't in the context: a groundedness failure. Config C's prompt ("ONLY the provided context") fixed that.
  • Each component gets its own metric: Recall@k for search, the judge for the answer. If the overall score drops, you'll know which part to fix.
D

tool_evals_inventory.py: right calculator, right number of times, at what cost?

Six inventory calculators, a tool-calling agent, and 12 scenarios where we know which tools should be called, including some where the right answer is "no tool at all".

1. The tools

tool_evals_inventory.py · lines 36–40
@tool
def reorder_point_calculator(avg_daily_demand: float, lead_time_days: float, safety_stock: float = 0) -> str:
    """Calculate reorder point: ROP = (avg_daily_demand * lead_time_days) + safety_stock."""
    rop = avg_daily_demand * lead_time_days + safety_stock
    return f"Reorder Point = {rop:.1f} units (demand {avg_daily_demand}/day × {lead_time_days} days lead time + {safety_stock} safety stock)"
tool_evals_inventory.py · lines 43–49
@tool
def eoq_calculator(annual_demand: float, ordering_cost: float, holding_cost_per_unit: float) -> str:
    """Calculate Economic Order Quantity: EOQ = sqrt(2 * D * S / H)."""
    if holding_cost_per_unit <= 0:
        return "Error: holding cost must be > 0"
    eoq = math.sqrt(2 * annual_demand * ordering_cost / holding_cost_per_unit)
    return f"EOQ = {eoq:.1f} units (D={annual_demand}, S=${ordering_cost}, H=${holding_cost_per_unit})"

Each tool is a normal Python function with @tool. The docstring is the description the model reads, and the type hints become the input schema. The other four tools follow the same pattern.

2. The agent under test

tool_evals_inventory.py · lines 95–102
agent = create_agent(
    llm,
    tools,
    system_prompt="""You are an inventory management assistant with access to calculation tools.
Use the appropriate tool(s) to answer inventory questions precisely.
Always use tools when they are relevant to the question.
Be precise in selecting the right tool for each task.""",
)

create_agent builds the standard loop: the model asks for tools, LangChain runs them and sends the results back, until the model answers.

3. The test scenarios: four kinds

tool_evals_inventory.py · lines 108–113
test_scenarios = [
    # Single-tool
    {"question": "Calculate the reorder point for an item with 50 units/day demand, 7-day lead time, and 100 units safety stock.",
     "expected_tools": ["reorder_point_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "What is the EOQ for annual demand of 10000 units, ordering cost $50, holding cost $2 per unit?",
     "expected_tools": ["eoq_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
KindCountWhat it tests
single_tool6Picks the one right tool with the right numbers
multi_tool2Calls both tools a two-part question needs
ambiguous2The tool isn't named ("take the square root", "right now")
no_tool2Doesn't call a calculator for a definition question

4. Reading what happened from the agent's messages

tool_evals_inventory.py · lines 196–234
def run_evaluation(scenario: dict) -> TaskEvaluation:
    expected = scenario["expected_tools"]
    alternatives = scenario.get("acceptable_alternatives", [])
    actual_tools, tool_logs = [], []
    output, error = None, None
    input_tokens = output_tokens = 0
    t0 = time.time()
    try:
        result = agent.invoke({"messages": [{"role": "user", "content": scenario["question"]}]})
        messages = result["messages"]
        requested = {}                                           # tool_call_id -> the model's request
        for m in messages:
            if isinstance(m, AIMessage):
                for tc in m.tool_calls:
                    requested[tc["id"]] = tc
                if m.usage_metadata:                             # real token counts from OpenAI
                    input_tokens += m.usage_metadata["input_tokens"]
                    output_tokens += m.usage_metadata["output_tokens"]
            elif isinstance(m, ToolMessage):                     # one per tool that actually ran
                tc = requested.get(m.tool_call_id, {"name": m.name, "args": {}})
                actual_tools.append(tc["name"])
                text = str(m.content)
                tool_logs.append(ToolCallLog(
                    tool_name=tc["name"], parameters=tc["args"], output=text,
                    success=m.status != "error" and "error" not in text.lower(),
                    is_correct=is_correct_tool(tc["name"], expected, alternatives),
                ))
        output = messages[-1].text
    except Exception as e:
        error = str(e)

    return TaskEvaluation(
        question=scenario["question"], category=scenario["category"],
        expected_tools=expected, actual_tools=actual_tools, tool_call_logs=tool_logs,
        output=output, error=error,
        requires_external_data=scenario["requires_external_data"],
        optimal_tool_count=scenario["optimal_tool_count"], acceptable_alternatives=alternatives,
        input_tokens=input_tokens, output_tokens=output_tokens, latency_s=time.time() - t0,
    )

💡 Read it in this order

  1. Run the agent once and time it.
  2. Every AIMessage holds the model's tool requests and its real token counts.
  3. Every ToolMessage is a tool that actually ran: we record its name, arguments, output, whether it errored, and whether it was one of the expected tools.
  4. The last message is the final answer.

5. The metrics

tool_evals_inventory.py · lines 240–251
def compute_precision(results: List[TaskEvaluation]) -> Dict:
    """Precision = correct tool calls / all tool calls made."""
    total_calls = sum(len(r.actual_tools) for r in results)
    correct_calls = sum(log.is_correct for r in results for log in r.tool_call_logs)
    per_task = []
    for r in results:
        if r.actual_tools:
            per_task.append(sum(log.is_correct for log in r.tool_call_logs) / len(r.actual_tools))
        else:
            per_task.append(1.0 if not r.expected_tools else 0.0)
    return {"overall_precision": correct_calls / total_calls if total_calls else 1.0,
            "avg_task_precision": sum(per_task) / len(per_task)}
tool_evals_inventory.py · lines 254–267
def compute_recall(results: List[TaskEvaluation]) -> Dict:
    """Recall = expected tools that were called / all expected tools."""
    total_expected = sum(len(r.expected_tools) for r in results)
    per_task, recalled_total = [], 0
    for r in results:
        if r.expected_tools:
            recalled = min(sum(1 for t in r.actual_tools if is_correct_tool(t, r.expected_tools, r.acceptable_alternatives)),
                           len(r.expected_tools))
            recalled_total += recalled
            per_task.append(recalled / len(r.expected_tools))
        else:
            per_task.append(1.0 if not r.actual_tools else 0.0)
    return {"overall_recall": recalled_total / total_expected if total_expected else 1.0,
            "avg_task_recall": sum(per_task) / len(per_task)}
tool_evals_inventory.py · lines 293–305
def compute_attribution(results: List[TaskEvaluation]) -> Dict:
    """Did the final answer actually USE a tool's result? Check the tool's main number appears in it."""
    tool_required = [r for r in results if r.requires_external_data]
    attributed = 0
    for r in tool_required:
        answer_numbers = numbers_in(r.output or "")
        for log in r.tool_call_logs:
            tool_numbers = numbers_in(log.output)
            if tool_numbers and any(abs(tool_numbers[0] - a) < 0.05 for a in answer_numbers):
                attributed += 1
                break
    n = len(tool_required)
    return {"attribution_rate": attributed / n if n else 0.0}

💡 Each metric in plain words

MetricQuestion it answers
PrecisionOf the tool calls made, how many were right? (Low = calls the wrong tools.)
RecallOf the tools that should have been called, how many were? (Low = skips needed tools.)
Calls per task, optimal / over / underDid it call the right number of tools?
Tool success rateDid the tools run without errors?
AttributionDid the final answer actually use the tool's result?
Avg latency, cost per successHow slow and how expensive is each task? (Lecture slide 6, "System" row.)

6. Run it

tool_evals_inventory.py · lines 319–345
if __name__ == "__main__":
    print(f"Tools: {[t.name for t in tools]}")
    print(f"Running {len(test_scenarios)} scenarios...\n")

    evaluation_results: List[TaskEvaluation] = []
    for i, scenario in enumerate(test_scenarios, 1):
        r = run_evaluation(scenario)
        evaluation_results.append(r)
        print(f"[{i:>2}/{len(test_scenarios)}] [{r.category}] {r.question}")
        for log in r.tool_call_logs:
            args = ", ".join(f"{k}={v}" for k, v in log.parameters.items())
            print(f"        → {log.tool_name}({args})\n          = {log.output}")
        if not r.tool_call_logs:
            print("        → (no tool call)")
        answer = (r.output or "").replace("\n", " ")
        print(f"        answer: {answer[:110]}{'...' if len(answer) > 110 else ''}")
        match = "✅" if sorted(r.actual_tools) == sorted(r.expected_tools) else "❌"
        status = "" if r.task_success else f"   ERROR: {r.error}"
        print(f"        expected {r.expected_tools or 'no tool'} {match}  {r.latency_s:.1f}s{status}\n")

    precision = compute_precision(evaluation_results)
    recall = compute_recall(evaluation_results)
    calls = compute_avg_tool_calls(evaluation_results)
    success = compute_tool_success_rate(evaluation_results)
    attribution = compute_attribution(evaluation_results)
    cost = compute_cost(evaluation_results)
    avg_latency = sum(r.latency_s for r in evaluation_results) / len(evaluation_results)
Example output (what you would see; exact text and numbers vary)
Tools: ['reorder_point_calculator', 'eoq_calculator', 'safety_stock_calculator', 'days_of_supply_calculator', 'abc_classifier', 'inventory_date_info']
Running 12 scenarios...

[ 1/12] [single_tool] Calculate the reorder point for an item with 50 units/day demand, 7-day lead time, and 100 units safety stock.
        → reorder_point_calculator(avg_daily_demand=50, lead_time_days=7, safety_stock=100)
          = Reorder Point = 450.0 units (demand 50.0/day × 7.0 days lead time + 100.0 safety stock)
        answer: The reorder point is **450 units**: 50 units/day × 7 days of lead time = 350 units, plus 100 units of safety s...
        expected ['reorder_point_calculator'] ✅  1.5s

[ 2/12] [single_tool] What is the EOQ for annual demand of 10000 units, ordering cost $50, holding cost $2 per unit?
        → eoq_calculator(annual_demand=10000, ordering_cost=50, holding_cost_per_unit=2)
          = EOQ = 707.1 units (D=10000.0, S=$50.0, H=$2.0)
        answer: The Economic Order Quantity is about **707 units** per order (√(2 × 10,000 × $50 ÷ $2) ≈ 707.1). Ordering this...
        expected ['eoq_calculator'] ✅  1.4s

[ 3/12] [single_tool] Calculate safety stock using Z=1.65, demand std dev of 20 units, and 5-day lead time.
        → safety_stock_calculator(z_score=1.65, demand_std_dev=20, lead_time_days=5)
          = Safety Stock = 73.8 units (Z=1.65, σ=20.0, LT=5.0 days)
        answer: Safety stock ≈ **73.8 units** (1.65 × 20 × √5). Rounding up, keep about 74 units as a buffer.
        expected ['safety_stock_calculator'] ✅  1.4s

[ 4/12] [single_tool] We have 800 units on hand and sell 40 units per day. How many days of supply do we have?
        → days_of_supply_calculator(on_hand_units=800, avg_daily_demand=40)
          = Days of Supply = 20.0 days (800.0 units ÷ 40.0 units/day)
        answer: You have **20 days of supply**: 800 units ÷ 40 units per day.
        expected ['days_of_supply_calculator'] ✅  1.4s

[ 5/12] [single_tool] An item represents 5% of our annual spend. What ABC class is it?
        → abc_classifier(annual_spend_pct=5)
          = Class C: 5.0% of annual spend — low-value — simplified control (but check criticality)
        answer: At 5% of annual spend, the item is **Class C** (low value). Use simplified control, but check whether it's ope...
        expected ['abc_classifier'] ✅  1.4s

[ 6/12] [single_tool] What is today's date? I need to schedule a reorder.
        → inventory_date_info()
          = Today is Tuesday, November 10, 2026 (week 46 of 2026)
        answer: Today is **Tuesday, November 10, 2026**. You can use this as the reference date when scheduling the reorder.
        expected ['inventory_date_info'] ✅  1.4s

[ 7/12] [multi_tool] Calculate the EOQ for D=5000, S=$30, H=$4, and also tell me today's date so I can schedule the first order.
        → eoq_calculator(annual_demand=5000, ordering_cost=30, holding_cost_per_unit=4)
          = EOQ = 273.9 units (D=5000.0, S=$30.0, H=$4.0)
        → inventory_date_info()
          = Today is Tuesday, November 10, 2026 (week 46 of 2026)
        answer: Today is **Tuesday, November 10, 2026**. You can use this as the reference date when scheduling the reorder.
        expected ['eoq_calculator', 'inventory_date_info'] ✅  1.4s

[ 8/12] [multi_tool] Our item has 30 units/day demand, 10-day lead time, no safety stock. Calculate the ROP and how many days 450 units on hand will last.
        → reorder_point_calculator(avg_daily_demand=30, lead_time_days=10, safety_stock=0)
          = Reorder Point = 300.0 units (demand 30.0/day × 10.0 days lead time + 0.0 safety stock)
        → days_of_supply_calculator(on_hand_units=450, avg_daily_demand=30)
          = Days of Supply = 15.0 days (450.0 units ÷ 30.0 units/day)
        answer: Reorder point = **300 units** (30 units/day × 10 days, no safety stock). Your 450 units on hand will last **15...
        expected ['reorder_point_calculator', 'days_of_supply_calculator'] ✅  1.4s

[ 9/12] [ambiguous] What is 2 * 5000 * 30 / 4 and then take the square root?
        → (no tool call)
        answer: 2 × 5,000 × 30 ÷ 4 = 75,000, and √75,000 ≈ **273.86**.
        expected ['eoq_calculator'] ❌  0.7s

[10/12] [ambiguous] Tell me about right now so I can timestamp my inventory report.
        → inventory_date_info()
          = Today is Tuesday, November 10, 2026 (week 46 of 2026)
        answer: It's **Tuesday, November 10, 2026**. You can use that as the timestamp for your inventory report.
        expected ['inventory_date_info'] ✅  1.4s

[11/12] [no_tool] What does FEFO stand for in warehouse management?
        → (no tool call)
        answer: FEFO stands for **First Expired, First Out**: items with the earliest expiry date are picked and shipped first...
        expected no tool ✅  0.7s

[12/12] [no_tool] Explain the difference between cycle stock and safety stock.
        → (no tool call)
        answer: **Cycle stock** is the inventory you expect to use between regular orders: it rises when an order arrives and ...
        expected no tool ✅  0.7s

================================================================================
CONSOLIDATED EVALUATION SUMMARY
================================================================================
       Category               Metric     Value                       Description
Tool Invocation  Precision (Overall)     1.000       Correct calls / Total calls
Tool Invocation Precision (Avg/Task)     0.917    Average precision across tasks
Tool Invocation     Recall (Overall)     0.917   Expected tools that were called
Tool Invocation    Recall (Avg/Task)     0.917       Average recall across tasks
     Efficiency   Avg Calls per Task      0.92             Mean tool invocations
     Efficiency    Optimal Call Rate     91.7%     Tasks with optimal tool count
     Efficiency    Over-calling Rate      0.0%      Tasks with excess tool calls
     Efficiency   Under-calling Rate      8.3%          Tasks with too few calls
        Success    Tool Success Rate     1.000      Calls that ran without error
        Success    Failed Tool Calls         0       Number of failed executions
        Success     Attribution Rate     0.900 Answers that used a tool's result
         System          Avg Latency      1.2s         Time per task, end to end
           Cost           Total Cost $0.001692           LLM tokens + tool calls
           Cost     Cost per Success $0.000141          Cost per successful task
           Cost  Cost Classification       Low             Low / Moderate / High

====================================================================================================
PER-TASK DETAILED RESULTS
====================================================================================================
 #                                      Question    Category                      Expected                        Actual Precision Recall Success  Tokens     Cost
 1 Calculate the reorder point for an item wi... single_tool                 reorder_point                 reorder_point      1.00   1.00     Yes    1401 $0.00016
 2 What is the EOQ for annual demand of 10000... single_tool                           eoq                           eoq      1.00   1.00     Yes    1381 $0.00016
 3 Calculate safety stock using Z=1.65, deman... single_tool                  safety_stock                  safety_stock      1.00   1.00     Yes    1360 $0.00015
 4 We have 800 units on hand and sell 40 unit... single_tool                days_of_supply                days_of_supply      1.00   1.00     Yes    1350 $0.00015
 5 An item represents 5% of our annual spend.... single_tool                abc_classifier                abc_classifier      1.00   1.00     Yes    1363 $0.00016
 6 What is today's date? I need to schedule a... single_tool                     date_info                     date_info      1.00   1.00     Yes    1328 $0.00015
 7 Calculate the EOQ for D=5000, S=$30, H=$4,...  multi_tool                eoq, date_info                eoq, date_info      1.00   1.00     Yes    1462 $0.00017
 8 Our item has 30 units/day demand, 10-day l...  multi_tool reorder_point, days_of_supply reorder_point, days_of_supply      1.00   1.00     Yes    1521 $0.00019
 9 What is 2 * 5000 * 30 / 4 and then take th...   ambiguous                           eoq                          None      0.00   0.00     Yes     620 $0.00007
10 Tell me about right now so I can timestamp...   ambiguous                     date_info                     date_info      1.00   1.00     Yes    1331 $0.00015
11 What does FEFO stand for in warehouse mana...     no_tool                          None                          None      1.00   1.00     Yes     644 $0.00008
12 Explain the difference between cycle stock...     no_tool                          None                          None      1.00   1.00     Yes     672 $0.00009

💡 What to point out

  • Precision is a perfect 1.000: every tool call was a correct one. Recall is 0.917 because of scenario 9, where the model did the square-root sum itself instead of using eoq_calculator.
  • Is that really a failure? The answer (273.86) is right. This is a good class debate: sometimes the test label is what needs fixing, not the agent.
  • The no-tool questions (FEFO, cycle stock) cost half the tokens of the tool questions, because a tool call means two model calls.
  • 12 tasks cost about $0.0017 in total; cost per success is "Low".
Human review

Checking the judge against a person

E

annotator.html + judge_agreement.py: can we trust the LLM judge?

Every score above came from an LLM judge. Before trusting it on thousands of answers, a person reviews a sample, and we measure how often the two agree beyond chance.

1. The review screen

annotator.html with prompt_eval_results.csv loaded: reviewing answer 4 of 18 (screenshot)
annotator.html with prompt_eval_results.csv loaded: reviewing answer 4 of 18 (screenshot)

💡 How to use it

  1. Double-click annotator.html to open it in your browser. Nothing to install.
  2. Upload agent output: choose prompt_eval_results.csv (or rag_eval_results.csv).
  3. For each answer: 👍 or 👎 (or press P / F), write why in the feedback box, then Submit feedback (Ctrl+Enter). "Show the reference answer" opens the answer key when you need it.
  4. Download feedback: you get the same CSV with human_label and human_feedback added.

The judge's scores are in the file but never shown on screen, so the reviewer isn't nudged to agree with them.

2. How the page works (the important parts)

annotator.html · lines 120–130
  function load(text, name) {
    const data = parseCSV(text.replace(/^\uFEFF/, ""));
    if (data.length < 2) return toast("That file has no rows.");
    cols = data[0];
    if (!pick(Q) || !pick(R)) return toast("Need a question column and a response column.");
    rows = data.slice(1).map(r => Object.fromEntries(cols.map((c, j) => [c, r[j] ?? ""])));
    rows.forEach(r => { r.human_label = r.human_label || ""; r.human_feedback = r.human_feedback || ""; });
    fileName = name || fileName; i = 0;
    $("annEmpty").hidden = true; $("annWork").hidden = false; $("annDownload").disabled = false;
    show();
  }
annotator.html · lines 156–164
  function download() {
    rows[i].human_feedback = $("annNote").value.trim();
    const header = [...cols.filter(c => c !== "human_label" && c !== "human_feedback"), "human_label", "human_feedback"];
    const csv = [header.map(esc).join(",")].concat(rows.map(r => header.map(c => esc(r[c] ?? "")).join(","))).join("\n");
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob([csv], {type: "text/csv"}));
    a.download = fileName.replace(/\.csv$/i, "") + "_feedback.csv";
    document.body.appendChild(a); a.click(); a.remove();
  }

load reads the CSV, finds the question and response columns by name, and adds two empty columns. download writes every original column plus the two new ones back out as a CSV file. Everything happens in the browser; no data leaves the computer.

3. Measure agreement

judge_agreement.py · lines 20–27
def cohens_kappa(a, b):
    """Agreement between two raters, after removing the agreement expected by chance."""
    n = len(a)
    observed = sum(x == y for x, y in zip(a, b)) / n
    labels = set(a) | set(b)
    chance = sum((a.count(l) / n) * (b.count(l) / n) for l in labels)
    kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0
    return observed, chance, kappa
judge_agreement.py · lines 38–70
if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "prompt_eval_results_feedback.csv"
    with open(path, encoding="utf-8") as f:
        rows = [r for r in csv.DictReader(f) if r.get("human_label") in ("pass", "fail")]
    if not rows:
        sys.exit("No rows with a human_label of pass/fail. Annotate the file in annotator.html first.")

    scores = [c for c in SCORE_COLUMNS if c in rows[0]]
    judge = ["pass" if all(r[c] == "1" for c in scores) else "fail" for r in rows]
    human = [r["human_label"] for r in rows]

    print(f"File: {path}  ({len(rows)} reviewed answers)")
    print(f"Judge passes an answer when all of these are 1: {', '.join(scores)}\n")

    print("                 Human: pass   Human: fail")
    for j in ("pass", "fail"):
        cells = [sum(1 for x, y in zip(judge, human) if x == j and y == h) for h in ("pass", "fail")]
        print(f"  Judge: {j:<5}   {cells[0]:>10}   {cells[1]:>11}")

    observed, chance, kappa = cohens_kappa(judge, human)
    print(f"\nRaw agreement        : {observed:.0%}")
    print(f"Agreement by chance  : {chance:.0%}   (judge passes {judge.count('pass')}/{len(rows)}, "
          f"human passes {human.count('pass')}/{len(rows)})")
    print(f"Cohen's kappa        : {kappa:.2f}  → {describe(kappa)} agreement")

    disagreements = [(r, j, h) for r, j, h in zip(rows, judge, human) if j != h]
    if disagreements:
        print(f"\nDisagreements to discuss ({len(disagreements)}):")
        for r, j, h in disagreements:
            tag = r.get("prompt_version") or r.get("config") or ""
            print(f"  • [{tag}] {r['question'][:70]}...")
            print(f"      judge: {j:<4} ({r.get('judge_reason', '')})")
            print(f"      human: {h:<4} ({r.get('human_feedback') or 'no note'})")
Output (real run on the example review of the 18 answers)
File: prompt_eval_results_feedback.csv  (18 reviewed answers)
Judge passes an answer when all of these are 1: accuracy, clarity, completeness

                 Human: pass   Human: fail
  Judge: pass            10             1
  Judge: fail             2             5

Raw agreement        : 83%
Agreement by chance  : 54%   (judge passes 11/18, human passes 12/18)
Cohen's kappa        : 0.64  → substantial agreement

Disagreements to discuss (3):
  • [Version 1] Supplier A has a unit price of $10 with 30-day lead time. Supplier B h...
      judge: pass (Mentions total cost including holding cost.)
      human: fail (Never says which supplier to pick or how to compare them.)
  • [Version 1] We ran out of stock last month. I want to set safety stock high enough...
      judge: fail (Right idea, but doesn't say how to set safety stock.)
      human: pass (Short, but right.)
  • [Version 2] We have a perishable item with a 10-day shelf life. Our reorder cycle ...
      judge: fail (Correct, but the action is buried in a long answer.)
      human: pass (Long, but correct and the action is clear enough.)

💡 Reading the result

  • 83% raw agreement sounds great, but 54% would happen by chance, because both judge and human pass most answers.
  • Kappa 0.64 is "substantial": good enough to use the judge for comparing prompt versions, not yet good enough to trust on its own in production.
  • The three disagreements are the most useful lines on the page. Two show the judge being stricter than a warehouse manager about long answers; one shows it passing an answer that never gives a decision. Each becomes a line in the judge's prompt; then measure again.
Teach and extend

Connecting the code to the lecture

↔

Link to the lecture

In the codeLecture ideaSlide
Prompt Version 1 vs Version 2Gulf of specification2
Running the same scenarios many times, scoring eachWhy one-off testing fails3
Four files, four componentsEach component needs its own evaluation4, 6
dataset, eval_dataset, expected_toolsReference-based metrics (the answer key)5, 18–19
Answer GroundednessReference-free metric5, 20
Recall@k, latency, cost, precision, recallMetrics per component6
Judge Reason + reviewer notesError analysis8, 23
annotator.htmlCustom data annotator9
judge_agreement.pyChance agreement and Cohen's kappa13–15
!

Known limits (good discussion points)

  1. The judge grades its own model. The advisor and the judge are both gpt-6-luna; models can be lenient on answers written in their own style. A larger model as judge is a common upgrade, and judge_agreement.py tells you whether it helped.
  2. Small test sets. 9 prompt questions and 5 RAG questions: one answer moves a score by 11–20 points. Set NUM_QUESTIONS = 10 in the RAG file, and grow the sets over time.
  3. Pass/fail hides partial credit. That's the price of consistency; the judge's reason gives back some of the detail.
  4. The router has no "other" route. "What's the weather?" is forced into reorder, forecast or supplier.
  5. Some test labels are debatable. Scenario 9 expects eoq_calculator for pure arithmetic, and relevant_docs says passage 1 is needed for the supplier question. Gold sets need review too.
  6. Attribution is still a heuristic. It checks that the tool's main number appears in the answer; an answer that rounds 707.1 to "about 700" counts as not using the tool.
  7. Two precision numbers. The summary counts every call (so calling a tool twice counts twice); the per-task table compares sets of tool names. Both are fair; just say which one you mean.
  8. The annotator keeps nothing until you download. Closing the tab loses unsaved reviews, so download as you go.
✎

Exercises for learners

1. Add a Version 3 prompt based on the error analysis, and rerun the prompt eval.

Add to prompts: Version 2's text plus "Before answering, name the assumption hidden in the question and say whether it holds." Compare Completeness and Clarity with Version 2: did the new line help, or make answers longer and less clear?

2. Set NUM_QUESTIONS = 10 in the RAG eval. Does the best configuration change?

Questions 6–10 include the perishable question, which needs only one passage, so Config A's Recall@k rises on that one. Look at whether the overall ranking holds with twice the data.

3. Add Precision@k to the RAG eval.

len(set(retrieved) & set(relevant)) / len(retrieved). Config C will have the best recall but the worst precision (it always fetches 3), which is the trade-off of a bigger k: more noise in the context.

4. Give the router an "other" route.

Add "other" to Route.category, a node that replies "I can help with reorders, forecasts and suppliers", and an edge for it. Add two off-topic questions to the slide 4 router test.

5. Add a scenario where a tool must fail.

"What is the EOQ for D=1000, S=$20, H=$0?" The tool returns "Error: holding cost must be > 0". Watch Tool Success Rate and Failed Tool Calls change, and check what the agent tells the user.

6. Review the 18 answers yourself in the annotator, then run judge_agreement.py on your file.

Is your kappa with the judge close to 0.64? Compare your notes with a classmate's: what's your kappa with each other? That's slides 11–15 in practice.

7. Change only the judge's model and compare kappa.

Set a different model for evaluate_response only (keep the advisor the same), rerun, review the same answers, and compare kappa. The better judge is the one that agrees with your expert more, not the one that gives higher scores.

★

Glossary

Golden dataset
Test questions with the answers (or tools, or passages) we expect.
LLM-as-judge
A model with a strict scoring prompt that grades another model's answers.
JSON mode
response_format={"type": "json_object"}: the reply is always valid JSON.
Structured output
with_structured_output(Route): the reply is parsed into a Python object with allowed values only.
Conditional edge
A LangGraph arrow chosen at run time from the state (here, the route label).
Embedding / cosine similarity
Numbers that capture meaning / a score for how close two meanings are.
k
How many passages the search returns.
Recall@k
Share of the needed passages found in the top k.
Groundedness
Every claim in the answer comes from the retrieved context.
Tool precision / recall
Share of calls that were right / share of needed tools that were called.
Attribution
Whether the final answer used the tool's result.
usage_metadata
The real input and output token counts attached to each model reply.
Cohen's kappa
Agreement between two raters after removing chance agreement.
ROP / EOQ / safety stock
Reorder point / economic order quantity / extra buffer stock for surprises.
{ }

Full source

langgraph_router.py (complete file)
langgraph_router.py (complete file)
"""
LangGraph router: send each inventory question to the right specialist.
By Shivank Agarwal. Model: OpenAI gpt-6-luna.

    router ──► reorder  ──► END
           ├─► forecast ──► END
           └─► supplier ──► END

The router is one component of the agent, so it can be evaluated on its own:
did each question reach the right specialist?
"""
from typing import Literal, TypedDict

from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
from pydantic import BaseModel

load_dotenv()                                        # reads OPENAI_API_KEY from .env

llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")


def ask(system, user):
    """One model call with a system prompt; returns the reply as plain text."""
    return llm.invoke([SystemMessage(content=system), HumanMessage(content=user)]).text


# ---------- 1. The router: the model must pick exactly one of three labels ----------
class Route(BaseModel):
    category: Literal["reorder", "forecast", "supplier"]


router_llm = llm.with_structured_output(Route)       # the reply is parsed into a Route object


class State(TypedDict):
    query: str
    category: str
    response: str


def router(state):
    decision = router_llm.invoke([
        SystemMessage(content="Route the inventory query to one of: reorder, forecast, or supplier.\n"
                              "- reorder: reorder point, EOQ, safety stock, when to order\n"
                              "- forecast: demand prediction, adjusting forecasts\n"
                              "- supplier: comparing suppliers, lead times, vendor costs"),
        HumanMessage(content=state["query"]),
    ])
    return {"category": decision.category}


# ---------- 2. Three specialists: same model, different system prompts ----------
def reorder_node(state):
    answer = ask("You are an inventory reorder specialist. Answer concisely using inventory "
                 "principles like ROP, EOQ, and safety stock.", state["query"])
    return {"response": answer}


def forecast_node(state):
    answer = ask("You are a demand forecasting specialist. Answer concisely using concepts like "
                 "rolling averages, seasonality, and trend.", state["query"])
    return {"response": answer}


def supplier_node(state):
    answer = ask("You are a supplier management specialist. Answer concisely using concepts like "
                 "lead time, total cost, and vendor reliability.", state["query"])
    return {"response": answer}


def route_edge(state):
    return state["category"]                         # the label decides which node runs next


# ---------- 3. Wire the graph ----------
graph = StateGraph(State)
graph.add_node("router", router)
graph.add_node("reorder", reorder_node)
graph.add_node("forecast", forecast_node)
graph.add_node("supplier", supplier_node)

graph.set_entry_point("router")
graph.add_conditional_edges("router", route_edge,
                            {"reorder": "reorder", "forecast": "forecast", "supplier": "supplier"})
graph.add_edge("reorder", END)
graph.add_edge("forecast", END)
graph.add_edge("supplier", END)

app = graph.compile()

queries = [
    "We have 300 units on hand and sell 30 a day with a 5-day lead time. Should we reorder?",
    "Demand spiked 60% last week. How should I adjust my forecast?",
    "Supplier A is cheaper but takes 30 days. Supplier B costs more but delivers in 5 days. Which is better?",
]

if __name__ == "__main__":
    for i, q in enumerate(queries, start=1):
        result = app.invoke({"query": q, "category": "", "response": ""})
        print(f"\n[{i}] {q}")
        print(f"    route  → {result['category']}")
        answer = result["response"].strip().replace("\n", "\n" + " " * 13)   # keep long answers indented
        print(f"    answer → {answer}")
        print("-" * 70)
prompt_evals_inventory.py (complete file)
prompt_evals_inventory.py (complete file)
"""
Prompt evals: is prompt Version 2 really better than Version 1?
By Shivank Agarwal. Model: OpenAI gpt-6-luna (both the advisor and the judge).

1. A golden dataset: 9 tricky inventory questions, each with the key points a correct answer must make.
2. Two system prompts for the same advisor.
3. An LLM judge scores every answer Pass (1) or Fail (0) on Accuracy, Clarity and Completeness,
   and gives a one-line reason, which is what you read during error analysis.
4. Pass rates per prompt version, and a CSV of every answer for human review.
"""
import csv
import json
import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                                        # reads OPENAI_API_KEY from .env
client = OpenAI()
MODEL = "gpt-6-luna"
METRICS = ["Accuracy", "Clarity", "Completeness"]
RESULTS_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt_eval_results.csv")


def evaluate_response(question, expected_answer, actual_response):
    """LLM-as-judge: strict binary scores (0 = Fail, 1 = Pass) plus a one-line reason."""
    eval_prompt = f"""Evaluate this inventory reorder advisor response with STRICT binary scoring (0=Fail, 1=Pass).

    Question: {question}
    Expected Key Points: {expected_answer}
    Actual Response: {actual_response}

    Be STRICT. Only give 1 if the criterion is fully met:
    - Accuracy: Is the reorder recommendation correct with NO errors or misleading statements? (0 or 1)
    - Clarity: Would a warehouse manager act on this WITHOUT further questions? (0 or 1)
    - Completeness: Does it address the SPECIFIC edge case or nuance in the question? (0 or 1)

    Respond ONLY with JSON in this exact shape:
    {{"Accuracy": 0 or 1, "Clarity": 0 or 1, "Completeness": 0 or 1, "Reason": "one short sentence"}}"""

    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        response_format={"type": "json_object"},     # JSON mode: the reply is always valid JSON
        messages=[{"role": "user", "content": eval_prompt}],
    )
    verdict = json.loads(response.choices[0].message.content)
    scores = {m: 1 if verdict.get(m) in (1, "1", True) else 0 for m in METRICS}
    scores["Reason"] = str(verdict.get("Reason", ""))
    return scores


def inventory_advisor(system_prompt, question):
    """The agent under test: answers an inventory question using the given system prompt."""
    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": question},
        ],
    )
    return response.choices[0].message.content


dataset = [
    {
        "q": "Our safety stock formula says reorder at 200 units. We have 210 units on hand and a PO arriving tomorrow. Should we reorder now?",
        "a": "No. On-hand (210) is above reorder point (200) AND incoming stock will arrive tomorrow. Reordering now creates overstock. Must account for in-transit inventory in the reorder calculation.",
    },
    {
        "q": "Demand jumped 40% last week. Should I immediately raise the reorder point by 40%?",
        "a": "No. A single week's spike may be seasonal or anomalous. Must consider average demand over a rolling window (e.g., 4–8 weeks). Raising the reorder point by 40% based on one week risks permanent overstock.",
    },
    {
        "q": "We use EOQ to calculate order quantity. Our carrying cost just doubled. Should my order quantity go up or down?",
        "a": "Down. EOQ = sqrt(2DS/H). As H (holding cost) doubles, EOQ decreases. Ordering in smaller, more frequent batches is now cheaper than holding large lots.",
    },
    {
        "q": "Lead time from our supplier is 7 days. My reorder point is 70 units (10 units/day × 7 days). Is that correct?",
        "a": "Only in the ideal case with zero demand variability. In practice the reorder point must include safety stock: ROP = (avg demand × lead time) + safety stock. The formula is incomplete without safety stock for variable demand.",
    },
    {
        "q": "We have a perishable item with a 10-day shelf life. Our reorder cycle is every 8 days. Is there a problem?",
        "a": "Potentially yes. If the item arrives on day 1 and sits until the next order cycle, remaining shelf life when consumed could be very short. Must align reorder cycle with shelf life and consider FEFO (First Expired First Out) rotation.",
    },
    {
        "q": "Our ABC analysis puts item X in class C (low value). Can I just set a fixed reorder point and ignore it?",
        "a": "Not always. Class C items can still be operationally critical (e.g., a cheap bolt that stops an assembly line). Must distinguish between value-based ABC and criticality. Critical C items need tighter review despite low cost.",
    },
    {
        "q": "Supplier A has a unit price of $10 with 30-day lead time. Supplier B has $11 with 5-day lead time. Supplier A is always better, right?",
        "a": "No. Longer lead time requires higher safety stock, which increases holding costs. Total cost = purchase price + ordering cost + holding cost. Supplier B's shorter lead time may result in lower total inventory cost despite higher unit price.",
    },
    {
        "q": "We ran out of stock last month. I want to set safety stock high enough that we never stock out again. Is that achievable?",
        "a": "Not economically. Safety stock reduces stockout probability but cannot eliminate it without infinite inventory. Must choose a service level (e.g., 95% or 99%) and calculate the safety stock that achieves it, accepting a residual stockout risk.",
    },
    {
        "q": "Demand is perfectly constant at 50 units/day and lead time is always exactly 3 days. Do I need safety stock?",
        "a": "No. With zero variability in both demand and lead time, the reorder point is exactly 150 units (50 × 3) and safety stock = 0. Safety stock compensates for variability; if there is none, it adds cost without benefit.",
    },
]

prompts = {
    "Version 1": "You are an inventory management advisor. Answer the question.",
    "Version 2": """You are an inventory management advisor for warehouse operations teams.

    When answering questions:
    1. State the core inventory principle or formula first (e.g., EOQ, ROP, safety stock)
    2. Explain BOTH the textbook/ideal case AND the real-world complication if they differ
    3. Explicitly correct any common misconception embedded in the question
    4. Use concrete numbers from the question to illustrate your answer

    Always address the specific edge case or nuance — managers ask these questions because they have a hidden assumption that may be wrong.""",
}


def mark(score):
    return "✅" if score else "❌"


def bar(passed, total, width=20):
    filled = round(width * passed / total) if total else 0
    return "█" * filled + "░" * (width - filled)


if __name__ == "__main__":
    # ---------- Step 1: look at one question side by side ----------
    q1 = dataset[0]["q"]
    print(f"\nQUESTION 1:\n{q1}\n")
    print("=" * 70)
    for prompt_name in prompts:
        print(f"\n{prompt_name} ANSWER:")
        print("-" * 30)
        print(inventory_advisor(prompts[prompt_name], q1))

    # ---------- Step 2: run every question through both prompts and judge each answer ----------
    results = {name: {m: [] for m in METRICS} for name in prompts}
    rows = []
    for prompt_name, prompt in prompts.items():
        print(f"\n{'=' * 70}\nEvaluating: {prompt_name}\n{'=' * 70}")
        print(f"  {'#':<4}{'Acc':^6}{'Clar':^6}{'Comp':^6}  Judge's reason")
        for i, item in enumerate(dataset, start=1):
            response = inventory_advisor(prompt, item["q"])
            scores = evaluate_response(item["q"], item["a"], response)
            for m in METRICS:
                results[prompt_name][m].append(scores[m])
            print(f"  Q{i:<3}{mark(scores['Accuracy']):^5}{mark(scores['Clarity']):^5}"
                  f"{mark(scores['Completeness']):^5}  {scores['Reason']}")
            rows.append({"prompt_version": prompt_name, "question": item["q"], "expected": item["a"],
                         "response": response, **{m.lower(): scores[m] for m in METRICS},
                         "judge_reason": scores["Reason"]})

    # ---------- Step 3: pass rates ----------
    print("\n" + "=" * 70)
    print("PASS RATES BY PROMPT VERSION")
    print("=" * 70)
    for prompt_name in prompts:
        print(f"\n{prompt_name.upper()}:")
        total_pass = total_tests = 0
        for m in METRICS:
            passed, total = sum(results[prompt_name][m]), len(results[prompt_name][m])
            total_pass, total_tests = total_pass + passed, total_tests + total
            print(f"  {m:<13} {bar(passed, total)} {passed}/{total} ({100 * passed / total:.0f}%)")
        print(f"  {'Overall':<13} {bar(total_pass, total_tests)} {total_pass}/{total_tests} "
              f"({100 * total_pass / total_tests:.0f}%)")

    # ---------- Step 4: save every answer for human review (the annotator reads this file) ----------
    with open(RESULTS_CSV, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"\nSaved {len(rows)} judged answers to {RESULTS_CSV}")
rag_evals_inventory.py (complete file)
rag_evals_inventory.py (complete file)
"""
RAG evaluation: which retrieval + prompt setup answers inventory questions best?
By Shivank Agarwal. Models: OpenAI gpt-6-luna (answers and judge), text-embedding-3-small (search).

1. A small knowledge base: 12 inventory-policy passages.
2. A simple RAG agent: embed the question, fetch the k closest passages, answer from them.
3. A golden dataset: 10 questions, each with a reference answer and the passages it needs.
4. Three configurations: A (k=1, minimal prompt), B (k=2, structured), C (k=3, grounded).
5. Two kinds of metric:
   - Retrieval Recall@k (no model needed): did we fetch the passages the question needs?
   - LLM-as-judge (0/1): Context Relevance, Answer Groundedness, Answer Correctness.
6. A comparison table, and a CSV of every answer for human review.
"""
import csv
import json
import os

import numpy as np
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                                        # reads OPENAI_API_KEY from .env
client = OpenAI()
MODEL = "gpt-6-luna"
EMBED_MODEL = "text-embedding-3-small"
NUM_QUESTIONS = 5                                    # set to 10 for the full run
METRICS = ["Context Relevance", "Answer Groundedness", "Answer Correctness"]
RESULTS_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag_eval_results.csv")


def evaluate_rag_response(question, retrieved_context, generated_answer, reference_answer):
    """LLM-as-judge: 3 binary scores (0/1) plus a one-line reason."""
    eval_prompt = f"""You are evaluating a RAG system for inventory management. Be STRICT with scoring.

    Question: {question}
    Retrieved Context: {retrieved_context}
    Generated Answer: {generated_answer}
    Reference Answer: {reference_answer}

    Evaluate these 3 metrics:

    1. Context Relevance (0 or 1):
    Does the retrieved context contain ALL information needed to fully answer the question?
    Score 0 if the context is missing key facts mentioned in the reference answer.

    2. Answer Groundedness (0 or 1):
    Is EVERY claim in the generated answer explicitly supported by the retrieved context?
    Score 0 if the answer includes ANY information not found in the context.
    Score 0 if the answer adds details or numbers beyond what the context provides.

    3. Answer Correctness (0 or 1):
    Does the generated answer match the reference answer's key facts?
    Score 0 if any key information is wrong or missing.

    Respond ONLY with JSON in this exact shape:
    {{"Context Relevance": 0 or 1, "Answer Groundedness": 0 or 1, "Answer Correctness": 0 or 1, "Reason": "one short sentence"}}"""

    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        response_format={"type": "json_object"},     # JSON mode: the reply is always valid JSON
        messages=[{"role": "user", "content": eval_prompt}],
    )
    verdict = json.loads(response.choices[0].message.content)
    scores = {m: 1 if verdict.get(m) in (1, "1", True) else 0 for m in METRICS}
    scores["Reason"] = str(verdict.get("Reason", ""))
    return scores


documents = [
    # Doc 0: Reorder point basics
    "A reorder point (ROP) is the inventory level that triggers a new purchase order. "
    "It is calculated as: ROP = average daily demand × lead time in days.",

    # Doc 1: Safety stock (needs Doc 0 for full picture)
    "Safety stock is extra inventory held to guard against demand spikes and lead-time variability. "
    "The full reorder point formula is: ROP = (average demand × lead time) + safety stock. "
    "Without safety stock the formula only works when demand and lead time are perfectly constant.",

    # Doc 2: EOQ definition
    "Economic Order Quantity (EOQ) is the order size that minimises total inventory cost. "
    "Formula: EOQ = sqrt(2 × D × S / H), where D = annual demand, S = ordering cost, H = holding cost per unit per year.",

    # Doc 3: EOQ sensitivity (needs Doc 2)
    "In the EOQ formula, holding cost H is in the denominator under the square root. "
    "When holding cost doubles, EOQ decreases — it becomes cheaper to order smaller quantities more frequently. "
    "Conversely, when ordering cost S rises, EOQ increases.",

    # Doc 4: ABC classification basics
    "ABC analysis classifies inventory by value: A items are high-value (top 70-80% of spend), "
    "B items are medium-value, and C items are low-value (bottom 5% of spend). "
    "Cycle count frequency and review effort are typically proportional to class.",

    # Doc 5: ABC criticality caveat (needs Doc 4)
    "ABC classification is based on monetary value, not operational importance. "
    "A low-value (Class C) item can still be operationally critical — for example, a cheap O-ring "
    "that stops an entire production line. Critical C items require tighter controls despite low cost.",

    # Doc 6: Lead time and supplier trade-offs
    "Supplier lead time directly affects required safety stock and reorder point. "
    "A supplier with a longer lead time forces higher safety stock, increasing holding costs. "
    "Total procurement cost = unit price + ordering cost + holding cost; a higher-priced supplier "
    "with shorter lead time may have lower total cost than a cheaper supplier with long lead time.",

    # Doc 7: Service level and stockout risk (needs Doc 1)
    "A 100% service level (zero stockout) would require infinite safety stock, which is not economically viable. "
    "Companies choose a target service level (e.g., 95% or 99%) and calculate the safety stock needed to achieve it "
    "using the formula: safety stock = Z × σ_demand × sqrt(lead time), where Z is the service-level z-score.",

    # Doc 8: Perishable inventory
    "Perishable items have a finite shelf life. The reorder cycle must be short enough that items are consumed "
    "before expiry. FEFO (First Expired First Out) rotation ensures oldest stock is picked first. "
    "If the reorder cycle approaches the shelf life, there is a risk of expiry before consumption.",

    # Doc 9: In-transit inventory
    "In-transit (pipeline) inventory refers to stock already ordered but not yet received. "
    "When calculating whether to reorder, on-hand inventory plus in-transit inventory should both be compared "
    "against the reorder point. Reordering when in-transit stock will bring inventory above ROP causes overstock.",

    # Doc 10: Demand variability and averaging
    "A single week of unusually high demand should not immediately trigger a permanent change to the reorder point. "
    "Demand should be averaged over a rolling window (typically 4–8 weeks) to smooth out anomalies. "
    "Reacting to a single spike risks permanent overstock if the spike was seasonal or one-off.",

    # Doc 11: Zero-variability special case (needs Doc 1 and Doc 7)
    "When both demand and lead time are perfectly constant with zero variability, safety stock is zero. "
    "The reorder point equals exactly: average demand × lead time. "
    "Safety stock exists to absorb variability; if there is none, safety stock adds cost without benefit.",
]

# ---------- Embeddings: every passage is embedded ONCE, in a single API call ----------
def embed(texts):
    response = client.embeddings.create(model=EMBED_MODEL, input=texts)
    return np.array([item.embedding for item in response.data])


doc_embeddings = embed(documents)                    # shape: (12, 1536)


def retrieve(query, k=2):
    """Return the numbers of the k passages closest in meaning to the query."""
    q = embed([query])[0]
    sims = doc_embeddings @ q / (np.linalg.norm(doc_embeddings, axis=1) * np.linalg.norm(q))
    return [int(i) for i in np.argsort(sims)[::-1][:k]]      # highest cosine similarity first


PROMPT_MINIMAL = """Context: {context}

Question: {question}
Answer:"""

PROMPT_STRUCTURED = """Use the context below to answer the inventory question.

Context:
{context}

Question: {question}
Answer based on the context:"""

PROMPT_GROUNDED = """You are an inventory management advisor. Answer using ONLY the provided context.
Combine information from all context passages to give a complete answer.
If the context is incomplete, say what's missing.

Context:
{context}

Question: {question}
Answer (use all relevant context):"""


def rag_agent(question, k=2, prompt_template=PROMPT_MINIMAL):
    """RAG agent: retrieve k passages, then answer from them."""
    doc_ids = retrieve(question, k=k)
    context = "\n---\n".join(documents[i] for i in doc_ids)
    prompt = prompt_template.format(context=context, question=question)
    response = client.chat.completions.create(
        model=MODEL,
        reasoning_effort="none",
        messages=[{"role": "user", "content": prompt}],
    )
    return {"doc_ids": doc_ids, "context": context, "answer": response.choices[0].message.content}


eval_dataset = [
    {
        "question": "What is the reorder point formula and when should safety stock be included?",
        "reference": "ROP = average demand × lead time. Safety stock must be added when demand or lead time vary: ROP = (avg demand × lead time) + safety stock.",
        "relevant_docs": [0, 1],
    },
    {
        "question": "If our holding cost doubles, should we increase or decrease our order quantity?",
        "reference": "Decrease. In EOQ = sqrt(2DS/H), H is in the denominator. Doubling H reduces EOQ — smaller, more frequent orders become cheaper.",
        "relevant_docs": [2, 3],
    },
    {
        "question": "A Class C item has very low cost. Can we safely ignore it in cycle counts?",
        "reference": "Not always. ABC is value-based, not criticality-based. A cheap Class C item can be operationally critical and stop a production line. Critical C items need tighter controls.",
        "relevant_docs": [4, 5],
    },
    {
        "question": "Supplier A is cheaper per unit but has a 30-day lead time. Supplier B costs more but delivers in 5 days. How should we evaluate them?",
        "reference": "Compare total cost = unit price + ordering cost + holding cost. Longer lead time forces higher safety stock and higher holding costs. Supplier B may have lower total cost despite higher unit price.",
        "relevant_docs": [6, 1],
    },
    {
        "question": "Can we set safety stock high enough to guarantee we never stock out?",
        "reference": "No. 100% service level requires infinite safety stock. Choose a target service level (e.g., 95% or 99%) and calculate safety stock using: safety stock = Z × σ_demand × sqrt(lead time).",
        "relevant_docs": [7, 1],
    },
    {
        "question": "We have a perishable product with a 10-day shelf life and reorder every 8 days. Is there a risk?",
        "reference": "Yes. If stock arrives and sits near the end of the cycle, remaining shelf life at time of use could be very short. Use FEFO rotation and ensure the reorder cycle is well within shelf life.",
        "relevant_docs": [8],
    },
    {
        "question": "We have 220 units on hand and a PO of 100 units arriving tomorrow. ROP is 200. Should we reorder?",
        "reference": "No. On-hand (220) already exceeds ROP (200), and in-transit stock (100) will push inventory even higher. Reordering now causes overstock. Always include in-transit inventory in the reorder check.",
        "relevant_docs": [9, 0],
    },
    {
        "question": "Demand spiked 50% last week. Should I immediately raise the reorder point by 50%?",
        "reference": "No. A single week's spike may be seasonal or anomalous. Average demand over a rolling 4–8 week window before adjusting the reorder point. Reacting to one spike risks permanent overstock.",
        "relevant_docs": [10, 0],
    },
    {
        "question": "Our demand is exactly 40 units/day and lead time is always exactly 5 days. Do we need safety stock?",
        "reference": "No. With zero variability in both demand and lead time, ROP = 40 × 5 = 200 units and safety stock = 0. Safety stock compensates for variability; with none, it only adds holding cost.",
        "relevant_docs": [11, 1],
    },
    {
        "question": "What is EOQ and what happens to it when ordering cost increases?",
        "reference": "EOQ = sqrt(2DS/H). When ordering cost S increases, EOQ increases — it becomes cheaper to order larger quantities less frequently to spread the fixed ordering cost.",
        "relevant_docs": [2, 3],
    },
]

rag_configs = {
    "Config A: k=1, minimal":    {"k": 1, "prompt": PROMPT_MINIMAL},
    "Config B: k=2, structured": {"k": 2, "prompt": PROMPT_STRUCTURED},
    "Config C: k=3, grounded":   {"k": 3, "prompt": PROMPT_GROUNDED},
}


def recall_at_k(retrieved, relevant):
    """Share of the needed passages that were actually retrieved (1.0 = all of them)."""
    return len(set(retrieved) & set(relevant)) / len(relevant)


def mark(score):
    return "✅" if score else "❌"


if __name__ == "__main__":
    print(f"Corpus: {len(documents)} passages, embedded with {EMBED_MODEL}")
    print(f"Evaluation dataset: {len(eval_dataset)} questions (running the first {NUM_QUESTIONS})")
    print("RAG configurations:")
    for name, cfg in rag_configs.items():
        print(f"  {name} (retrieves {cfg['k']} passage(s))")

    test_data = eval_dataset[:NUM_QUESTIONS]
    results = {name: {m: [] for m in METRICS + ["Recall@k"]} for name in rag_configs}
    rows = []

    for config_name, config in rag_configs.items():
        print(f"\n{'=' * 78}\nEvaluating: {config_name}\n{'=' * 78}")
        print(f"  {'#':<4}{'needed':<9}{'retrieved':<12}{'Recall':>7}  {'Rel':^5}{'Grd':^5}{'Cor':^5}  Judge's reason")
        for i, item in enumerate(test_data, start=1):
            out = rag_agent(item["question"], k=config["k"], prompt_template=config["prompt"])
            recall = recall_at_k(out["doc_ids"], item["relevant_docs"])
            scores = evaluate_rag_response(item["question"], out["context"], out["answer"], item["reference"])
            for m in METRICS:
                results[config_name][m].append(scores[m])
            results[config_name]["Recall@k"].append(recall)
            print(f"  Q{i:<3}{str(item['relevant_docs']):<9}{str(out['doc_ids']):<12}{recall:>7.0%}  "
                  f"{mark(scores['Context Relevance']):^4}{mark(scores['Answer Groundedness']):^4}"
                  f"{mark(scores['Answer Correctness']):^4}  {scores['Reason']}")
            rows.append({"config": config_name, "question": item["question"], "reference": item["reference"],
                         "relevant_docs": item["relevant_docs"], "retrieved_docs": out["doc_ids"],
                         "recall_at_k": round(recall, 2), "response": out["answer"],
                         **{m.lower().replace(" ", "_"): scores[m] for m in METRICS},
                         "judge_reason": scores["Reason"]})

    print("\n" + "=" * 78)
    print(f"RAG EVALUATION RESULTS ({NUM_QUESTIONS} questions per configuration)")
    print("=" * 78)
    print(f"{'Configuration':<28}{'Recall@k':>10}{'Relevant':>10}{'Grounded':>10}{'Correct':>10}{'Overall':>10}")
    print("-" * 78)
    best_config, best_score = None, -1
    for config_name in rag_configs:
        r = results[config_name]
        avg = {m: sum(v) / len(v) for m, v in r.items()}
        overall = (avg["Context Relevance"] + avg["Answer Groundedness"] + avg["Answer Correctness"]) / 3
        print(f"{config_name:<28}{avg['Recall@k']:>10.0%}{avg['Context Relevance']:>10.0%}"
              f"{avg['Answer Groundedness']:>10.0%}{avg['Answer Correctness']:>10.0%}{overall:>10.0%}")
        if overall > best_score:
            best_score, best_config = overall, config_name
    print("-" * 78)
    print(f"Best: {best_config} ({best_score:.0%})")

    with open(RESULTS_CSV, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"\nSaved {len(rows)} judged answers to {RESULTS_CSV}")
tool_evals_inventory.py (complete file)
tool_evals_inventory.py (complete file)
"""
Tool evals: does the agent pick the right calculator, the right number of times, at what cost?
By Shivank Agarwal. Model: OpenAI gpt-6-luna.

1. Six inventory tools (reorder point, EOQ, safety stock, days of supply, ABC class, today's date).
2. A tool-calling agent built with LangChain's create_agent.
3. 12 test scenarios with the tools we EXPECT: single-tool, multi-tool, ambiguous, and no-tool.
4. Metrics from the lecture's "Tool Use" row: precision, recall, calls per task, tool success rate,
   attribution, latency and cost per successful task.
"""
import math
import re
import time
from dataclasses import dataclass, field
from datetime import date
from typing import Any, Dict, List, Optional

import pandas as pd
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.messages import AIMessage, ToolMessage
from langchain_openai import ChatOpenAI

load_dotenv()                                        # reads OPENAI_API_KEY from .env

# gpt-6-luna list prices, USD per 1M tokens (openai.com/api/pricing, Nov 2026). Update if they change.
INPUT_PRICE_PER_1M = 0.10
OUTPUT_PRICE_PER_1M = 0.50
TOOL_COST_PER_CALL = 0.0                             # these tools run locally, so they're free; set a price for paid APIs


# ---------------------------------------------------------------------------
# 1. Tools
# ---------------------------------------------------------------------------
@tool
def reorder_point_calculator(avg_daily_demand: float, lead_time_days: float, safety_stock: float = 0) -> str:
    """Calculate reorder point: ROP = (avg_daily_demand * lead_time_days) + safety_stock."""
    rop = avg_daily_demand * lead_time_days + safety_stock
    return f"Reorder Point = {rop:.1f} units (demand {avg_daily_demand}/day × {lead_time_days} days lead time + {safety_stock} safety stock)"


@tool
def eoq_calculator(annual_demand: float, ordering_cost: float, holding_cost_per_unit: float) -> str:
    """Calculate Economic Order Quantity: EOQ = sqrt(2 * D * S / H)."""
    if holding_cost_per_unit <= 0:
        return "Error: holding cost must be > 0"
    eoq = math.sqrt(2 * annual_demand * ordering_cost / holding_cost_per_unit)
    return f"EOQ = {eoq:.1f} units (D={annual_demand}, S=${ordering_cost}, H=${holding_cost_per_unit})"


@tool
def safety_stock_calculator(z_score: float, demand_std_dev: float, lead_time_days: float) -> str:
    """Calculate safety stock: SS = Z * σ_demand * sqrt(lead_time)."""
    ss = z_score * demand_std_dev * math.sqrt(lead_time_days)
    return f"Safety Stock = {ss:.1f} units (Z={z_score}, σ={demand_std_dev}, LT={lead_time_days} days)"


@tool
def days_of_supply_calculator(on_hand_units: float, avg_daily_demand: float) -> str:
    """Calculate days of supply remaining: DoS = on_hand / avg_daily_demand."""
    if avg_daily_demand <= 0:
        return "Error: daily demand must be > 0"
    dos = on_hand_units / avg_daily_demand
    return f"Days of Supply = {dos:.1f} days ({on_hand_units} units ÷ {avg_daily_demand} units/day)"


@tool
def abc_classifier(annual_spend_pct: float) -> str:
    """Classify an inventory item as A, B, or C based on its share of total annual spend (0-100)."""
    if annual_spend_pct >= 70:
        cls, desc = "A", "high-value — tight control, frequent review"
    elif annual_spend_pct >= 20:
        cls, desc = "B", "medium-value — moderate review"
    else:
        cls, desc = "C", "low-value — simplified control (but check criticality)"
    return f"Class {cls}: {annual_spend_pct:.1f}% of annual spend — {desc}"


@tool
def inventory_date_info() -> str:
    """Return today's date for reorder scheduling and expiry calculations."""
    today = date.today()
    return f"Today is {today.strftime('%A, %B %d, %Y')} (week {today.isocalendar()[1]} of {today.year})"


tools = [reorder_point_calculator, eoq_calculator, safety_stock_calculator,
         days_of_supply_calculator, abc_classifier, inventory_date_info]


# ---------------------------------------------------------------------------
# 2. The agent under test
# ---------------------------------------------------------------------------
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
agent = create_agent(
    llm,
    tools,
    system_prompt="""You are an inventory management assistant with access to calculation tools.
Use the appropriate tool(s) to answer inventory questions precisely.
Always use tools when they are relevant to the question.
Be precise in selecting the right tool for each task.""",
)


# ---------------------------------------------------------------------------
# 3. Test scenarios: the question, the tools we expect, and the ideal number of calls
# ---------------------------------------------------------------------------
test_scenarios = [
    # Single-tool
    {"question": "Calculate the reorder point for an item with 50 units/day demand, 7-day lead time, and 100 units safety stock.",
     "expected_tools": ["reorder_point_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "What is the EOQ for annual demand of 10000 units, ordering cost $50, holding cost $2 per unit?",
     "expected_tools": ["eoq_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "Calculate safety stock using Z=1.65, demand std dev of 20 units, and 5-day lead time.",
     "expected_tools": ["safety_stock_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "We have 800 units on hand and sell 40 units per day. How many days of supply do we have?",
     "expected_tools": ["days_of_supply_calculator"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "An item represents 5% of our annual spend. What ABC class is it?",
     "expected_tools": ["abc_classifier"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "What is today's date? I need to schedule a reorder.",
     "expected_tools": ["inventory_date_info"], "category": "single_tool", "requires_external_data": True, "optimal_tool_count": 1},

    # Multi-tool
    {"question": "Calculate the EOQ for D=5000, S=$30, H=$4, and also tell me today's date so I can schedule the first order.",
     "expected_tools": ["eoq_calculator", "inventory_date_info"], "category": "multi_tool", "requires_external_data": True, "optimal_tool_count": 2},
    {"question": "Our item has 30 units/day demand, 10-day lead time, no safety stock. Calculate the ROP and how many days 450 units on hand will last.",
     "expected_tools": ["reorder_point_calculator", "days_of_supply_calculator"], "category": "multi_tool", "requires_external_data": True, "optimal_tool_count": 2},

    # Ambiguous: the right tool is not named in the question
    {"question": "What is 2 * 5000 * 30 / 4 and then take the square root?",
     "expected_tools": ["eoq_calculator"], "category": "ambiguous",
     "acceptable_alternatives": [], "requires_external_data": True, "optimal_tool_count": 1},
    {"question": "Tell me about right now so I can timestamp my inventory report.",
     "expected_tools": ["inventory_date_info"], "category": "ambiguous", "requires_external_data": True, "optimal_tool_count": 1},

    # No tool needed: the model should answer from its own knowledge
    {"question": "What does FEFO stand for in warehouse management?",
     "expected_tools": [], "category": "no_tool", "requires_external_data": False, "optimal_tool_count": 0},
    {"question": "Explain the difference between cycle stock and safety stock.",
     "expected_tools": [], "category": "no_tool", "requires_external_data": False, "optimal_tool_count": 0},
]


# ---------------------------------------------------------------------------
# 4. What we record for every tool call and every task
# ---------------------------------------------------------------------------
@dataclass
class ToolCallLog:
    tool_name: str
    parameters: Dict[str, Any]
    output: str
    success: bool
    is_correct: bool


@dataclass
class TaskEvaluation:
    question: str
    category: str
    expected_tools: List[str]
    actual_tools: List[str]
    tool_call_logs: List[ToolCallLog]
    output: Optional[str]
    error: Optional[str]
    requires_external_data: bool
    optimal_tool_count: int
    acceptable_alternatives: List[List[str]] = field(default_factory=list)
    input_tokens: int = 0
    output_tokens: int = 0
    latency_s: float = 0.0

    @property
    def task_success(self) -> bool:
        return self.error is None and bool(self.output)

    @property
    def llm_cost(self) -> float:
        return self.input_tokens / 1e6 * INPUT_PRICE_PER_1M + self.output_tokens / 1e6 * OUTPUT_PRICE_PER_1M

    @property
    def tool_cost(self) -> float:
        return TOOL_COST_PER_CALL * len(self.tool_call_logs)

    @property
    def total_cost(self) -> float:
        return self.llm_cost + self.tool_cost


# ---------------------------------------------------------------------------
# 5. Run one scenario and read everything off the agent's message history
# ---------------------------------------------------------------------------
def is_correct_tool(tool_name: str, expected_tools: List[str], alternatives: List[List[str]]) -> bool:
    return tool_name in expected_tools or any(tool_name in alt for alt in alternatives)


def run_evaluation(scenario: dict) -> TaskEvaluation:
    expected = scenario["expected_tools"]
    alternatives = scenario.get("acceptable_alternatives", [])
    actual_tools, tool_logs = [], []
    output, error = None, None
    input_tokens = output_tokens = 0
    t0 = time.time()
    try:
        result = agent.invoke({"messages": [{"role": "user", "content": scenario["question"]}]})
        messages = result["messages"]
        requested = {}                                           # tool_call_id -> the model's request
        for m in messages:
            if isinstance(m, AIMessage):
                for tc in m.tool_calls:
                    requested[tc["id"]] = tc
                if m.usage_metadata:                             # real token counts from OpenAI
                    input_tokens += m.usage_metadata["input_tokens"]
                    output_tokens += m.usage_metadata["output_tokens"]
            elif isinstance(m, ToolMessage):                     # one per tool that actually ran
                tc = requested.get(m.tool_call_id, {"name": m.name, "args": {}})
                actual_tools.append(tc["name"])
                text = str(m.content)
                tool_logs.append(ToolCallLog(
                    tool_name=tc["name"], parameters=tc["args"], output=text,
                    success=m.status != "error" and "error" not in text.lower(),
                    is_correct=is_correct_tool(tc["name"], expected, alternatives),
                ))
        output = messages[-1].text
    except Exception as e:
        error = str(e)

    return TaskEvaluation(
        question=scenario["question"], category=scenario["category"],
        expected_tools=expected, actual_tools=actual_tools, tool_call_logs=tool_logs,
        output=output, error=error,
        requires_external_data=scenario["requires_external_data"],
        optimal_tool_count=scenario["optimal_tool_count"], acceptable_alternatives=alternatives,
        input_tokens=input_tokens, output_tokens=output_tokens, latency_s=time.time() - t0,
    )


# ---------------------------------------------------------------------------
# 6. Metrics
# ---------------------------------------------------------------------------
def compute_precision(results: List[TaskEvaluation]) -> Dict:
    """Precision = correct tool calls / all tool calls made."""
    total_calls = sum(len(r.actual_tools) for r in results)
    correct_calls = sum(log.is_correct for r in results for log in r.tool_call_logs)
    per_task = []
    for r in results:
        if r.actual_tools:
            per_task.append(sum(log.is_correct for log in r.tool_call_logs) / len(r.actual_tools))
        else:
            per_task.append(1.0 if not r.expected_tools else 0.0)
    return {"overall_precision": correct_calls / total_calls if total_calls else 1.0,
            "avg_task_precision": sum(per_task) / len(per_task)}


def compute_recall(results: List[TaskEvaluation]) -> Dict:
    """Recall = expected tools that were called / all expected tools."""
    total_expected = sum(len(r.expected_tools) for r in results)
    per_task, recalled_total = [], 0
    for r in results:
        if r.expected_tools:
            recalled = min(sum(1 for t in r.actual_tools if is_correct_tool(t, r.expected_tools, r.acceptable_alternatives)),
                           len(r.expected_tools))
            recalled_total += recalled
            per_task.append(recalled / len(r.expected_tools))
        else:
            per_task.append(1.0 if not r.actual_tools else 0.0)
    return {"overall_recall": recalled_total / total_expected if total_expected else 1.0,
            "avg_task_recall": sum(per_task) / len(per_task)}


def compute_avg_tool_calls(results: List[TaskEvaluation]) -> Dict:
    """How many calls per task, and how often that was too few, just right, or too many."""
    counts = {"too_few": 0, "optimal": 0, "too_many": 0}
    for r in results:
        n = len(r.actual_tools)
        key = "too_few" if n < r.optimal_tool_count else "optimal" if n == r.optimal_tool_count else "too_many"
        counts[key] += 1
    total = len(results)
    return {"avg_calls_per_task": sum(len(r.actual_tools) for r in results) / total,
            "efficiency_rate": {k: v / total for k, v in counts.items()}}


def compute_tool_success_rate(results: List[TaskEvaluation]) -> Dict:
    """Share of tool calls that ran without an error."""
    logs = [log for r in results for log in r.tool_call_logs]
    successful = sum(log.success for log in logs)
    return {"overall_success_rate": successful / len(logs) if logs else 1.0, "failed_calls": len(logs) - successful}


def numbers_in(text: str) -> List[float]:
    return [float(n) for n in re.findall(r"\d+(?:\.\d+)?", text.replace(",", ""))]


def compute_attribution(results: List[TaskEvaluation]) -> Dict:
    """Did the final answer actually USE a tool's result? Check the tool's main number appears in it."""
    tool_required = [r for r in results if r.requires_external_data]
    attributed = 0
    for r in tool_required:
        answer_numbers = numbers_in(r.output or "")
        for log in r.tool_call_logs:
            tool_numbers = numbers_in(log.output)
            if tool_numbers and any(abs(tool_numbers[0] - a) < 0.05 for a in answer_numbers):
                attributed += 1
                break
    n = len(tool_required)
    return {"attribution_rate": attributed / n if n else 0.0}


def compute_cost(results: List[TaskEvaluation]) -> Dict:
    total_cost = sum(r.total_cost for r in results)
    successful = [r for r in results if r.task_success]
    cost_per_success = total_cost / len(successful) if successful else 0.0
    classification = "Low" if cost_per_success < 0.001 else "Moderate" if cost_per_success < 0.01 else "High"
    return {"total_cost": total_cost, "cost_per_success": cost_per_success, "cost_classification": classification}


# ---------------------------------------------------------------------------
# 7. Run everything and print the report
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    print(f"Tools: {[t.name for t in tools]}")
    print(f"Running {len(test_scenarios)} scenarios...\n")

    evaluation_results: List[TaskEvaluation] = []
    for i, scenario in enumerate(test_scenarios, 1):
        r = run_evaluation(scenario)
        evaluation_results.append(r)
        print(f"[{i:>2}/{len(test_scenarios)}] [{r.category}] {r.question}")
        for log in r.tool_call_logs:
            args = ", ".join(f"{k}={v}" for k, v in log.parameters.items())
            print(f"        → {log.tool_name}({args})\n          = {log.output}")
        if not r.tool_call_logs:
            print("        → (no tool call)")
        answer = (r.output or "").replace("\n", " ")
        print(f"        answer: {answer[:110]}{'...' if len(answer) > 110 else ''}")
        match = "✅" if sorted(r.actual_tools) == sorted(r.expected_tools) else "❌"
        status = "" if r.task_success else f"   ERROR: {r.error}"
        print(f"        expected {r.expected_tools or 'no tool'} {match}  {r.latency_s:.1f}s{status}\n")

    precision = compute_precision(evaluation_results)
    recall = compute_recall(evaluation_results)
    calls = compute_avg_tool_calls(evaluation_results)
    success = compute_tool_success_rate(evaluation_results)
    attribution = compute_attribution(evaluation_results)
    cost = compute_cost(evaluation_results)
    avg_latency = sum(r.latency_s for r in evaluation_results) / len(evaluation_results)

    summary = pd.DataFrame([
        {"Category": "Tool Invocation", "Metric": "Precision (Overall)",  "Value": f"{precision['overall_precision']:.3f}", "Description": "Correct calls / Total calls"},
        {"Category": "Tool Invocation", "Metric": "Precision (Avg/Task)", "Value": f"{precision['avg_task_precision']:.3f}", "Description": "Average precision across tasks"},
        {"Category": "Tool Invocation", "Metric": "Recall (Overall)",     "Value": f"{recall['overall_recall']:.3f}", "Description": "Expected tools that were called"},
        {"Category": "Tool Invocation", "Metric": "Recall (Avg/Task)",    "Value": f"{recall['avg_task_recall']:.3f}", "Description": "Average recall across tasks"},
        {"Category": "Efficiency",      "Metric": "Avg Calls per Task",   "Value": f"{calls['avg_calls_per_task']:.2f}", "Description": "Mean tool invocations"},
        {"Category": "Efficiency",      "Metric": "Optimal Call Rate",    "Value": f"{calls['efficiency_rate']['optimal']:.1%}", "Description": "Tasks with optimal tool count"},
        {"Category": "Efficiency",      "Metric": "Over-calling Rate",    "Value": f"{calls['efficiency_rate']['too_many']:.1%}", "Description": "Tasks with excess tool calls"},
        {"Category": "Efficiency",      "Metric": "Under-calling Rate",   "Value": f"{calls['efficiency_rate']['too_few']:.1%}", "Description": "Tasks with too few calls"},
        {"Category": "Success",         "Metric": "Tool Success Rate",    "Value": f"{success['overall_success_rate']:.3f}", "Description": "Calls that ran without error"},
        {"Category": "Success",         "Metric": "Failed Tool Calls",    "Value": str(success['failed_calls']), "Description": "Number of failed executions"},
        {"Category": "Success",         "Metric": "Attribution Rate",     "Value": f"{attribution['attribution_rate']:.3f}", "Description": "Answers that used a tool's result"},
        {"Category": "System",          "Metric": "Avg Latency",          "Value": f"{avg_latency:.1f}s", "Description": "Time per task, end to end"},
        {"Category": "Cost",            "Metric": "Total Cost",           "Value": f"${cost['total_cost']:.6f}", "Description": "LLM tokens + tool calls"},
        {"Category": "Cost",            "Metric": "Cost per Success",     "Value": f"${cost['cost_per_success']:.6f}", "Description": "Cost per successful task"},
        {"Category": "Cost",            "Metric": "Cost Classification",  "Value": cost['cost_classification'], "Description": "Low / Moderate / High"},
    ])
    print("=" * 80)
    print("CONSOLIDATED EVALUATION SUMMARY")
    print("=" * 80)
    print(summary.to_string(index=False))

    def short(names):                                # "reorder_point_calculator" -> "reorder_point"
        return ", ".join(n.replace("_calculator", "").replace("inventory_", "") for n in names) or "None"

    rows = []
    for i, r in enumerate(evaluation_results, 1):
        exp_set, act_set = set(r.expected_tools), set(r.actual_tools)
        p = len(exp_set & act_set) / len(act_set) if act_set else (1.0 if not exp_set else 0.0)
        rc = len(exp_set & act_set) / len(exp_set) if exp_set else (1.0 if not act_set else 0.0)
        rows.append({"#": i, "Question": r.question[:42] + "...", "Category": r.category,
                     "Expected": short(r.expected_tools), "Actual": short(r.actual_tools),
                     "Precision": f"{p:.2f}", "Recall": f"{rc:.2f}", "Success": "Yes" if r.task_success else "No",
                     "Tokens": r.input_tokens + r.output_tokens, "Cost": f"${r.total_cost:.5f}"})
    print("\n" + "=" * 100)
    print("PER-TASK DETAILED RESULTS")
    print("=" * 100)
    print(pd.DataFrame(rows).to_string(index=False))
judge_agreement.py (complete file)
judge_agreement.py (complete file)
"""
Can we trust the LLM judge? Compare its verdicts with a human reviewer using Cohen's kappa.
By Shivank Agarwal. No model calls: this only reads a CSV.

How to use:
1. Run prompt_evals_inventory.py      -> prompt_eval_results.csv (the judge's scores)
2. Open annotator.html, upload that CSV, mark each answer 👍 / 👎, click "Download feedback"
                                       -> prompt_eval_results_feedback.csv
3. python judge_agreement.py prompt_eval_results_feedback.csv

The judge "passes" an answer only if every score column is 1. The human label is pass / fail.
"""
import csv
import sys

SCORE_COLUMNS = ["accuracy", "clarity", "completeness",                                  # prompt evals
                 "context_relevance", "answer_groundedness", "answer_correctness"]       # RAG evals


def cohens_kappa(a, b):
    """Agreement between two raters, after removing the agreement expected by chance."""
    n = len(a)
    observed = sum(x == y for x, y in zip(a, b)) / n
    labels = set(a) | set(b)
    chance = sum((a.count(l) / n) * (b.count(l) / n) for l in labels)
    kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0
    return observed, chance, kappa


def describe(k):
    """Common reading of kappa values (Landis & Koch)."""
    for limit, word in [(0, "poor"), (0.20, "slight"), (0.40, "fair"), (0.60, "moderate"), (0.80, "substantial")]:
        if k <= limit:
            return word
    return "almost perfect"


if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "prompt_eval_results_feedback.csv"
    with open(path, encoding="utf-8") as f:
        rows = [r for r in csv.DictReader(f) if r.get("human_label") in ("pass", "fail")]
    if not rows:
        sys.exit("No rows with a human_label of pass/fail. Annotate the file in annotator.html first.")

    scores = [c for c in SCORE_COLUMNS if c in rows[0]]
    judge = ["pass" if all(r[c] == "1" for c in scores) else "fail" for r in rows]
    human = [r["human_label"] for r in rows]

    print(f"File: {path}  ({len(rows)} reviewed answers)")
    print(f"Judge passes an answer when all of these are 1: {', '.join(scores)}\n")

    print("                 Human: pass   Human: fail")
    for j in ("pass", "fail"):
        cells = [sum(1 for x, y in zip(judge, human) if x == j and y == h) for h in ("pass", "fail")]
        print(f"  Judge: {j:<5}   {cells[0]:>10}   {cells[1]:>11}")

    observed, chance, kappa = cohens_kappa(judge, human)
    print(f"\nRaw agreement        : {observed:.0%}")
    print(f"Agreement by chance  : {chance:.0%}   (judge passes {judge.count('pass')}/{len(rows)}, "
          f"human passes {human.count('pass')}/{len(rows)})")
    print(f"Cohen's kappa        : {kappa:.2f}  → {describe(kappa)} agreement")

    disagreements = [(r, j, h) for r, j, h in zip(rows, judge, human) if j != h]
    if disagreements:
        print(f"\nDisagreements to discuss ({len(disagreements)}):")
        for r, j, h in disagreements:
            tag = r.get("prompt_version") or r.get("config") or ""
            print(f"  • [{tag}] {r['question'][:70]}...")
            print(f"      judge: {j:<4} ({r.get('judge_reason', '')})")
            print(f"      human: {h:<4} ({r.get('human_feedback') or 'no note'})")
annotator.html (complete file)
annotator.html (complete file)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Eval Annotator · by Shivank Agarwal</title>
<style>
  :root { --bg:#14161b; --panel:#1d2027; --line:#2c303a; --text:#eceef2; --muted:#9aa1ad;
          --amber:#f5a524; --amber-ink:#2a1a00; --blue:#2f80ed; --green:#27ae60; --red:#e5484d; }
  * { box-sizing: border-box; }
  body { margin:0; background:var(--bg); color:var(--text); font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; }
  .ann { max-width:1100px; margin:0 auto; padding:18px; }
  .top { display:grid; grid-template-columns: 1fr auto; gap:14px; align-items:start; }
  .card { background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:12px 14px; }
  .label { font-size:12px; font-weight:700; letter-spacing:.06em; text-transform:uppercase; color:var(--amber); margin-bottom:6px; display:flex; justify-content:space-between; gap:8px; }
  textarea { width:100%; background:#111318; color:var(--text); border:1px solid var(--line); border-radius:8px; padding:8px 10px; font:inherit; resize:vertical; }
  .btns { display:flex; flex-direction:column; gap:8px; }
  button, .upload { font:600 14px system-ui,sans-serif; border:0; border-radius:8px; padding:9px 14px; cursor:pointer; }
  .blue { background:var(--blue); color:#fff; }
  .ghost { background:transparent; color:var(--text); border:1px solid var(--line); }
  .upload input { display:none; }
  button:disabled { opacity:.4; cursor:not-allowed; }
  .progress { height:6px; background:#2a2e37; border-radius:4px; overflow:hidden; margin:14px 0 6px; }
  .progress > div { height:100%; width:0; background:var(--green); transition:width .2s; }
  .meta { display:flex; justify-content:space-between; color:var(--muted); font-size:13px; flex-wrap:wrap; gap:6px; }
  .chip { display:inline-block; background:#2a2e37; border-radius:999px; padding:1px 9px; font-size:12px; color:var(--text); }
  .main { display:grid; grid-template-columns: 1.25fr auto 1fr; gap:14px; margin-top:12px; align-items:stretch; }
  .query { background:var(--amber); color:var(--amber-ink); border-radius:12px; padding:12px 14px; font-weight:600; }
  .query .label { color:var(--amber-ink); }
  .resp { margin-top:12px; background:#fff7e6; color:#2b2213; border-radius:12px; padding:12px 14px; max-height:340px; overflow:auto; white-space:pre-wrap; }
  .resp .label { color:#8a5a00; }
  details.ref { margin-top:10px; color:var(--muted); font-size:14px; }
  details.ref summary { cursor:pointer; }
  .votes { display:flex; flex-direction:column; justify-content:center; gap:14px; }
  .vote { width:64px; height:64px; border-radius:14px; font-size:30px; background:#2a2e37; border:2px solid transparent; }
  .vote.up.on { background:var(--green); border-color:#bff0d0; }
  .vote.down.on { background:var(--red); border-color:#ffd0d2; }
  .fb textarea { min-height:220px; background:#fff; color:#1b1d22; }
  .nav { display:flex; justify-content:center; gap:10px; margin-top:14px; flex-wrap:wrap; }
  .empty { text-align:center; color:var(--muted); padding:60px 20px; border:1px dashed var(--line); border-radius:12px; margin-top:14px; }
  .toast { position:fixed; bottom:18px; left:50%; transform:translateX(-50%); background:#000; color:#fff; padding:8px 14px; border-radius:8px; opacity:0; transition:opacity .2s; pointer-events:none; }
  .toast.show { opacity:.92; }
  .keys { color:var(--muted); font-size:12px; text-align:center; margin-top:8px; }
  @media (max-width: 760px) {
    .top { grid-template-columns: 1fr; } .btns { flex-direction:row; flex-wrap:wrap; }
    .main { grid-template-columns: 1fr; } .votes { flex-direction:row; justify-content:center; }
  }
</style>
</head>
<body>
<div class="ann" id="ann">
  <div class="top">
    <div class="card">
      <div class="label">Evaluation function description</div>
      <textarea id="annRubric" rows="3" aria-label="Evaluation function description">PASS if a warehouse manager could act on this answer as it is: it is correct, clear, and handles the edge case hidden in the question. Otherwise FAIL, and write down what went wrong.</textarea>
    </div>
    <div class="btns">
      <label class="upload blue" tabindex="0">⬆ Upload agent output<input type="file" id="annFile" accept=".csv,text/csv"></label>
      <button class="blue" id="annDownload" disabled>⬇ Download feedback</button>
    </div>
  </div>

  <div class="progress"><div id="annBar"></div></div>
  <div class="meta"><span id="annPos">No file loaded</span><span id="annDone"></span></div>

  <div id="annEmpty" class="empty">Upload <b>prompt_eval_results.csv</b> or <b>rag_eval_results.csv</b> (made by the eval scripts).<br>Any CSV with a question column and a response column works.</div>

  <div id="annWork" hidden>
    <div class="main">
      <div>
        <div class="query"><div class="label"><span>User query</span><span id="annTag"></span></div><div id="annQuery"></div></div>
        <div class="resp"><div class="label">Agent response</div><div id="annResp"></div></div>
        <details class="ref" id="annRefBox"><summary>Show the reference answer</summary><div id="annRef"></div></details>
      </div>
      <div class="votes">
        <button class="vote up" id="annUp" title="Pass (P)" aria-label="Pass">👍</button>
        <button class="vote down" id="annDown" title="Fail (F)" aria-label="Fail">👎</button>
      </div>
      <div class="card fb">
        <div class="label">Qualitative reviewer feedback</div>
        <textarea id="annNote" placeholder="What exactly is wrong or right? e.g. 'ignores the PO arriving tomorrow'"></textarea>
      </div>
    </div>
    <div class="nav">
      <button class="ghost" id="annPrev">← Previous</button>
      <button class="blue" id="annSubmit">Submit feedback</button>
      <button class="ghost" id="annNext">Next →</button>
    </div>
    <div class="keys">Keys: P = pass · F = fail · ← / → move · Ctrl+Enter = submit</div>
  </div>
</div>
<div class="toast" id="annToast"></div>

<script>
(function () {
  const $ = id => document.getElementById(id);
  let rows = [], cols = [], i = 0, fileName = "agent_output.csv";
  const Q = ["question", "query", "user_query", "q", "input"];
  const R = ["response", "answer", "agent_response", "output", "generated_answer"];
  const REF = ["expected", "reference", "reference_answer", "a"];
  const TAG = ["prompt_version", "config", "variant"];
  const pick = names => cols.find(c => names.includes(c.trim().toLowerCase()));

  // CSV reader that handles quotes, commas and line breaks inside fields
  function parseCSV(text) {
    const out = []; let row = [], f = "", q = false;
    for (let k = 0; k < text.length; k++) {
      const c = text[k];
      if (q) { if (c === '"') { if (text[k + 1] === '"') { f += '"'; k++; } else q = false; } else f += c; }
      else if (c === '"') q = true;
      else if (c === ",") { row.push(f); f = ""; }
      else if (c === "\n" || c === "\r") { if (c === "\r" && text[k + 1] === "\n") k++; row.push(f); out.push(row); row = []; f = ""; }
      else f += c;
    }
    if (f !== "" || row.length) { row.push(f); out.push(row); }
    return out.filter(r => r.some(x => x.trim() !== ""));
  }
  const esc = v => /[",\n\r]/.test(v) ? '"' + String(v).replace(/"/g, '""') + '"' : String(v);

  function load(text, name) {
    const data = parseCSV(text.replace(/^\uFEFF/, ""));
    if (data.length < 2) return toast("That file has no rows.");
    cols = data[0];
    if (!pick(Q) || !pick(R)) return toast("Need a question column and a response column.");
    rows = data.slice(1).map(r => Object.fromEntries(cols.map((c, j) => [c, r[j] ?? ""])));
    rows.forEach(r => { r.human_label = r.human_label || ""; r.human_feedback = r.human_feedback || ""; });
    fileName = name || fileName; i = 0;
    $("annEmpty").hidden = true; $("annWork").hidden = false; $("annDownload").disabled = false;
    show();
  }

  function show() {
    const r = rows[i], qc = pick(Q), rc = pick(R), refc = pick(REF), tagc = pick(TAG);
    $("annQuery").textContent = r[qc];
    $("annResp").textContent = r[rc];
    $("annRefBox").hidden = !refc; if (refc) $("annRef").textContent = r[refc];
    $("annTag").innerHTML = tagc ? '<span class="chip">' + r[tagc].replace(/[<>&]/g, "") + "</span>" : "";
    $("annNote").value = r.human_feedback;
    $("annUp").classList.toggle("on", r.human_label === "pass");
    $("annDown").classList.toggle("on", r.human_label === "fail");
    $("annPrev").disabled = i === 0; $("annNext").disabled = i === rows.length - 1;
    const done = rows.filter(x => x.human_label).length;
    $("annPos").textContent = `Item ${i + 1} of ${rows.length}`;
    $("annDone").textContent = `${done} annotated · ${rows.filter(x => x.human_label === "fail").length} failures`;
    $("annBar").style.width = (100 * done / rows.length) + "%";
  }

  function vote(label) { if (!rows.length) return; rows[i].human_label = rows[i].human_label === label ? "" : label; show(); }
  function submit() {
    if (!rows.length) return;
    rows[i].human_feedback = $("annNote").value.trim();
    if (!rows[i].human_label) return toast("Pick 👍 or 👎 first.");
    toast("Saved"); if (i < rows.length - 1) i++; show();
  }
  function move(d) { if (!rows.length) return; rows[i].human_feedback = $("annNote").value.trim(); i = Math.min(rows.length - 1, Math.max(0, i + d)); show(); }
  function download() {
    rows[i].human_feedback = $("annNote").value.trim();
    const header = [...cols.filter(c => c !== "human_label" && c !== "human_feedback"), "human_label", "human_feedback"];
    const csv = [header.map(esc).join(",")].concat(rows.map(r => header.map(c => esc(r[c] ?? "")).join(","))).join("\n");
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob([csv], {type: "text/csv"}));
    a.download = fileName.replace(/\.csv$/i, "") + "_feedback.csv";
    document.body.appendChild(a); a.click(); a.remove();
  }
  function toast(msg) { const t = $("annToast"); t.textContent = msg; t.classList.add("show"); clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove("show"), 1200); }

  $("annFile").addEventListener("change", e => { const f = e.target.files[0]; if (!f) return; f.text().then(t => load(t, f.name)); e.target.value = ""; });
  $("annUp").onclick = () => vote("pass"); $("annDown").onclick = () => vote("fail");
  $("annSubmit").onclick = submit; $("annPrev").onclick = () => move(-1); $("annNext").onclick = () => move(1);
  $("annDownload").onclick = download;
  document.addEventListener("keydown", e => {
    if (!rows.length) return;
    if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) return submit();
    if (e.target.tagName === "TEXTAREA") return;
    if (e.key === "ArrowLeft") move(-1); else if (e.key === "ArrowRight") move(1);
    else if (e.key.toLowerCase() === "p") vote("pass"); else if (e.key.toLowerCase() === "f") vote("fail");
  });
  window.annotatorLoad = load;      // lets a page preload rows: annotatorLoad(csvText, "name.csv")
})();
</script>
</body>
</html>
README.md
README.md (complete file)
# Component evals and LangGraph: code for the "Evaluating your Agent" lecture

By Shivank Agarwal. Every file uses OpenAI `gpt-6-luna` (and `text-embedding-3-small` for search).

## Setup

```bash
pip install -r requirements.txt
cp .env.example .env        # then paste your OpenAI key into .env
```

## Files

| File | What it evaluates | Output |
|---|---|---|
| `langgraph_router.py` | A LangGraph router that sends each question to a reorder, forecast or supplier specialist | Route + answer per question |
| `prompt_evals_inventory.py` | Prompt Version 1 vs Version 2, scored by an LLM judge on Accuracy, Clarity, Completeness | Pass rates + `prompt_eval_results.csv` |
| `rag_evals_inventory.py` | Three RAG setups (k = 1, 2, 3 and three prompts) on Recall@k and three judge metrics | Comparison table + `rag_eval_results.csv` |
| `tool_evals_inventory.py` | A tool-calling agent on 12 scenarios: precision, recall, calls per task, success, latency, cost | Summary + per-task tables |
| `annotator.html` | Human review screen: open in a browser, upload a results CSV, mark 👍 / 👎, download feedback | `..._feedback.csv` |
| `judge_agreement.py` | Does the LLM judge agree with your review? Cohen's kappa + the disagreements | Agreement report |

## A full loop

```bash
python prompt_evals_inventory.py                 # writes prompt_eval_results.csv
# open annotator.html, upload that CSV, review, click "Download feedback"
python judge_agreement.py prompt_eval_results_feedback.csv
```