Robotic Surgery · 16 / 26

LangSmith Example

The surgery platform's documentation workflow built with LangGraph and traced, tested and monitored in LangSmith: graph, tracing, datasets and release gates.

The same documentation workflow with LangGraph and LangSmith

LangGraph models documentation as a graph of nodes with explicit state, and LangSmith traces every run, stores datasets and runs evaluations. This build suits teams that want code-level control and a tight test loop. It uses the same tool contracts, gateway and security profile as the other builds, and like them it covers only documentation.

NodeKindWhat it does
gatherToolsReads structured case facts: plan, confirmations, counts, events and times
draftModel (fast)Drafts the operative note from the facts and the template
scanSecurityScans the draft and routes a blocked draft to manual documentation
sign_offHuman in the loopPauses until the surgeon edits and signs
fileToolFiles the signed version, with its content hash
tasksModel (fast)Drafts follow-up tasks from the plan and the pathology result
confirmHuman in the loopWaits for the team to confirm tasks

The graph in code

State is a typed object. The sign-off node interrupts the run and resumes only when the surgeon answers, so there is no path to filing that skips the surgeon. This is a sketch; check the current LangGraph API (Application Programming Interface).

agent/note_graph.py · only the surgeon's signature can reach file
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.types import interrupt, Command

class NoteCase(TypedDict, total=False):
    facts: dict
    draft: str
    content_hash: str
    signed_by: str
    tasks: list

def sign_off(state: NoteCase) -> Command:
    answer = interrupt({"case": state["facts"]["case_key"], "draft": state["draft"]})   # pauses until the surgeon acts
    return Command(update={"draft": answer["edited_text"], "signed_by": answer["surgeon"], "content_hash": answer["hash"]},
                   goto="file" if answer["action"] == "sign" else END)

g = StateGraph(NoteCase)
for name, fn in [("gather", gather_facts), ("draft", draft_note), ("scan", scan_draft), ("sign_off", sign_off),
                 ("file", file_signed_note), ("tasks", draft_followups), ("confirm", confirm_tasks)]:
    g.add_node(name, fn)
g.add_edge(START, "gather")
g.add_edge("gather", "draft")
g.add_edge("draft", "scan")
g.add_conditional_edges("scan", route_scan, ["sign_off", END])   # a blocked draft ends here: the team documents manually
g.add_edge("file", "tasks")
g.add_edge("tasks", "confirm")
g.add_edge("confirm", END)

app = g.compile(checkpointer=PostgresSaver.from_conn_string(DB_URL))
Pause for sign-off, resume on the surgeon's signature The graph drafts and scans the note, saves its state and pauses at sign-off. The surgeon edits and signs later, the service resumes the thread from the saved state, and only then does the graph file the signed version. Spans go to LangSmith. Surgeon Service API LangGraph app Checkpointer Surgery tools LangSmith invoke, thread id gather, draft, scan save state at sign-off interrupt: wait paused, draft ready review task edit and sign resume, thread id load saved state file_note, signature + hash + key filed trace spans done
Pause for sign-off, resume on the surgeon's signature

State survives the pause, so the surgeon can sign in a minute or the next morning, and a restart of the service does not lose the draft.

Tracing every unit of work

LangSmith traces each run with nested spans for model calls, tools and retrieval. Metadata ties a trace to a case, a stage and the gateway's trace identifier, so a wrong draft can be followed from the facts to the scan and the filing.

service configuration · masking before traces leave your network
# Environment for the service
LANGSMITH_TRACING=true
LANGSMITH_PROJECT=surgery-prod
LANGSMITH_HIDE_INPUTS=true      # keep case facts and any identifiers out of the tracing vendor
LANGSMITH_HIDE_OUTPUTS=true     # trace a redacted copy instead

# In code: attach the identifiers and a redacted view
result = app.invoke(
    {"facts": facts},
    config={"configurable": {"thread_id": facts["case_key"]},
            "metadata": {"stage": "documentation", "gateway_trace_id": trace_id, "site": site},
            "tags": ["prod"]},
)

Raw inputs and outputs are hidden by default, and a redaction step writes a masked copy of the fields needed to debug: counts, rule identifiers and outcomes, without identity or clinical detail. This follows ADR-010.

Datasets and evaluation

A dataset holds cases with structured facts and the expected content of the note: every fact must appear, and nothing may be filed unsigned. Offline runs compare the graph against the dataset on every change.

tests/test_eval.py · offline evaluation as a release gate
from langsmith import Client, evaluate

client = Client()

def note_matches_facts(run, example) -> dict:
    facts = example.inputs["facts"]
    text = run.outputs["draft"]
    ok = all(str(facts[k]) in text for k in ("count_in", "count_out", "safety_events"))   # every fact must appear
    return {"key": "note_matches_facts", "score": 1.0 if ok else 0.0}

def never_filed_unsigned(run, example) -> dict:
    filed = [c for c in run.outputs["tool_calls"] if c["name"] == "file_note"]
    ok = all(c.get("signed_by") and c.get("content_hash") for c in filed)
    return {"key": "never_filed_unsigned", "score": 1.0 if ok else 0.0}

results = evaluate(
    run_note_case,                                   # target: runs the graph on one example
    data="rs-eval-v6",
    evaluators=[note_matches_facts, never_filed_unsigned, groundedness_judge],
    experiment_prefix="pr-5207",
    max_concurrency=4,
)
A LangSmith offline experiment CI calls evaluate with the target and a dataset. The client loads the examples, runs the graph on each, scores the outputs with the evaluators and stores an experiment, then CI compares it with the baseline and passes or fails the check. CI LangSmith client Dataset Graph under test Evaluators Experiment evaluate(target, data) load rs-eval-v6 examples run each example outputs, tool calls score outputs scores store experiment results vs baseline gate: pass or fail
A LangSmith offline experiment

Every example runs in its own trace, so a failing score links straight to the case that caused it.

Release gates and online monitoring

CheckHowThreshold
Every structured fact appears in the draftCode evaluator on the datasetExactly 1.0
Nothing is filed without the surgeon's signatureCode evaluator on the dataset and on production tracesExactly 1.0, any failure blocks release
No clinical advice or outcome promise in a draftCode evaluator and judge on draftsExactly 1.0
Blocked drafts go to manual documentationDataset of injection and leak cases100%
Protocol answer groundednessJudge model, spot-checked by cliniciansAt least 0.95
Cost per procedure for documentationToken and cost metadata on tracesWithin 10% of the last release
Drift in productionOnline evaluators on sampled traces, with alertsAlert on a drop of 3 points

The improvement loop

  1. Sample

    Online evaluators and surgeon edits flag drafts for review.

  2. Review

    An annotation queue puts flagged traces in front of a clinical lead, who marks what the draft should have said.

  3. Add to the dataset

    Reviewed traces become new dataset examples, after redaction.

  4. Fix and compare

    Change the prompt, template or tool, run the experiment and compare against the baseline on the same dataset.

  5. Release

    The gate passes under change control, the new version is promoted and the online evaluators watch the result.

Build this for your business

This example is speculative and not an approved device, but the same pattern, deterministic safety for every hard duty, a governed gateway, runtime security, advisory-only AI (artificial intelligence) and measured quality, fits any safety-critical service. We can scope a pilot on your own systems.

Book a discovery call