← All AI Engineer talks

AI Engineer World's Fair 2026

AI System Design: From Idea to Production

Read the talk

AI System Design: From Idea to Production

A health insurance claims review system shows how product requirements determine data pipelines, model autonomy, human review, evaluation, and the work needed before production.

From a talk by Apoorva Joshi

Before you start: Basic familiarity with LLMs, embeddings, and retrieval will help; no healthcare or MongoDB expertise is required.

What makes an AI-generated application safe to ship?

If an AI coding tool can build an application, why spend time designing it first? For a low-stakes experiment, where you can inspect the output and easily tell whether it is right, generating code and trying it can work well. The difficulty starts when other people depend on the result and mistakes have consequences. Apoorva Joshi points to talks from Anthropic and OpenAI to emphasize that enthusiasm for AI coding does not remove the need to define what the software should do.

The specification must define the product requirements, system design, and evaluation criteria. Those three pieces give a coding assistant a target and give its human collaborators a way to judge the result. Writing code faster is useful only if the application implements the right behavior.

Slide titled “Specs are the new code” with three stacked boxes labeled Evaluation criteria, System design, and Product requirements.
Specs are the new code: evaluation criteria, system design, and product requirements.
0:460:57
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

0:46 · section reference included

Follow a claim through four design phases

The design process has four phases, with each supplying decisions needed by the next:

  1. Product requirements: identify the users, the problem, and the constraints.
  2. System design: choose the data, architecture, and patterns that satisfy those requirements.
  3. Evaluation and monitoring: establish whether the system works before launch and continues working afterward.
  4. Optimization: improve accuracy, cost, latency, and reliability before shipping and as production exposes gaps.

Consider an internal health insurance claims review system. A medical reviewer must cross-reference clinical guidelines, insurance coverage policies, and patient history to determine whether a treatment, procedure, or medication is covered. Publicly funded healthcare systems also distinguish between covered and uncovered care, so the underlying review problem is not limited to private insurance. The goal is to use AI to simplify the medical reviewer's work. In the fictitious MDB Health example, the scope is the internal review system, not the external claim-submission process.

Background slide with two text panels explaining medical claims review and an internal system for fictitious insurer MDB Health, with external claim submission out of scope.
Background and scope for MDB Health’s internal claims review system.
1:492:07
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

1:49 · section reference included

Quantify the problem and bound the system

Start with a business problem that names the users, describes their current situation, and quantifies their pain. Do not prescribe an agent or a multi-agent architecture yet. In Joshi's hypothetical MDB Health example, medical reviewers average two days per claim review, described as four times the non-urgent industry standard and twelve times the urgent standard. These comparisons are assumptions in the example, not established industry benchmarks. The consequence is concrete: delays in review can postpone patient care, particularly time-sensitive treatment. This is a focused problem with a measurable baseline, while leaving the solution open.

Next, collect the constraints that determine what the system is allowed to do. Regulatory requirements, restrictions on data movement, and vendor procurement approvals can rule out an otherwise attractive architecture. MDB Health's example constraints are:

  • Data boundary: patient data must remain in the approved cloud environment.
  • Model availability: only models available in that cloud may be used.
  • Complex cases: a senior physician must review them.
  • Denials: a human reviewer must review every proposed denial.

These requirements establish limits on automation before any model or framework is selected.

Performance requirements belong in the same early conversation. How quickly must the system respond? What is the monthly LLM inference budget? What uptime SLA must it meet? A system with a strict response deadline or spending ceiling has a different design space from one with room for slower, more expensive processing.

AI's role can then be described along three independent dimensions:

DimensionMDB Health choiceReason
Critical or complementaryComplementaryReview already works without AI, but slowly.
Reactive or proactiveReactiveA submitted claim triggers processing.
Level of autonomyAt most semi-autonomousSpecified cases require human review.

The human-review requirements are part of the product contract, not optional exceptions to an otherwise autonomous system.

Choose one or two success metrics tied directly to the business problem. Joshi's proposed target is to reduce average urgent-claim review time from two days to one hour within ninety days of launch. It is specific, measurable, relevant, and time-bound; its proposed basis for achievability is faster information gathering and faster initial recommendations. This is a launch objective, not a reported outcome.

3:383:46
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

3:38 · section reference included

Make the evidence available and keep it current

With the requirements established, the first design question is data access. What information does the application need, where does it reside, and can the system consume its raw format? Clinical guidelines describe appropriate care for a condition. MDB Health's coverage policies describe what the insurer will pay for. Patient claims history supplies previous conditions, procedures, and the dates on which they occurred. Assume the guidelines and policies are PDFs in Confluence, while processed claims are stored in MongoDB.

The ingestion pipeline must keep pace with source changes. Otherwise, even a well-behaved model can make recommendations using stale evidence.

SourceIllustrative update pattern
Clinical guidelinesAnnually
Internal coverage policiesQuarterly
Patient claims historyWhenever a claim is processed

Joshi connects the one-hour urgent-review objective to a possible hourly refresh of claim history. The design dependency matters more than the particular schedule: a source's update frequency and the application's freshness needs determine when its processing pipeline must run.

Long guideline and policy documents need preparation for retrieval. Chunk the documents, embed their chunks, and extract metadata such as procedure names and publication dates. Patient history is already structured in MongoDB, so its preparation is different: remove personally identifiable information before passing it to the LLM.

Retrieval should also differ by source. Semantic similarity is useful for finding relevant passages, but medical diagnosis and procedure codes may require exact matching that vector search alone can miss.

SourceRetrieval approach
Guidelines and policiesVector search with metadata pre-filtering, or hybrid keyword/vector search
Patient claims historyExact match on the system's patient name or ID

Metadata filters constrain the candidate documents; keyword search can capture terminology and codes that need lexical matches. Patient history instead requires selecting the correct patient's records, not finding records about similar patients.

8:358:41
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

8:35 · section reference included

Map the workflow before choosing an agent

Start with the simplest design, evaluate it, and add complexity in response to observed failures. Defaulting to an agent—or letting a coding assistant select the architecture without this analysis—can produce an over-engineered system. Mapping the actual claim-processing sequence makes the necessary responsibilities visible.

The claim moves through the following steps:

  1. Receive the claim request and the physician's clinical notes.
  2. Retrieve relevant clinical guidelines, coverage policies, and patient claims history.
  3. Supply the LLM with the retrieved evidence, the claim, and instructions for generating a recommendation.
  4. Generate an approval or denial recommendation.
  5. Send complex cases to a senior physician and proposed denials to a human medical reviewer.
  6. Record the final decision and its reasoning in MongoDB.

The distinction between a recommendation and a final decision is essential. A proposed denial enters human review; it does not become a finalized denial merely because the model generated it.

12:1212:31
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

12:12 · section reference included

Choose the amount of autonomy the workflow needs

Several AI design patterns can participate in this workflow. Retrieval-augmented generation, or RAG, supplies external knowledge alongside the model's pretrained knowledge. In Joshi's terminology, agents use one or more LLMs and tools to complete tasks autonomously, while agentic systems cover a broader range of semi-autonomous designs. These are useful architectural conventions for discussing who controls execution.

Two patterns make that control boundary especially clear:

  • Control flow: code predetermines the sequence of steps, while an LLM performs particular tasks within it.
  • LLM-as-a-router: the model categorizes an incoming request and sends it to an appropriate downstream workflow. Its autonomy is limited to that routing decision.

The router diagram makes the distinction visible: one input reaches an LLM router, branches to one of three workflows, and then reaches the end.

Diagram showing Input flowing into an LLM Router, branching to Workflow 1, Workflow 2, and Workflow 3, then converging at END.
An LLM router directs input to one of three workflows.

Human-in-the-loop adds required human intervention somewhere in an LLM or agent process. Fine-tuning addresses a different kind of need: it is worth exploring when failures concern model behavior rather than missing data or incorrect orchestration, or when a domain-specific task requires better performance. Changing model behavior is not a substitute for retrieving the right policy or enforcing an escalation rule.

For claims review, the selected baseline combines three patterns. RAG supplies the guidelines and coverage policies. A controlled workflow produces a recommendation and applies predefined escalation rules. Human review handles the required cases. An additional LLM routing call could classify whether a case is complex if that classification is not already well-defined, but Joshi keeps the baseline as control flow rather than adding that call by default.

The escalation portion can be expressed as a small Python function. It preserves the model's recommendation while keeping human review pending; a complex proposed denial satisfies both review requirements.

python

from typing import Literal, TypedDict


class ReviewState(TypedDict):
    recommendation: Literal["approve", "deny"]
    required_reviews: list[str]
    status: Literal["pending_human_review", "ready_to_finalize"]


def route_recommendation(
    recommendation: Literal["approve", "deny"],
    *,
    is_complex: bool,
) -> ReviewState:
    required_reviews: list[str] = []
    if is_complex:
        required_reviews.append("senior_physician")
    if recommendation == "deny":
        required_reviews.append("human_medical_reviewer")

    return {
        "recommendation": recommendation,
        "required_reviews": required_reviews,
        "status": (
            "pending_human_review"
            if required_reviews
            else "ready_to_finalize"
        ),
    }


pending_claim = route_recommendation("deny", is_complex=True)

This function represents the routing boundary, not completed reviews or a database write. The surrounding workflow still has to obtain the required reviews before recording a final decision.

14:1014:19
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

14:10 · section reference included

Design the reviewer's interaction and feedback

Architecture alone does not define the product experience. Specify the input, output, location, and trigger. Here, the input is a claim request form; the eventual output is an approval or denial with an explanation. A standalone application, an existing website, and a Slack bot would create different interactions. For this example, the application would likely live inside MDB Health's main website and begin processing when a claim is submitted.

In the required cases, the human reviews the system's assessment and makes the final decision. To support that work, the assessment should cite the clinical guidelines and coverage policies behind it. Medical reviewers can then override the model's verdict and record why. They should also be able to flag irrelevant citations, invented references, or real policies applied to the wrong claim. That feedback distinguishes a disagreeable recommendation from a specific failure in the evidence supporting it.

Only after defining the architecture and interaction should the team settle the tooling. A coding assistant's preferred stack may violate the approved-cloud requirements. The remaining choices include the generation model, data-processing tools, embedding model, vector database, and orchestration framework. Existing data-processing capabilities may eliminate work the team would otherwise build itself. Joshi leaves these choices open because the organizational constraints in the example are hypothetical.

17:3017:48
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

17:30 · section reference included

Measure boundaries, evidence quality, and outcomes

Evaluation establishes whether the system works before shipping; monitoring checks its behavior afterward. Both require explicit definitions of acceptable behavior. Because an LLM can generate unexpected, incorrect, or harmful output, guardrails must state which inputs and outputs the application will accept.

For an input guardrail, a request to write a poem is irrelevant to claims review and should be rejected as an invalid request. That is different from denying insurance coverage. For an output guardrail, an approval or denial without supporting citations is invalid. These checks define boundaries, but passing them does not yet establish that the recommendation is good.

Evaluate several dimensions rather than collapsing quality into one score:

DimensionMetricQuestion
Input guardrailsInput rejection rateHow often are submissions rejected by input checks?
Output guardrailsMissing-citation rateHow often does the model omit citations?
Response qualityFaithfulnessIs the verdict grounded in retrieved evidence?
Application outcomeClaim-processing timeIs review becoming faster?
System healthCost per recommendationWhat does each recommendation cost?

Excessive input rejection should trigger investigation. Citation presence needs a separate faithfulness check: a response can include references without grounding its verdict in the retrieved guidelines and policies. Processing time keeps evaluation connected to the original business problem, while cost per recommendation captures an operational constraint. Token usage, token cost, and conversation turns are other possible system-health measures.

20:5621:12
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

20:56 · section reference included

Use reviewer behavior to detect production regressions

After launch, continue tracking the metrics used in offline evaluation so regressions remain visible. Production also exposes signals that a prelaunch test cannot fully supply: how people interact with the recommendations and how much work the system actually saves them.

Track how often medical reviewers override the AI verdict. An increase above a chosen threshold is a reason to investigate the recommendations and their supporting evidence. Also track how long a human takes to review a recommendation. Long review times may indicate that responses are verbose or confusing, even when the model's underlying assessment is useful. These measures connect model behavior to the experience of the people the product is supposed to help.

24:0024:16
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

24:00 · section reference included

Optimize the working system for production

Good prototype accuracy does not settle production readiness. Cost, latency, and reliability can require further iterations of implementation, evaluation, and testing. Treat them as requirements that must hold alongside accuracy, not work to consider only after the product is deployed.

For accuracy, focus on the information reaching the LLM's context window:

  • Prompt engineering: improve the instructions that guide the recommendation.
  • Re-ranking: order retrieved material by relevance so the context surfaces the most useful evidence.
  • Memory: persisted patient history in MongoDB already retains information across requests; consider whether other information is useful across sessions.

These changes address different parts of the same path: instructions, retrieved evidence, and retained context.

For cost and latency, Joshi proposes semantic caching to expedite work using similar past claims, and batch processing as an alternative to processing claims individually. These are candidates to evaluate against the system's requirements; neither is presented as an implemented improvement in the example. Similarity-based reuse must still respect the patient's applicable evidence, and batching must fit the urgent-review time budget.

Reliability work must also account for API failures. The concrete technique Joshi emphasizes is structured output containing both the decision and its citations. This gives downstream code an explicit response contract. Requiring those fields does not establish that the decision is correct or that the citations support it, so the faithfulness evaluation remains necessary. Refusals and incomplete responses also need handling rather than being treated as valid decisions.

25:1225:30
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

25:12 · section reference included

Let measured failures determine the next iteration

The hard work begins before asking AI to generate code: deciding what the product must accomplish and what behavior is permissible. A latency budget, a cost ceiling, and a regulatory requirement each constrain the architecture downstream. For MDB Health, those decisions lead to evidence retrieval, a controlled recommendation workflow, and mandatory human review in specified cases.

Build the simplest system that meets those needs, evaluate it, and use the failures to decide what changes next. Adding autonomy or orchestration before knowing what is failing makes the system harder to understand without establishing that it works better. Evaluation therefore belongs in the initial design, not at the end of implementation.

Key takeaways slide with four bullets about product requirements before code generation, business and performance constraints, simple iterative system design, and evaluation from the start.
Four takeaways: define requirements, account for constraints, keep the system simple, and evaluate from the start.

Joshi closes by pointing to a Gen AI Cookbook for further examples of retrieval techniques, agentic design patterns, evaluation, and optimization—the implementation exercises that follow once the product's requirements and evidence needs are clear.

27:2427:40
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

27:24 · section reference included

Resources

Read the complete timestamped transcript
  1. 0:02

    Hi, everyone. I'm Apoorva, and I'm a data scientist turned developer advocate currently at MongoDB. I spent the first years of my career building machine learning applications for various cybersecurity use cases, and I now use that applied machine learning knowledge to help AI builders successfully build AI applications with, uh, MongoDB and Voyage AI.

  2. 0:25

    In this talk, you'll learn how to think through building AI systems end-to-end from idea to production. We'll take a real-world use case and walk through all the steps of designing it, and hopefully in the end you'll walk away with a repeatable framework that you can apply to, uh, any AI system you design.

  3. 0:46

    Now, you might be thinking, in the age of AI, do we even need to think about what we build? Just write code it and ship it, right? But that's actually where I want to start.

  4. 0:57

    Now, here's the problem with that. Write coding works great when you're building for fun, the stakes are low, and you can easily eyeball whether the output of what you're building is right.

  5. 1:09

    But the moment you're building something real, something other people depend on, something with real consequences, "Just ship it," is actually kind of dangerous. Uh, and it's not just me saying it.

  6. 1:20

    Folks from Anthropic and OpenAI who are so bullish on AI coding are saying the same thing. These are actually quotes from their talks over the past few months.

  7. 1:30

    Specs are the new code. The art is in defining the product requirements, the system design, and evaluation criteria so you can be confident that your AI coding buddies are building the right thing.

  8. 1:42

    And the rest of the talk is just about that. How do we do this well?

  9. 1:49

    It's useful to think about it as a framework. Four phases. You start with product requirements. What are you actually building, uh, for whom, and what are the constraints? Then system design, the data, the architecture, the patterns that actually help you meet these requirements.

  10. 2:07

    Then comes evaluation and monitoring. How do you know, uh, what's being built actually works before and also after you ship? And finally, how do you optimize for cost? Uh, not just for accuracy, but also for cost, latency, and reliability before you ship, uh, and/or as you find gaps in production.

  11. 2:30

    Instead of talking abstractly through a framework, I thought, why not, uh, apply it to a real-world use case so you can see how exactly each decision flows from, uh, one stage of the ne- framework to the next?

  12. 2:43

    So let's take the example of a health insurance claims review system.

  13. 2:49

    So adjudicating health insurance claims has historically been an extremely manual process where, uh, human medical reviewers have to, uh, cross-reference clinical guidelines, insurance coverage policies, uh, patient history and stuff to decide whether or not, uh, a medical treatment, procedure, or medication is covered by a patient's health insurance policy.

  14. 3:13

    Now, if you live somewhere that has free healthcare, uh, even there, there's things that are covered, uh, and things that are not by your healthcare system, so you're still subject to, uh, some version of this process.

  15. 3:27

    Now, our goal with building the system is to see if we can improve or simplify the experience for, uh, medical reviewers with the help of AI.

  16. 3:38

    So let's see what the product requirements stage of the framework for this application might look like.

  17. 3:46

    So first thing to do is quantify the business problem. The business problem should focus on something specific, uh, clearly state who the users of the application are, uh, the current state of things, and quantify the user's pain point.

  18. 4:02

    It should not prescribe what the system is going to be, whether it's going to be an agent, a multi-agent system, something else. Uh, that'll come later.

  19. 4:14

    So here's what the business problem for our claims review system could look like. Medical reviewers at MDB Health spend an average of two days processing claim review requests, which is four times the industry standard for non-urgent cases and twelve times the industry standard for urgent ones.

  20. 4:31

    Delays at this scale postpone patient care, uh, particularly for time-sensitive treatment. So as you can see, this business problem is user-specific. It says this is meant for medical reviewers.

  21. 4:44

    Uh, it states the current state, which is, like, this manual process that leads to them spending two days processing, uh, claim reviews. It's measurable because it states some baselines.

  22. 4:57

    Uh, it's solution agnostic. It doesn't really tell you, uh, what the system should look like. Uh, and it's very focused on a specific problem.

  23. 5:11

    Next, you want to gather any business constraints for the application, so any regulatory, uh, compliance requirements, any constraints on data leaving your organization, procurement constraints, meaning are certain vendors, uh, not approved for use within the organization.

  24. 5:28

    Uh, all of these would be good to know before you even start designing the system. So for our application, say these are some of the business constraints. Patient data has to stay within the approved cloud environment.

  25. 5:40

    Um, only models available on the approved cloud can be used. Um, there's some use cases where human review is required, so any complex use cases require a senior physician's review.

  26. 5:54

    Um, what else? Any denial decisions must be, uh, reviewed by a human reviewer. So there's cases which you can't fully automate with AI. So yeah, all of these are useful design inputs, so you want to have these sooner rather than later.

  27. 6:14

    Also good to know of any performance requirements. Uh, do we need sub-millisecond responses, or do we have some leeway there? Uh, how much can we spend per month on LLM inference?

  28. 6:26

    Any uptime SLAs to be aware of? Next, if you're building an AI product, identifying the role of AI, uh, in your product is helpful. And I like to think about the role of AI along three dimensions.

  29. 6:41

    First, is AI critical to your product or complementary? In this case, complementary, since, um, claims are already happening without... claim reviews are already happening without AI, but they are just slower.

  30. 6:54

    Next, will this be a reactive or proactive system? Meaning, is it triggered by a user or an event, or does it proactively do things? In this case, it's going to be a reactive system since, uh, it's triggered by a claims application actually being submitted.

  31. 7:12

    And finally, what's the level of autonomy, uh, for AI in the application? So in our case, the business constraints prescribe human review in certain cases, so our system can be semi-autonomous at max.

  32. 7:28

    And finally, as part of defining what you're solving for, you also want to come up with one to two, uh, success metrics aligned with the business problem so you can capture what success looks like.

  33. 7:39

    A good success metric is specific, measurable, achievable, relevant, and time-bound. And here's an example of a success metric for our claims review application. So it says, it says reduce the average processing time for urgent claim review requests from two days to one hour, uh, within ninety days of launch.

  34. 7:59

    So it's super specific. It's measurable because it's saying, uh,

  35. 8:06

    the processing time needs to be one hour. Uh, it seems achievable because, um, there'll be AI in the loop, so hopefully any information gathering, uh, getting an initial recommenda-re-recommendation will be faster.

  36. 8:20

    Uh, it's very relevant and rooted in the business problem from before, and it's time-bound because it gives you a, a window for when we need to start seeing success.

  37. 8:35

    Okay, so at this point we've figured out, uh, the what. Let's look at the how.

  38. 8:41

    The first thing you want to think about here is your data strategy. What does... Uh, what data does your application need? Do you even have access to it? Where does it reside?

  39. 8:52

    Uh, is it ready for consumption in its raw form, and so on.

  40. 8:59

    So for our claims review application, these are the data sources that we might need, where they reside, and what their raw access formats might look like. So we need, uh, clinical guidelines probably, uh, which describe what care is appropriate for a given condition.

  41. 9:14

    Uh, MDB Health coverage policies that state what MDB Health will and will not pay for.

  42. 9:22

    And finally, the patient's claims history to know any, uh, past conditions, uh, procedures that were performed, when they were performed, and so on.

  43. 9:33

    Let's assume that the clinical guidelines and coverage policies are stored as PDFs in something like Confluence, uh, and claims are stored in MongoDB as and when they are processed.

  44. 9:46

    The next thing to think about is data update frequency. How often do the data sources update? Now, if you're doing any sort of data processing on these raw data sources, and you typically are, these pipelines are going to have to, uh, run at the right cadence to keep up.

  45. 10:02

    Otherwise, our system is going to work off of stale information, and that's not good, especially in such a high-stakes use case.

  46. 10:11

    So let's work this out for our claims review system. Clinical guide, these probably update annually. Uh, internal coverage policies may be quarterly, and the patient's claim history needs to be updated whenever a new claim is processed.

  47. 10:28

    And in our success metrics, if you recall, uh, we've said we want to aim for a one-hour timeframe for adjudicating urgent claims. So these will probably get updated hourly.

  48. 10:42

    Next, can the data be consumed directly by our application, or does it need any processing? For clinical guidelines, which are typically long documents, you probably want to chunk them, uh, embed the chunks, and also extract metadata such as procedure names, publication dates to make it suitable for retrieval using something like vector search or hybrid search.

  49. 11:04

    Same goes for, uh, coverage policies. But for patient claims history, which is already well formatted and stored in MongoDB, we might just need to remove, uh, personally identifiable information, uh, before passing it to an LLM.

  50. 11:20

    Next, we want to think about what retrieval techniques would be best suited for each of the data sources. And you kind of already start thinking about this in the data processing step, but let's quickly formalize this.

  51. 11:32

    Now, clinical guidelines and coverage policies, um, are well suited for vector search, but they can contain, uh, medical terminology such as diagnosis codes, procedure codes, uh, that might not be picked up by vector search.

  52. 11:45

    So, um, but these will be picked up by metadata filters or something like keyword search. So for these, you'd either want to, uh, use vector search with metadata pre-filtering or hybrid search.

  53. 12:01

    For getting the patient's claims history, you can do an exact match on the patient name or ID, whatever the patient identifier is in the system.

  54. 12:12

    Next, you wanna think about what the system architecture looks like. Now, it can be tempting to jump straight to building an agent, there's so much hype around them, uh, or let a coding agent decide what the system architecture should look like, but you risk ending up with an over-engineered system by doing this.

  55. 12:31

    So what you instead want to do is start with the simplest design, uh, evaluate it, uh, find gaps during the evaluation, and iterate from there.

  56. 12:42

    To decide what the system should look like, let's first map out how an insurance claim would flow through the system, because this will help us, uh, inform the architecture.

  57. 12:52

    So first, the claim request and any clinical notes from the physician are received by our system. Uh, then the system needs to retrieve any clinical guidelines and coverage policies are, that are relevant to the current claim, uh, and also retrieve the patient's claims history.

  58. 13:12

    Then all of this information, along with, um, the claim itself, uh, and any system prompts on how the LLM should generate... go about generating the recommendations, all of these are passed to the LLM, um, and it uses those to generate, uh, a recommendation of whether the claim is...

  59. 13:31

    claim should be approved or rejected. Now, if it's a complex case, our, uh, system, or the LLM at this point, should, uh, send its initial recommendation, um, to a senior physician.

  60. 13:45

    And if the LLM's recommendation is to deny the claim, then it should also be escalated to a human medical reviewer.

  61. 13:54

    And finally, the final decision should be logged to MongoDB, which is where we are storing our claim documents, uh, along with a reasoning for why the claim was approved or rejected.

  62. 14:10

    Now, let's talk about some of the most common AI design patterns that we see, uh, in AI systems today, and see which of those might apply to our system.

  63. 14:19

    So the first one is RAG, uh, short for Retrieval-augmented generation. You all probably know it at this point. Um, basically in these systems, you simply augment an LLM's pre-trained knowledge with external knowledge sources.

  64. 14:33

    So information from external knowledge sources. Then there's AI agents, where you give, uh, a single L- LLM or multiple LLMs in the case of multi-agent systems, full autonomy to complete tasks end-to-end with the help of a set of tools.

  65. 14:52

    And then there's agentic systems, which cover, uh, a broad spectrum of semi-autonomous AI systems.

  66. 15:01

    A common architecture pattern for, uh, these types of systems are control flows, where LLMs perform certain tasks within the workflow, but the sequence of steps in the workflow itself is predetermined by design or by code.

  67. 15:18

    Then there's LLM-as-a-router, where LLMs have limited autonomy, in that their job is simply to, uh, categorize incoming requests and route them to different downstream workflows.

  68. 15:32

    Then you have human-in-the-loop, where an LLM or agent can take certain actions, but it needs human intervention, uh, somewhere in the process.

  69. 15:42

    And finally, there's fine-tuning. So if you're observing that the LLM's failures are behavioral rather than data or orchestration issues, uh, or if you need superior performance on a domain-specific task, then fine-tuning is, uh, a good technique to explore.

  70. 16:02

    I don't have the time to go too deep into these here, but if you'd like to learn more about these design patterns, uh, I'm going to leave this resource here for you to check out later.

  71. 16:18

    So we've thought through what the workflow of the system should look like. We've spoken about a few different AI design patterns. Uh, now let's apply those and decide what design patterns, um, we'd need to implement for our system.

  72. 16:33

    So since we need to retrieve clinical guidelines, coverage policies, and stuff to inform the decision, this is... this definitely looks like a RAG component, so we need some form of RAG.

  73. 16:44

    The workflow is pretty structured in that the LLM first provides its recommendation on whether or not a claim should be approved or rejected. And in very specific and well-defined cases, uh, it needs to escalate claims to human reviewers.

  74. 16:58

    So this sounds like a controlled workflow. You could also argue that this looks a little bit like LLM-as-a-router, especially if you use, um, an additional LLM call to decide what a complex case looks like, uh, unless this is already well-defined.

  75. 17:13

    So yeah, this could be an LLM-as-a-router, but, uh, for now, let's just go with control flow.

  76. 17:21

    And finally, there's also an element of human-in-the-loop, right? Since human reviewers are very much a part of the workflow.

  77. 17:30

    And finally, in the design phase, you also want to think about the end user experience and how you'll collect feedback from your users to improve the system. Here's some questions to ask yourself in this stage to help think through, uh, what the UX and feedback mechanism should look like.

  78. 17:48

    So first, what does the system take as input? In our case, it's going to be a claim request form of some kind.

  79. 17:56

    Then what does the system produce as output? So in our case, it's going to be, uh, an approval or denial verdict, along with an explanation for why, uh, a claim was approved or rejected.

  80. 18:09

    Where does the system live? Does it have its standalone app? Is it embedded in an existing website? Is it a Slack bot? Uh, and so on. Uh, so for

  81. 18:20

    Our application, it's very likely going to be embedded within MDB Health's main website, let's say. Uh, what triggers the system? So in our case, very clearly a claim submission.

  82. 18:33

    What's the human's role? So in our case, they are going to review the system's assessment and make the final decision in some cases.

  83. 18:42

    Um, how does the system explain itself? In our case, um, it explains itself by providing citations, so quoting, uh, the clinical guidelines and coverage policies that, uh, inform the system's assessment.

  84. 18:57

    And finally, how users give feedback. So remember, for our system, um, the consumers are medical reviewers. Um, so they can provide feedback by overriding the verdict of the LLM and also log a reason for why.

  85. 19:13

    Uh, they can also... We can maybe also have them flag any irrelevant citations. So if the LLM is hallucinating, um, clinical guidelines and policies or, uh, yeah, quoting the wrong ones for a particular claim, then we can have them flag those as well.

  86. 19:36

    All right. So at this point, we've decided what the architecture of our system should look like, uh, but we also need to decide what our stack should look like.

  87. 19:47

    Once again, it might be tempting to have a coding agent recommend, uh, what tools to use, but they might not necessarily apply to your system, or you might not be able to use them based on the constraints that we identified during, uh, the product requirement stage.

  88. 20:01

    So we had constraints around, uh, models, uh, need to be supported by our cloud provider and things like that.

  89. 20:12

    Really going to get into this too much since our constraints are, uh, well, hypothetical. Uh, but I just wanted to mention that this is the next step and the different tooling decisions to be made, uh, such as what model to use.

  90. 20:25

    Uh, there's a, a bunch of data processing tools out there that have some nice out-of-the-box data processing capabilities.

  91. 20:33

    If retrieval is part of your system, then, uh, and you're using things like vector search, then you might need to decide what embedding models to use, what vector database to use.

  92. 20:43

    Um, then there's orchestration frameworks and so on. So I'm just gonna leave this here for reference later on.

  93. 20:56

    Next, let's talk about evaluation and monitoring. How do you know that what you've built works before and also after you ship? So evaluation is before, uh, monitoring is after you ship, and you need both of them.

  94. 21:12

    But before we get into evaluation metrics, let's talk about guardrails because these weren't really th- really a thing pre-LLMs.

  95. 21:20

    The reason they've become a topic of conversation is because unlike traditional software, LLM-based systems are going to... are probabilistic systems and can produce outputs that are unexpected, incorrect, or even harmful.

  96. 21:33

    And guardrails are an attempt to mitigate these risks and ensure that your system behaves within acceptable boundaries. And what those boundaries are, are something you need to define. So for inputs to your system, the goal is usually to detect invalid, irrelevant, or harmful inputs.

  97. 21:50

    Uh, so for a claims review system, an input like, "Write me a poem," is irrelevant, and our system should reject this claim.

  98. 22:01

    Similarly, for outputs, our goal is to detect invalid, incorrect, or hallucinated, uh, or harmful outputs. So for our claims application, we'll consider, uh, a response to be invalid if the system doesn't provide citations for, uh, what informed an approval or denial.

  99. 22:20

    Now, guardrail compliance is not the only thing you want to measure. You want to measure the quality of the responses, um, create and measure domain-specific accuracy metrics, and also general system health.

  100. 22:34

    So for input guardrail compliance, uh, for our system, we can calculate a claim rejection rate. How often is our, uh, system rejecting claims because they don't obey, uh, our input guardrails?

  101. 22:47

    Now, if it's rejecting too many times, then that's a call for investigation. But if you didn't measure this in the first place, then you wouldn't have anything to investigate.

  102. 22:55

    So, uh, there we go. That's why you need metrics. For output guardrail compliance, we can have something like a missing citation rate. How many times is the LLM producing responses without citations?

  103. 23:07

    For response quality, we can measure faithfulness, which is whether or not the claim's approval or rejection is actually rooted in the retrieved, uh, information, like clinical guidelines and policies.

  104. 23:24

    Then you want to define at least one domain or application-specific metric. So in our case, something like claim processing time might be a good one because that's really, uh, our north star.

  105. 23:36

    And system level metrics are usually, uh, around overall system health. So, uh, what's your system's average token cost, token usage, uh, average number of turns in a conversation? Uh, so here, just to, um, not have another latency metric, uh, I put down something like cost per recommendation.

  106. 24:00

    So once you've evaluated your system and shipped your product in front of users, then comes monitoring the system for regressions in real time. Now, in production, you still want to track the metrics that you used for, uh, offline evaluation, so the metrics that we [audio cuts out] about.

  107. 24:16

    But you might also be able to track additional metrics that can act as, uh, implicit indicators of your product's success or, like, how, um, How happy users are with your product and overall system health.

  108. 24:31

    For example, for the claims review app, you can track how often a human reviewer overrides the AI verdict. Uh, now, you want this rate to be low, uh, because that means the system is not doing its job.

  109. 24:42

    So if you ever start seeing is, seeing it increasing about, above a certain threshold, then you need to go and investigate. Or you can also track something like how long does it take for a human to review the AI recommendation?

  110. 24:56

    If it takes too long, which means, um, this could mean that the responses are verbose, confusing. So yeah, these would be, uh, some good indicators to track, uh, once you ship your product to production.

  111. 25:12

    Now, once you have a working prototype that you've evaluated, accuracy looks good, it's time to move to production, right? Well, what about cost, latency, and reliability? Uh, these constraints become absolutely non-negotiable as you're moving your product to production.

  112. 25:30

    So you might need to do a few more iterations, evaluations, and testing, uh, between accuracy looks good and moving to production.

  113. 25:40

    So let's talk about some optimization techniques for each of these. So optimizing for accuracy. In LLM-based applications, it really comes down to optimizing the information that, uh, ends up in the LLM's context window.

  114. 25:55

    And here are some techniques for you to refer to later, but let's quickly talk about which of these, uh, might apply to our claims review application. So prompt engineering, of course.

  115. 26:05

    Uh, re-ranking is another good one because, uh, retrieval is a big component of it, so, uh, a re-ranker will make sure that the information being retrieved, um, is surfacing information in the right order of relevance, which is important when working with LLMs.

  116. 26:22

    Uh, we are also persisting patient history, uh, to MongoDB, so our application already has some form of memory. But you could also think about other types of information that might be, uh, useful to persist across sessions.

  117. 26:36

    Here are some techniques for cost and latency optimization. For our use case, semantic caching could be useful to expedite decisions based on, uh, similar claims from the past. Uh, batch processing perhaps to process claims in batches instead of one at a time.

  118. 26:54

    And finally, optimizing for reliability. Most of these would be useful for our use case since they're mainly solving for API failures. But, uh, I want to specifically call out structured outputs, um, which would be a good one to make sure that our system is always producing a structured output which contains not just the decision, but also the

  119. 27:15

    citations. This brings me to the end of my talk, but I wanted to leave you with a few takeaways.

  120. 27:24

    Think deeply about your product's requirements before having AI generate any code. The product spec is the hard part now, uh, it's not the code anymore.

  121. 27:40

    Your latency budget, your cost ceiling, any regulatory requirements, all of these shape every architectural decision downstream. So, uh, good to identify, uh, business and performance constraints before starting to design your application.

  122. 27:57

    Design the simplest system that meets your needs. Evaluate it, and then iterate from there. The most common mistake I see is over-engineering the solution before knowing what's actually failing or not even evaluating what's actually failing.

  123. 28:14

    And that brings me to evaluation. Uh, build evaluation in from the start. Uh, you can't improve what you can't measure.

  124. 28:23

    Link to our Gen AI Cookbook that has a ton of examples of, uh, different retrieval technique, agentic design patterns, and, uh, some of the evaluation and op-optimization techniques that, uh, I was talking about.

  125. 28:40

    And yeah, thank you so much for taking the time to listen to my talk. I'll see you at the conference. [mouse clicking]