7
Test Cases
v1
71%
Accuracy (Q1–7)
v1
—
Gen (Q8–19)
untested
0%
Slack UX
not started
Build Log — April 2026

Nicholas Bray Langchain Assessment: Building a Knowledge Agent

Using agents to build and evaluate agents.
8 iterations of qabot, and a lesson on overfitting.

The Assignment

I was given a SQLite database of B2B enterprise customer data and asked to build an AI agent that could answer natural language questions about it. The agent had to be connected to a Slack channel — users would ask questions in Slack and receive answers in-thread, sourced directly from the database. No pre-written queries, no hardcoded lookups: the agent had to figure out what to retrieve and how to answer on its own.

Phase 1 — Foundation

Database Exploration

The dataset was a SQLite database: 50 B2B enterprise customers across four regions, each with active support scenarios, implementation records, and a trail of artifacts — call transcripts, internal Slack threads, planning documents, and design reviews.

The schema had real relational depth: scenarios → customers → implementations → artifacts. An FTS5 index already existed on artifacts_fts, covering title, summary, and content_text. The artifacts themselves ranged from 300 to 1,500 tokens each — small enough to pass full content to an LLM without chunking.

-- Core schema, simplified
customers (customer_id, name, region, industry, account_health, crm_stage)
scenarios (scenario_id, customer_id, title, status, opened_date)
implementations (implementation_id, customer_id, product_id, contract_value)
artifacts (artifact_id, scenario_id, artifact_type, title, summary, content_text)
artifacts_fts (FTS5 virtual table — title, summary, content_text)
competitors (competitor_id, name, pricing_tier, strengths, weaknesses)
employees (employee_id, name, role, region)
Key decision

I decided to use the existing FTS5 index as the primary retrieval layer. The domain vocabulary (product names, customer names, component identifiers like EN-RULES-ENGINE) was precise enough that BM25 keyword matching could handle most queries without additional embedding infrastructure.

Phase 2 — Infrastructure

Wiring Up Slack

Before any agent logic, the Slack integration needed to be solid. The first problem: Slack requires a 200 response within 3 seconds, but LLM + SQL retrieval took several seconds at minimum. The naive approach — await the agent, then respond — would cause Slack to retry the request, producing duplicate replies.

The fix was to return 200 immediately, then hand the event off to an asyncio.create_task() background task before the agent ran. Separating the acknowledgment from the work was the only safe pattern.

# Slack event handler — immediate ack, background agent async def handle_event(req): body = await req.json() verify_signature(req) # HMAC-SHA256 + 5min replay guard asyncio.create_task( # fire and forget run_agent(body["event"]) ) return JSONResponse({"ok": True}) # < 3s, always
Threading model

All bot replies used thread_ts — responses appeared in threads, not the channel. Each thread was also the conversation history key, scoping memory naturally per session.

Security

HMAC-SHA256 signature verification with hmac.compare_digest (timing-safe) + 5-minute replay window on every request. No arbitrary POSTs could trigger the agent.

Phase 3 — Eval Infrastructure

Building the Judge

To iterate faster, the eval loop needed to be automated. This meant three things: ground truth answers, a semantic judge, and source retrieval checking.

The 7 benchmark questions came with provided answers, which became my ground truth. What I still needed to determine was which artifacts supported each answer — I read through the database directly to map each question to its source documents, expected customers, and key facts the agent would need to surface.

# Eval harness — three signals per question
1. correctness = llm_judge(agent_answer, reference_answer) # 0.0–1.0
2. sources_found = customer_name_in(agent_answer, expected_sources)
3. tool_trace = [(name, args, result), ...] # ordered
# Judge model: gpt-4o-mini (cheaper than gpt-4o, sufficient for comparison)
Phase 4 — v1

The First Agent

The architecture was a LangGraph ReAct loop: a StateGraph with two nodes — call_model and call_tools — cycling until the model stopped requesting tools. GPT-4o at temperature 0.

The initial tool set was purpose-built for relational navigation: search_artifacts for FTS queries, artifact_full_text to fetch full content by ID, customer_artifacts to list all artifacts for a customer, scenario_summary for a one-shot customer overview, and sql_query for structured filtering.

v1 — first eval run
71%
v1
71%

Easy questions: 4/4 ✓  ·  Hard questions: 1/3  ·  Avg score: 0.63  ·  Avg tool calls: 2.4

The easy questions all passed. The hard questions exposed a single failure mode: the agent reached for sql_query first and quit after one empty result.

Primary failure mode — v1

For competitive risk and cross-account synthesis questions, the structured columns (crm_stage, contract_value) contained no signal. The answer lived in artifact content. A single SQL query returning zero rows was not a signal that the data didn't exist — it was a signal that I was asking the wrong layer.

Phase 5 — Tool Iteration

Climbing to 100% on the Original 7

With the eval harness in place, each version could be measured precisely. v3 fixed the tool-call explosion by adding find_pattern_across_customers — a grouped FTS tool that returns a count and customer list before surfacing individual artifacts. v4 added a more explicit system prompt describing the full schema.

Version progression — original 7 questions
100%
v1
71%
v3
86%
v4
100%

The v4 system prompt had grown to include the full table schema, explicit tool-selection rules, and step-by-step recipes for the three hard question types. The agent could now navigate all seven questions correctly.

search_artifacts
→
artifact_full_text
→
find_pattern_across_customers
→
sql_query
→
customer_artifacts

Seven tools total — enough to handle every question in the known set. But I had only seen seven questions.

Phase 6 — The Trap

Oops I Overfit the Tools

Taking a deeper look at v4, which was finally answering all 7 questions. It had 10 rules. And those 10 rules mapped nearly 1:1 to the 7 benchmark questions. A classic ML problem, I was overfitting my model to the question set.

Rule The question it was written to fix
Rule 1: Geographic segment → list_customers() firstq6 (NA West taxonomy)
Rule 2: Competitive risk → never sql_query aloneq5 (BlueHarbor / NoiseGuard)
Rule 3: Pattern → find_pattern_across_customers() 3× with synonymsq7 (Canada approval bypass)
Rule 7: "widespread?" → always grouped searchq7 phrasing
Rule 9: Preferred tool sequencesGeneral patch for q5/q6/q7 failures
The problem

The rules read like a post-mortem fix list for these specific questions, not a principled retrieval strategy. The Nordics region (13 customers) and ANZ region (12 customers) were completely untested — 25 of 50 customers with zero coverage. I didn't know if the agent would work at all on questions I hadn't seen.

Phase 7 — v5

Expanding the Problem Set

I had Claude Code generate twelve new benchmark questions to cover the unexplored regions of the database: cross-region diagnosis, multi-account root cause patterns, action item owners with due dates, and competitor profiles.

The eval suite grew from 7 to 19 questions. The provided questions (Q1–7) held at 100%; the 12 new synthetic questions scored 58% — but that number was honest. The agent was running on genuinely new questions for the first time.

v5 — accuracy vs generalizability
100% / 58%
Accuracy — Q1–7 (provided)
Acc
100%
Generalizability — Q8–19 (synthetic)
Gen
58%
Failure: q13 (commercial terms)

Agent never called artifact_full_text. The concession details sat in an internal_document — without reading it in full, the agent answered from summaries and scored 0.00.

Failure: q17 (multi-account)

9 tool calls, still no synthesis. FTS5 AND semantics meant a query with all three customer names returned zero rows — no single artifact mentioned all of them.

The tool library had a 7-tool surface. It worked — but seven tools across four use cases was starting to feel like a long menu. Every new question type might require a new tool. I knew there had to be a more composable approach.

Phase 8 — v6

Simplifying to 3 Primitives

My hypothesis: seven tools could be collapsed to three composable primitives. search() for FTS with inline snippets. read() for batch full-text fetch by ID. lookup() for structured row queries. The system prompt shrank from ~800 words to ~250.

v6 — accuracy collapsed

Accuracy on Q1–7 collapsed from 100% → 43%. Generalizability on Q8–19 dipped from 58% → 50%. Six previously-correct cases regressed. The simplification was structurally right but had three bugs: (1) a SQLite alias error broke every search() call silently — the agent received no results and hallucinated. (2) Removing customer_artifacts forced reliance on FTS vocabulary matching, which failed on unusual query terms. (3) 400-char snippets trained the agent to stop reading early.

Accuracy — Q1–7 (provided)
v5
100%
v6
43%
Generalizability — Q8–19 (synthetic)
v5
58%
v6
50%

The v6 experiment confirmed two things: the 3-primitive structure was correct, and the regression was not caused by simplification itself. It was caused by bugs introduced during the refactor — and one genuine design gap.

What actually improved

q16 (action item owners): 0.20 → 1.00. The new artifact_type filter directly targeted Slack threads — the right source. q7 (Canada bypass): same score in 1 call instead of 4. The primitives were more composable for cases that fit them well.

Phase 9 — v7

Bug Fixes & Even More Flexible Tools

The v6 failures had known root causes. I fixed them, and the 3-primitive architecture recovered — and surpassed v5 on generalizability.

ADDITION: sql_query tool

I restored sql_query() as a safety valve — a tool that allowed the agent to reason through what data it needed and generate its own SQL to extract it. More flexible than any of the structured retrieval tools.

v7 — after fixes
86% / 83%
Accuracy — Q1–7 (provided)
v6
43%
v7
86%
Generalizability — Q8–19 (synthetic)
v6
50%
v7
83%

The final tool surface: search / read / lookup + sql_query as a safety valve for exact column-value filtering and joins that lookup() cannot express. Average tool calls dropped from 3.4 (v5) to 2.2 — more efficient and more accurate.

Phase 10 — v8

Adding a Thinking Step

Hard questions — competitor defection risk, cross-account classification, multi-account root cause — required more than one retrieval hop. The agent often anchored on the first search result and stopped. A think() tool — a scratchpad with no DB access — gave it a place to plan before committing to tools.

# think() — no DB query, just reasoning space think(reasoning="This question asks for a competitor defection risk. I need to:
1) identify the competitor via lookup,
2) search by competitor name with group_by_customer,
3) read the top artifact to find the commitment at stake,
4) search for the specific delivery plan by name.
Start with lookup('competitors')."
)

v8 also removed question-specific rules, in a continuing attempt not to overfit. I replaced a tool that was very question-directed with an abstract recipe: derive search keywords from the commitment identified after reading the call artifact. The model still finds the right document — but without leaking test case vocabulary into the system prompt.

Questionv7 scorev8 scoreChange
q16 (action item owners)0.601.00 ✓+0.40
q19 (remediation timeline)0.401.00 ✓+0.60
q6 (NA West classification)ERR0.80 ✓fixed
q17 (multi-account pattern)ERR0.80+fixed
q18 (escalation recovery)0.600.80+0.20
q13 (commercial terms)0.60 ✗0.60 ✗unchanged
The overfitting trap

A Lesson On Overfitting


The early tool designs were shaped by the 7 provided questions — and it showed. Each iteration added a specialized tool or filter to solve the exact query in front of me: a customer_artifacts shortcut here, a region-specific helper there. The agent got better at those 7 questions and worse at everything else. It had learned the test, not the database.

Stepping back and asking what does this database actually need? — not what do these questions need? — forced a cleaner answer: search by text, fetch by ID, filter by column, escape to raw SQL. Four primitives that composed into any query, not seven tools that each solved one. The score on the provided questions went up anyway. Generalization came for free.

Phase 11 — Slack UX

Improve Slack UX

The agent could take 10+ tool calls on hard questions — 15-30 seconds of silence from Slack's perspective. Users had no way to know if the bot was thinking or broken.

The fix was progressive updates: as each tool call completed, the bot edited its original message (🤔thinking...) with a summary of the artifact or result just retrieved. Hard questions showed a live trace of retrieval steps, collapsing into a final answer when the agent finished.

# Tool call trace in thread — editing a single message
# Step 1 (after search):
🔍 Searching for competitor risk signals...
→ Found 4 artifacts across 3 customers
# Step 2 (after read):
📄 Reading BlueHarbor Logistics call transcript...
→ Proof-of-fix milestone: query log + A/B test (March 15)
# Final:
BlueHarbor Logistics is the highest defection risk.
NoiseGuard (low-cost dedup layer) was offered if Northstar
can't demonstrate relevance improvement by March 15...
Before

30 seconds of silence, then a wall of text. No indication the bot was working. Users refreshed or re-sent the question.

After

Live updates every few seconds as artifacts were retrieved. A single clean message that rewrote in place. Transparent reasoning without chat spam.

Phase 12 — Security Posture

Agent Security

The agent's tools had a well-defined schema — they needed to, for the model to use them. But that schema included table names, column names, and join paths. I wanted to understand the attack surface.

QuestionAnswerRisk
Can you get the tool schema? Yes Medium — by design, visible to the model
Can you use that to infer the DB schema? Yes Medium — table names appear in docstrings
Can you drop the customer DB? No Low — sql_query enforces read-only
Can you extract all customer data? Yes (slowly) Medium — no row-level rate limiting
Guardrails implemented

Read-only enforcement: sql_query() wrapped every statement in a SELECT-only regex check before execution. Any statement containing INSERT, UPDATE, DELETE, DROP, or CREATE was rejected before hitting SQLite.

Since I exposed a tool for flexible SQL queries, read-only protection was necessary for database integrity. If the database were accessible from anywhere else, I would have wanted to hide the schema much more aggressively.


Results

Where I Ended Up

19
Test Cases
7 original → 19 with Nordics + ANZ
100%
Accuracy (Q1–7)
7/7 on provided questions, avg score 0.83
83%
Generated (Q8–19)
10/12 on synthetic questions (unseen regions)
4/4
Slack UX
Ack, threads, traces, live editing

I was satisfied with the final performance. It was only knowable because I built an eval harness with a judge architecture and tracked metrics across every iteration.

Key insight

The best accuracy (84%) used fewer tools than v5 (2.2 avg calls vs 3.4) while covering a larger and harder question set. Composable primitives + a thinking step outperformed a larger specialized tool library — once the bugs were fixed.

Remaining open problems

q13 (numeric threshold extraction): The model read the correct artifact but paraphrased exact thresholds instead of quoting them verbatim. The "report verbatim" instruction didn't fire for scoring rules and commercial SLAs.

q17 (multi-account pattern): The model solved it in targeted runs but hit the 10-call limit in full end-to-end runs. The think() tool increased planning calls. A harder budget constraint or an explicit "search once grouped, then batch read all three" recipe would address it.