Skip to content
← All work

Case study 05

Denning AI

A legal-AI assistant for Kenyan practice. A deterministic router decides when to retrieve, so research questions cannot skip the law.

Stack
PythonLangGraphLangChainPydanticgRPCLangGraph CloudOpenAIAmazon S3SQLite FTS5LangSmith
Code
Private repository, code on request
Sections
Context · The problem · Design · Guardrails · Evals and results · A failure I handled · Stack · Links

Context

Denning is a legal-AI platform for Kenyan legal practice, built at LSL, my own consultancy. It has a global assistant for research and drafting, and a case-file assistant that knows one matter’s parties, procedure, deadlines, tasks and diary. A Go backend owns the case data, a web frontend renders the chat, and Python workers run document jobs.

Denning AI v2 is my rebuild of the LangGraph layer between them. Before porting anything I audited the first generation, resolved nine entanglements, and dropped about 4,000 lines of dead code. The rule for the port: input and output shapes and the SSE stream stay identical, because the frontend, backend and workers depend on them. Everything between those seams is new.

The problem

A legal assistant that answers from training data sounds right, cites nothing, and cannot be checked. That set three requirements. Research questions must always reach retrieval. Citations in a draft must come from what retrieval returned. And anything the assistant says it changed on a case must match what the backend actually stored.

Design

  • Two chat graphs, one shape. denning_global serves the assistant page. denning_case_file serves a case page and adds a pre-router chain that loads the case from Go, captures frontend action metadata and tracks proactive updates. Both use the same re-entrant router loop.
  • Deterministic routing. The router runs three phases: frontend action metadata, then keyword rules, then a small structured-output intent classifier that returns an ordered plan. Specialists edge back to the router, which pops the next step until the plan is empty, then hands off to one general agent that writes the reply. A hop cap of 4 stops runaway loops.
  • Specialists. The case graph has research, case drafting, procedures, mutations, tasks and notes, and diary. Each is a LangChain v1 create_agent with its own middleware and a LangSmith Hub prompt. Writes go to the Go backend through typed gRPC wrappers.
  • One envelope per turn. A single compose_envelope node reads state and emits exactly one terminal event.
  • Retrieval. The research path runs a deterministic retrieval plan over separate surfaces: a curated, enriched set of 191 Kenyan cases ranked by a fused score (semantic, issue-tag match, court level), landmark cases injected as a safety net, a markdown legal wiki of statutes and doctrine synced from S3, a SQLite FTS5 BM25 index over a long-tail judgment archive, and web search last. Web results never outrank curated cases. The first generation used Pinecone; v2 does not.
  • Worker graphs. Intake extraction, document analysis, template extraction, cause suggestion, binding-case suggestion and procedure analysis run as separate graphs that the Python workers call. Intake, document analysis and template extraction each became one structured-output LLM call.
  • Procedure rules in code. A pure function computes the current stage, missing documents, deadlines and priority from the case and the procedure template. The LLM only narrates the result.

Guardrails

  • No skip-retrieval branch. Routing is a graph decision, not a model choice. A research question goes to the research agent because the router has nowhere else to send it.
  • Citation guards. A pure module drops citations that cannot exist: a Supreme Court of Kenya decision before 2010, an eKLR citation before 2003, an EACA report outside the years it was published. Both drafters run their output through it.
  • Grounding checks. The cross-specialist journey checks that every citation in a drafted document traces back to an authority the research turn returned.
  • Client data. The drafting prompt renders firm letterhead details but omits client identifiers such as national ID and phone unless the document type requires them. A journey tests both sides: a Computation of Loss must omit them, a Plaint must include them.
  • Prompt injection. After a stress test, the intent classifier short-circuits jailbreak phrasing, the general agent has a fixed refusal shape, and the mutations specialist refuses to call any write tool on an injected payload.
  • Sensitive case fields are staged. Enrichment writes missing values directly, but changes to cause of action, court, judge, jurisdiction or opposing party become suggestions a lawyer accepts.

Evals and results

  • Router journey. A 25-prompt validation against the real classifier routed 18 of 18 case-mode prompts and 7 of 7 global-mode prompts correctly.
  • Retrieval rounds. On a 15-query set, the retrieval router first failed to infer a legal issue on 9 queries, including natural phrasings like “employee dismissed without hearing”. After weighted token overlap and a synonym map it failed on 1, against a target of 2 or fewer. Landmark cases then appeared in 11 of 11 answers where landmark coverage existed (11 of 15 overall).
  • Lawyer journeys. Persona-driven scripts run each specialist against the real backend with hard checks. In one, the drafter cited only Cap. 22 and Cap. 23, both present in the research results.
  • Contract and unit tests. The repo has 113 tests, including envelope shapes, SSE events, each specialist’s I/O and the citation guards.
  • Live sweep. A browser run of the journeys against the deployed graph found 7 bugs, 5 patched at the time. My verdict was “not yet shippable to general users”.

What is not measured: the scored LangSmith eval dataset covers only the memory specialist (7 examples) and runs nightly in report-only mode. There is no scored eval of answer quality for research or drafting, no measure of citation accuracy beyond the journey checks, and no latency or cost figures in the repo.

A failure I handled

For a while the global assistant used a single “chief” agent: one ReAct loop holding four tools, including legal research. A live trace for “What is murder under Kenyan law?” came back with fluent prose and research: null. The chief had decided the question was answerable from training. It cited no statute, no section 203 of the Penal Code, and no authorities.

I treated this as a shape problem, not a prompt problem. Tool skipping was a valid action for the chief, so any prompt fix would leave the next phrasing to slip through. I wrote an architecture pivot doc, deleted the chief shell and its tool wrappers, and went back to the deterministic three-phase router with specialists as graph nodes.

The same pattern showed up at smaller scale. The task tools reported success while the backend stored 0 tasks, because tasks without an assignee were silently dropped. The fix defaults the assignee to the requesting user. The mutations journey now prints every tool result and flags any turn where the agent claims a filing was marked while the backend recomputed 0 stages.

Stack

Python, LangGraph and LangChain v1 (create_agent, middleware), Pydantic, LangGraph Cloud, gRPC and protobuf to a Go backend, OpenAI models, Amazon S3, SQLite FTS5 with BM25, Redis, Tavily web search, LangSmith for prompts, traces and evals.

Private repositories, proprietary to LSL.

Next case study

Hedge Fund

A 13-seat AI investment committee for Nairobi Securities Exchange stocks. A deterministic risk gate sizes every trade, and nothing executes without my approval.

Read it →