{"slug": "where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot", "title": "Where Not to Use the LLM: Lessons from Building a Healthcare Front-Office Chatbot in Python", "summary": "A healthcare patient-services worker spent roughly six and a half months building Steve, a Python and Flask front-office chatbot prototype that routes each message through deterministic workflow handlers before falling back to an LLM via the Groq API. The project's central design rule is that predictable workflows are handled in Python and answered directly, with the model reserved for genuinely open-ended interactions and fed system-injected context blocks rather than relying on its own assumptions. The developer stresses the demo is fictional, not clinically validated, and not HIPAA compliant, with schedules and chart lookups simulated.", "body_md": "**A quick disclaimer:** Steve is a personal portfolio project. It has never been used with real patients, is not clinically validated, and is not HIPAA compliant. Every patient, provider, and scenario in the demo is fictional. Much of its backend functionality, including schedules, chart lookups, and appointment availability, is simulated. I'll explain why that distinction matters throughout this article.\n\nI work in healthcare patient services, so I have a practical understanding of the kinds of requests that come through a primary care front office every day.\n\nA lot of the work involves a relatively small set of recurring requests:\n\nThese conversations may be repetitive, but they are not necessarily simple.\n\nWho is calling matters. Whether the caller is authorized to receive patient information matters. Whether the office is open, whether the patient is a minor, and whether a medication is a controlled substance can all change how a request should be handled.\n\nThat combination of repetitive interactions and important workflow rules made me interested in a particular question:\n\n**In an AI application, the interesting design question isn't just what the LLM can do. It's what the LLM should be allowed to decide.**\n\nI spent approximately 6½ months building Steve, a text-based chatbot designed to handle these types of patient services conversations.\n\nAlthough the conversations are written in the style of a phone call, Steve operates through a web-based text chat interface. It does not use speech recognition or text-to-speech.\n\nSteve is built with **Python and Flask**, with an LLM accessed through the **Groq API** for open-ended conversational interactions.\n\nThe prototype supports several workflows, including:\n\nHere is a demonstration using fictional patients:\n\n**▶️ [Watch the Steve demo on YouTube](https://youtu.be/FszKyz-8_L8)**\n\nThe most important architectural lesson I learned while building Steve was that not every interaction needs an LLM.\n\nMy central design rule became:\n\n**If a workflow is predictable, Python handles it and returns the response directly. The LLM handles what is genuinely open-ended.**\n\nEvery message enters through a single Flask `/chat` route. That route checks a sequence of deterministic workflow handlers first.\n\nIf a handler recognizes and owns the interaction, it returns a response without calling the LLM. Only when none of the defined workflows handles the message does the application assemble the relevant context and call the model.\n\nHere is a simplified illustration of that approach:\n\n``` python\n@app.route(\"/chat\", methods=[\"POST\"])\ndef chat():\n    # 1. Deterministic workflows get first priority\n    response = handle_some_workflow(user_message, message_lower)\n\n    if response is not None:\n        return jsonify({\"response\": response})\n\n    # 2. Otherwise, assemble context and ask the LLM\n    system_with_context = \"\\n\".join(\n        part for part in (system_prompt, pre_chart_context, ...) if part\n    )\n\n    completion = groq_create_completion(\n        messages=messages,\n        ...\n    )\n```\n\nWhen the LLM is called, it does not receive just a bare conversation.\n\nPython builds the system prompt and appends context blocks calculated for that particular turn. Depending on the interaction, these can include:\n\nThese context blocks are labeled as system-injected information, and the prompt instructs the model to use them rather than relying on its own assumptions.\n\nThe application evolved over 17 development sprints. `app.py` handles routing and session control, while separate modules contain workflows for post-hospital follow-ups, wellness visits, medication refills, lab orders, fax inquiries, and miscellaneous requests.\n\nThose modules use state-machine-style logic to manage the different stages of each workflow.\n\nI did not start with this architecture. Initially, I relied more heavily on the prompt and the model's ability to interpret instructions.\n\nDuring development, I encountered several situations that changed how I approached the design.\n\nA patient requested an order for a monthly Prolia shot.\n\nProlia is not a controlled substance. However, my prompt contained a detailed section about controlled-substance procedures, and the model incorrectly treated the request as one. It generated a medication schedule and an invented timeframe related to the patient's last office visit.\n\nThe problem was not simply that the model misunderstood a word. It was applying a nearby set of instructions to a situation where they did not belong.\n\nMy solution was to add a deterministic handler for non-controlled medication order requests rather than continuing to rely on prompt adjustments.\n\nI originally asked the model to calculate which calendar date corresponded to each weekday.\n\nIt sometimes produced incorrect dates. For example, it offered Monday, September 1, even though September 1, 2026 was a Tuesday. It also occasionally suggested dates that had already passed.\n\nI moved that responsibility into Python.\n\nThe application now calculates the next occurrence of each weekday, accounts for recognized office holidays, and provides the model with a literal lookup table.\n\nPython calculates the dates. The LLM communicates them.\n\nAt the end of an interaction, Steve asks:\n\n\"Is there anything else I can help you with?\"\n\nOccasionally, when a patient responded with \"No. Thank you,\" the model returned an empty response.\n\nClosing a conversation is one of the most predictable parts of the interaction. I therefore moved that behavior into deterministic application logic.\n\nThese experiences reinforced a rule I now use when thinking about AI application development:\n\n**If a rule can reliably calculate or determine the answer, put that responsibility in code.**\n\nIdentity checks, age calculations, office hours, eligibility windows, and calendar dates should not depend on an LLM improvising a response.\n\nThe LLM is useful for conversational flexibility and handling the many different ways people express themselves. It should not automatically become the authority for every business rule.\n\nSeveral important workflow rules live in Python rather than relying exclusively on the system prompt.\n\nHere are some examples.\n\n**Third-party callers:** Someone calling about a patient must pass a simulated authorization-on-file check. If the caller is not listed as authorized, the workflow moves toward having the patient join the conversation. The patient must then verify their own last name and date of birth and provide consent before information is shared.\n\n**Minors:** A date of birth that calculates to an age under 18 triggers a restriction. Scheduling cannot proceed until a parent or guardian is on the line and has identified themselves.\n\n**Office hours and holidays:** Seven recognized holidays, including weekend-observance adjustments, are incorporated into the office-hours logic. Steve uses the same function to determine whether the office is open on weekends and holidays.\n\n**Medication questions:** Steve does not explain what medications are used for. Those requests are directed toward a callback workflow.\n\n**Controlled substances:** Requests follow a separate workflow based on the medication's schedule and the patient's last-visit timeframe. One path also includes a bridge-medication question after an appointment is booked.\n\nIt is important to distinguish between a simulated workflow and a real verification system.\n\nFor example, the authorization-on-file result is randomly generated because Steve does not connect to an actual electronic health record. The purpose was to develop and test the conversation logic, not to represent a compliant patient-information verification system.\n\nSteve does not connect to an EHR or an actual scheduling platform.\n\nAs a result, many backend results are simulated. These include:\n\nAppointments booked through Steve are saved to local JSON files. This allows the prototype to retrieve appointment information or handle a later rescheduling request.\n\nOne challenge with simulated data is that random results can make testing difficult.\n\nA conversation might follow one path today and a different path tomorrow because the simulated result changed.\n\nTo address this, I added environment-variable overrides that force specific workflow branches. This allowed me to replay the same conversation and test the same conditions repeatedly.\n\nI learned that randomness can be useful when simulating real-world variation, but reproducibility is essential when troubleshooting an application.\n\nA significant amount of development time went into debugging.\n\nThe recurring problems were often straightforward Python issues rather than complicated AI failures:\n\n`elif` statements`global` declarations\nA few examples were particularly memorable.\n\nSome workflow modules needed access to the application's live state, including conversation history and patient information.\n\nThe modules accessed that state by importing `app`.\n\nHowever, when Flask is launched with:\n\n```\npython app.py\n```\n\nPython loads the running file under the module name `__main__`.\n\nWhen another module subsequently imports `app`, Python can load the same file again as a separate module. That second copy has its own globals, which are not the same as the live application's state.\n\nThe result was a strange bug: the application did not necessarily crash, but the workflow modules could behave as if the patient had never provided certain information.\n\nI addressed this with:\n\n```\nsys.modules.setdefault(\"app\", sys.modules[__name__])\n```\n\nIt was a good reminder that some bugs are difficult to identify precisely because nothing visibly crashes.\n\nMy early intent detection relied on simple substring checks.\n\nThat created several unexpected matches:\n\n`\"form\"` matched inside `\"metformin\"`\n`\"no\"` matched inside `\"now\"` and `\"know\"`\n`\"ave\"` matched inside `\"have\"`\n`\"park\"` matched `\"Parker\"` when searching for a provider named Park\nI changed the matching logic to use word boundaries:\n\n``` python\ndef _contains_trigger(message_lower, triggers):\n    for trigger in triggers:\n        if re.search(r'\\b' + re.escape(trigger) + r'\\b', message_lower):\n            return True\n    return False\n```\n\nThis improved matching for the scenarios I was testing, although it did not eliminate the broader limitations of regex-based intent detection.\n\nAnother problem occurred when someone said:\n\n\"Schedule a follow-up for my spouse and myself.\"\n\nA name-capture pattern incorrectly extracted \"and\" and \"myself\" as a first and last name.\n\nThat incorrect capture then interfered with later logic intended to identify whether the caller was the patient.\n\nI added checks to reject certain non-name tokens.\n\nThe larger lesson was that extracting names from unrestricted conversational text is more complicated than it initially appears.\n\nI also encountered cases where the model response was cut off because it reached its token limit.\n\nFor example, a patient could receive a response ending with:\n\n\"...is there anything else I\"\n\nI added logic to detect truncated responses and trim incomplete output back to the last complete sentence. In the specific closing workflow, the application can complete the expected closing response deterministically.\n\nAnother issue involved API failures. Initially, a failed API request could expose raw provider error information, including status codes and quota details, to the user.\n\nI changed the error handling so that the user receives a generic apology while the application logs the exception type for troubleshooting.\n\nThe application also supports multiple API keys through environment variables and rotates to another configured key when a request fails.\n\nThe important point is that credentials are not hard-coded into the application.\n\nI want to be clear about what testing meant in this project.\n\nSteve went through disciplined, scenario-based manual testing. It did not have a completed automated test suite.\n\nMy testing process included:\n\nOne improvement I would make next is converting those manually replayed conversations into automated transcript tests.\n\nMany of the test cases already exist in the form of conversations I used during development. Turning them into automated tests would make regression testing more efficient and repeatable.\n\nBuilding Steve was a valuable learning experience, but there are important limitations.\n\n`app.py` file:\nIf I continued developing Steve, my priorities would be:\n\nThese are not small changes, but identifying them is part of understanding what it would take to move a prototype toward a more mature application.\n\nAfter spending months developing and debugging Steve, these are the lessons I would carry into another project:\n\n**1. Decide what the model is allowed to decide.**\n\nDo not assume that the LLM should control every part of the interaction. Define its responsibilities deliberately.\n\n**2. Calculate what can be calculated.**\n\nDates, eligibility windows, age checks, and office hours are better handled by predictable application logic.\n\n**3. A better prompt will not always fix a recurring problem.**\n\nIf you find yourself repeatedly adjusting a prompt to address the same failure, consider whether the responsibility belongs in code instead.\n\n**4. Make randomness controllable.**\n\nSimulated outcomes are useful, but you need to be able to reproduce a failing scenario to troubleshoot it effectively.\n\n**5. Plan for unglamorous failures.**\n\nTruncated responses, API rate limits, empty replies, and error messages that expose internal details are all part of application development.\n\n**6. Keep track of recurring bugs.**\n\nRecognizing patterns such as overly broad regex expressions, incorrect logic ordering, and state-management problems can make debugging more efficient.\n\n**7. Be honest about what your application does and does not do.**\n\nA prototype with clearly documented limitations is more credible than one that makes unsupported claims.\n\nMy background is in healthcare informatics and data analytics, and I think that influenced how I approached this project.\n\nAn important part of analytical work is defining rules, identifying exceptions, understanding the underlying information, and checking results against expectations.\n\nThose same habits proved valuable when developing an AI-assisted application.\n\nThe LLM contributed conversational flexibility, but the application needed predictable logic for the things that had to be handled consistently.\n\nSteve is the largest coding project I have built, and it taught me more than I expected, particularly through the problems I encountered along the way.\n\nIt also reinforced an idea I find increasingly important as AI applications become more common:\n\n**Building a useful AI application isn't just about getting the model to produce a good response. It's about designing the surrounding application so that the right things happen for the right reasons.**\n\nI'd welcome feedback from other developers:\n\nThanks for reading. I'd be interested to hear about your own experiences building and testing AI-assisted applications.", "url": "https://wpnews.pro/news/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot", "canonical_source": "https://dev.to/don_buser_558e61f7bd75349/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot-in-python-4c79", "published_at": "2026-11-28 23:31:43+00:00", "updated_at": "2026-11-28 23:43:59.338453+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-agents", "ai-tools", "developer-tools"], "entities": ["Steve", "Python", "Flask", "Groq"], "also_reported_by": [], "takeaway": "Route every message through deterministic Python workflow handlers first and only call the LLM when no defined workflow owns the request, injecting labeled context blocks into the system prompt so the model uses computed data instead of its own assumptions.", "recommendation": {"advice": "Put deterministic state-machine handlers ahead of the LLM in your request path and reserve the model for genuinely open-ended turns, injecting labeled system context for each interaction.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot", "markdown": "https://wpnews.pro/news/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot.md", "text": "https://wpnews.pro/news/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot.txt", "jsonld": "https://wpnews.pro/news/where-not-to-use-the-llm-lessons-from-building-a-healthcare-front-office-chatbot.jsonld"}}