Chapter 13
LLM Application Patterns
Chapter 13: LLM Application Patterns
Large Language Models are not useful only because they can chat. Their real power appears when they are placed inside application patterns: repeatable designs for solving business problems using prompts, retrieval, tools, workflow rules, APIs, databases, and user interfaces. This chapter explains the most common LLM application patterns in a practical way so that you can identify which pattern fits a real project.
A pattern is a reusable solution style. For example, a chatbot pattern is useful when a user needs conversation. A classification pattern is useful when an incoming message must be assigned to a category. A report generation pattern is useful when structured data must be converted into readable business language. Once you learn these patterns, you can design many AI applications confidently.
After completing this chapter, you should be able to look at a business requirement and decide whether it needs a chatbot, RAG-based document Q&A, summarizer, classifier, extractor, SQL generator, email assistant, workflow automation assistant, or multi-modal AI application. You should also be able to draw a simple architecture and write a first version of the prompt for each pattern.
An LLM application pattern is a standard way of using a language model to solve a particular type of task. The LLM is only one part of the application. A real application also needs input handling, authentication, prompt templates, data retrieval, validation, output formatting, monitoring, and sometimes human approval.
For example, suppose a company wants an AI system that reads customer emails and decides whether the issue is related to billing, technical support, cancellation, refund, or sales. This is not mainly a chatbot problem. It is a classification problem. The best design is usually an LLM classification pattern, possibly supported by examples, business rules, and confidence scoring.
Suppose another company wants employees to ask questions such as, "How many paid leaves can I carry forward?" The answer must come from the company HR policy. This is not only a general chat problem. It is a document Q&A or RAG pattern because the model must retrieve relevant policy content before answering.
|
Requirement type |
Useful pattern |
|
User wants conversation |
Chatbot |
|
User asks questions from documents |
Document Q&A / RAG |
|
Long text must become short |
Summarization |
|
Input must be assigned to a label |
Classification |
|
Specific fields must be pulled from text |
Extraction |
|
Numbers must be converted into business language |
Report generation |
|
User wants help analyzing data |
Data analysis assistant |
|
User wants code help |
Code assistant |
|
User wants database answers from natural language |
SQL generation |
|
User wants email drafting or reply help |
Email assistant |
|
Customer issue must be handled automatically |
Customer support automation |
|
Ticket must go to the correct team |
Ticket routing |
|
Company knowledge must be searchable by AI |
Knowledge base assistant |
|
AI must perform multi-step tasks |
Workflow automation |
|
AI must handle text plus images/audio/video |
Multi-modal AI application |
Although each pattern solves a different problem, many of them use the same building blocks. Understanding these blocks helps you design any LLM application more easily.
User / System Input
|
v
Application UI or API
|
v
Prompt Template + Business Rules
|
+---- Optional Retrieval from Documents / Database / Tools
|
v
LLM Call
|
v
Output Parser / Validator / Guardrails
|
v
Final Response / Action / Workflow Update
|
v
Logs, Feedback, Evaluation, Monitoring
The core idea is simple: collect the input, prepare the model instruction, optionally retrieve supporting data, call the LLM, validate the answer, and return the result to the user or downstream system.
A chatbot allows users to interact with an AI system through conversation. The user can ask follow-up questions, clarify requirements, and receive answers in a natural language format. Chatbots are useful for learning assistants, support assistants, HR assistants, sales assistants, and internal productivity tools.
User Chat Window
|
v
Conversation API
|
v
Session History + User Profile + Prompt Template
|
v
LLM
|
v
Safety Check + Response Formatter
|
v
Chat Response
|
Input |
Output |
|
User message, previous conversation history, user role, optional business context. |
Natural language answer, clarification question, instruction, or formatted response. |
You are a helpful support assistant. Answer the user clearly and ask a clarifying question only when required. User question: "I cannot login after password reset. What should I do?"
Please try clearing your browser cache and then login again with the new password. If the issue continues, check whether your account is locked. I can also help you prepare a support ticket with the error message and your user ID.
Document Q&A allows users to ask questions from PDFs, Word files, web pages, policy documents, manuals, contracts, standard operating procedures, and knowledge articles. This pattern usually uses RAG because the LLM must retrieve the most relevant document chunks before answering.
Documents -> Chunking -> Embeddings -> Vector Database
^
|
User Question -> Query Embedding -> Retriever -> Relevant Chunks
|
v
Prompt + Context
|
v
LLM
|
v
Answer with Sources
|
Input |
Output |
|
User question and a document collection already indexed in a vector database. |
Answer grounded in retrieved document context, often with source references. |
Answer the question only using the provided policy context. If the answer is not available, say that the policy does not provide enough information. Question: "How many casual leaves can an employee take in a year?" Context: {retrieved_policy_chunks}
According to the provided HR policy context, employees are eligible for 12 casual leaves per calendar year. The policy also says unused casual leave cannot be carried forward.
Summarization converts long content into shorter, useful content. It is used for meeting notes, long reports, emails, legal documents, call transcripts, medical discharge summaries, customer complaints, and research papers.
Long Text / Document
|
v
Pre-processing and Chunking
|
v
Chunk-level Summaries
|
v
Summary Merger
|
v
Final Summary + Key Points + Action Items
|
Input |
Output |
|
Long text, document, transcript, report, or multiple files. |
Short summary, executive summary, bullet summary, action items, risks, or decision notes. |
Summarize the following customer call transcript for a support manager. Include issue, customer sentiment, promised action, and next step. Transcript: {transcript}
Issue: The customer is unable to access the billing portal. Sentiment: Frustrated but cooperative. Promised action: Support will reset the account session and share a new login link. Next step: Follow up within 24 hours and confirm login success.
Classification assigns input text to one or more predefined categories. It is useful for ticket routing, sentiment detection, email triage, fraud alert grouping, document type detection, risk classification, and intent recognition.
Incoming Text
|
v
Prompt with Label Definitions + Examples
|
v
LLM Classifier
|
v
JSON Output: label, confidence, reason
|
v
Workflow Rule / Dashboard / Queue
|
Input |
Output |
|
Text to classify and list of allowed labels with definitions. |
Category, confidence score, short reason, and optionally next action. |
Classify this IT ticket into one of: Network, Hardware, Database, Security, HR Payroll, Application Support. Return JSON only. Ticket: "I clicked a suspicious email link and now my laptop is behaving strangely."
{"category":"Security","confidence":"high","reason":"The ticket mentions a suspicious email link and possible compromised device behavior."}
Extraction pulls specific fields from unstructured or semi-structured text. It is used to extract invoice details, resume skills, contract dates, patient discharge details, customer names, complaint IDs, order numbers, and policy clauses.
Source Text / Document
|
v
Extraction Prompt + Schema
|
v
LLM
|
v
JSON Parser + Validation
|
v
Database / API / Review Screen
|
Input |
Output |
|
Document text and required output schema. |
Structured JSON, table, CSV row, or database-ready object. |
Extract invoice_number, vendor_name, invoice_date, total_amount, currency, and payment_due_date from this invoice text. Return JSON only. Text: {invoice_text}
{"invoice_number":"INV-2026-1045","vendor_name":"ABC Services Pvt Ltd","invoice_date":"2026-06-10","total_amount":45000,"currency":"INR","payment_due_date":"2026-07-10"}
Report generation converts data, metrics, and findings into readable business reports. It is used in finance, sales, project management, operations, risk management, and executive dashboards.
Structured Data / Metrics
|
v
Data Aggregation + Business Rules
|
v
Report Prompt Template
|
v
LLM
|
v
Formatted Report: Summary, Trends, Risks, Recommendations
|
Input |
Output |
|
Metrics, tables, KPI values, comments, time period, and audience type. |
Executive summary, detailed report, risk analysis, recommendation section, or email-ready report. |
Create a weekly project status report for senior management using these metrics: completed_tasks=42, delayed_tasks=6, open_risks=3, budget_used=72%, sprint_goal_status="at risk". Include summary, risks, and recommended actions.
This week the project completed 42 tasks, but the sprint goal is at risk due to 6 delayed tasks and 3 open risks. Budget consumption is at 72%, which is acceptable but should be monitored. Recommended actions: review delayed tasks, assign owners to risks, and re-check sprint scope.
A data analysis assistant helps users understand datasets, ask questions about metrics, generate charts, identify anomalies, explain trends, and create insights. In production, the LLM should not freely guess from data. It should use tools such as SQL, Python, BI APIs, or governed semantic layers.
User Question
|
v
Intent Understanding
|
+--> Data Catalog / Schema Lookup
|
+--> SQL or Python Tool
|
v
Verified Result Table / Chart Data
|
v
LLM Explanation
|
v
Insight + Caveats + Next Questions
|
Input |
Output |
|
Natural language question, dataset schema, business definitions, and allowed analysis tools. |
Insight, table, chart description, trend explanation, anomaly explanation, or next-step recommendation. |
The following sales data has already been calculated by SQL. Explain the trend for a business user and mention possible reasons without claiming certainty. Data: {monthly_sales_table}
Sales increased steadily from January to March, dropped slightly in April, and recovered in May. The recovery may indicate improved demand or campaign impact, but campaign and market data should be checked before making a final conclusion.
A code assistant helps developers write, explain, debug, refactor, document, and test code. It can improve productivity, but it must be used carefully because generated code may be insecure, outdated, or incompatible with the project environment.
Developer Request
|
v
Project Context + Language + Framework + Error Logs
|
v
LLM Code Assistant
|
v
Generated Code / Explanation / Test Cases
|
v
Developer Review + Unit Tests + Security Scan
|
Input |
Output |
|
Requirement, existing code, error message, stack trace, language, framework, and constraints. |
Code snippet, explanation, debugging steps, test case, refactoring plan, or documentation. |
Explain why this Python function fails and provide a corrected version. Keep the answer beginner-friendly. Code: {code_snippet}
The function fails because it tries to add a string and an integer. Convert the input to an integer before addition, and handle invalid input using try/except.
SQL generation allows users to ask questions in natural language and receive SQL queries or data answers. It is useful for analytics, reporting, business intelligence, and self-service data access. This pattern should be designed with strong safeguards because SQL can access sensitive data or produce expensive queries.
Natural Language Question
|
v
Schema + Business Definitions + Security Rules
|
v
LLM Generates SQL
|
v
SQL Validator / Permission Check / Cost Guard
|
v
Database Execution
|
v
Result Explanation
|
Input |
Output |
|
User question, database schema, table descriptions, column definitions, and access rules. |
SQL query, result table, explanation, or error clarification. |
Generate SQL for BigQuery. Use only the provided schema. Question: "Show total sales by month for 2026." Schema: sales(order_id, order_date, amount, customer_id). Return SQL only.
SELECT FORMAT_DATE("%Y-%m", order_date) AS sales_month, SUM(amount) AS total_sales FROM sales WHERE EXTRACT(YEAR FROM order_date) = 2026 GROUP BY sales_month ORDER BY sales_month;
An email assistant drafts, rewrites, summarizes, classifies, and responds to emails. It can save time in sales, HR, support, operations, project management, and customer communication.
Email Thread / User Instruction
|
v
Context Builder: recipient, tone, purpose, constraints
|
v
LLM Draft Generator
|
v
Policy Check + Human Review
|
v
Draft / Send / Archive / Follow-up Reminder
|
Input |
Output |
|
Email thread, desired tone, objective, recipient type, and action requested. |
Draft email, reply, subject line, summary, or follow-up note. |
Draft a polite email to a customer explaining that the refund is approved and will be processed within 5 business days. Keep it professional and concise.
Subject: Refund Approval Update
Dear Customer,
Your refund request has been approved. The amount will be processed within 5 business days and credited to your original payment method. Thank you for your patience.
Regards,
Support Team
Customer support automation combines multiple patterns: classification, summarization, RAG, response drafting, workflow action, and escalation. It helps reduce response time and improve support consistency.
Customer Message
|
v
Classify Intent + Priority + Sentiment
|
+--> Retrieve Knowledge Articles / Policies
|
v
Draft Response + Suggested Action
|
v
Confidence Check
|
+--> Auto Reply if Safe
+--> Human Agent if Risky
|
v
Ticket Update + Monitoring
|
Input |
Output |
|
Customer message, account metadata, product information, knowledge base, and support policies. |
Suggested response, ticket category, priority, knowledge article, resolution step, or escalation. |
A customer wrote: "My payment was deducted but order is not showing." Classify issue, suggest priority, draft response, and mention required backend check.
Category: Payment/Order Sync. Priority: High. Draft: We are sorry for the inconvenience. Please share your transaction ID so we can verify the payment and order status. Backend check required: payment gateway confirmation and order creation log.
Ticket routing sends incoming issues to the correct team or queue. It is widely used in IT service management, HR helpdesks, banking operations, telecom support, and enterprise shared services.
Incoming Ticket
|
v
Clean Text + Extract Entities
|
v
Classify Category + Urgency + Product
|
v
Routing Rules
|
v
Assigned Team + SLA + Suggested First Response
|
Input |
Output |
|
Ticket title, description, user department, product, attachment metadata, and historical ticket examples. |
Assigned team, category, priority, SLA, and explanation. |
Route this ticket to the correct team. Teams: Network, Hardware, Database, Security, Application Support, HR Payroll. Ticket: "Oracle server connection timeout from reporting app." Return JSON.
{"team":"Database","priority":"medium","reason":"The issue mentions Oracle server connection timeout, which is usually handled by the database team. Application support may be involved if DB is healthy."}
A knowledge base assistant helps employees or customers find accurate answers from approved articles, FAQs, manuals, policies, and troubleshooting guides. It is similar to document Q&A but often includes article ranking, feedback, and content improvement suggestions.
Knowledge Articles / FAQs / Manuals
|
v
Indexing: metadata + embeddings + keyword search
|
v
User Question
|
v
Hybrid Retrieval + Re-ranking
|
v
LLM Answer + Article Links
|
v
Feedback: helpful/not helpful + gap detection
|
Input |
Output |
|
User question, knowledge base content, metadata, article quality signals, and access permissions. |
Answer, article links, step-by-step guide, or escalation suggestion. |
Using the retrieved knowledge base articles, answer the user question and include the most relevant article title. Question: "How do I reset VPN access after password change?" Context: {articles}
After a password change, disconnect the VPN client, sign in with the new password, and approve MFA. If login still fails, clear saved credentials and retry. Relevant article: "VPN Login After Password Reset".
Workflow automation uses an LLM to understand instructions, decide next steps, call tools, update systems, create tasks, send drafts, or trigger approvals. This pattern is powerful but must be designed with clear permissions and safety checks.
User Request
|
v
Intent + Required Action Detection
|
v
Plan Steps
|
+--> Tool/API Calls
+--> Human Approval for Sensitive Actions
|
v
Execute Workflow
|
v
Confirm Result + Log Action
|
Input |
Output |
|
User request, available tools, permissions, business rules, and system state. |
Completed workflow, draft action, task creation, system update, or approval request. |
The user says: "Create a follow-up task for the payment issue and assign it to the billing team." Identify the workflow steps and return a safe action plan.
Action plan: 1) Create support task titled "Payment issue follow-up". 2) Assign to Billing Team. 3) Link it to the original ticket. 4) Set due date according to SLA. 5) Notify the user after task creation.
Multi-modal applications process more than one type of input: text, images, audio, video, documents, tables, and sometimes sensor data. They are useful for medical imaging support, insurance claim inspection, product catalog search, education, accessibility, manufacturing quality checks, and visual document understanding.
Text / Image / Audio / Video Input
|
v
Modality-specific Pre-processing
|
+--> OCR / Speech-to-Text / Image Understanding / Frame Extraction
|
v
Multi-modal Model or LLM + Tools
|
v
Structured Output / Explanation / Recommendation
|
Input |
Output |
|
Text plus image, scanned document, audio transcript, video frames, or mixed content. |
Description, classification, extracted fields, answer, recommendation, or generated content. |
Analyze this product damage image and customer description. Identify visible damage, classify severity, and suggest next support action. Description: "The package arrived with a broken corner."
Visible issue: corner damage is reported and may be packaging-related. Severity: medium, pending image verification. Suggested action: request order ID, confirm if product is affected, and initiate replacement workflow if damage is confirmed.
In real systems, one application often uses multiple LLM patterns together. A customer support solution may classify the ticket, summarize the message, retrieve a knowledge article, draft a response, update the ticket, and route the case to a team. A document assistant may combine document Q&A, summarization, extraction, and report generation. A data assistant may combine SQL generation, data analysis, report generation, and email drafting.
Example: Enterprise Support Copilot
Customer Message
|
+--> Classification: billing / technical / refund / complaint
|
+--> Extraction: order number, product, issue date
|
+--> RAG: retrieve policy and troubleshooting article
|
+--> Summarization: create short case summary
|
+--> Response Drafting: prepare customer reply
|
+--> Workflow Automation: create task / escalate / update CRM
|
v
Human Review or Auto Resolution
The most important design skill is not memorizing patterns separately, but knowing how to combine them safely. Start with the smallest useful pattern, test it, then add more capabilities step by step.
|
Question |
Recommended pattern |
|
Do users need a conversational interface? |
Chatbot |
|
Must answers come from documents? |
Document Q&A / Knowledge Base Assistant |
|
Is the input too long and needs reduction? |
Summarization |
|
Do you need to assign a category? |
Classification |
|
Do you need fields in JSON/table format? |
Extraction |
|
Do you need narrative from metrics? |
Report Generation |
|
Do users ask business questions from data? |
Data Analysis Assistant / SQL Generation |
|
Do developers need code help? |
Code Assistant |
|
Do support cases need end-to-end handling? |
Customer Support Automation |
|
Do tasks need system actions? |
Workflow Automation / Agents |
|
Do inputs include images, audio, or video? |
Multi-modal AI Application |
Let us design a practical AI helpdesk assistant for an IT department. Employees submit support tickets in natural language. The AI assistant should classify the ticket, summarize the issue, route it to the correct team, retrieve a helpful article, and draft the first response.
Employee Ticket
|
v
Text Cleaner and PII Masker
|
+--> Classification Pattern: team and category
+--> Summarization Pattern: short issue summary
+--> Extraction Pattern: system name, error code, urgency
+--> Knowledge Base Assistant: relevant article
+--> Email/Response Assistant: draft reply
|
v
Ticket Update + Human Agent Review
Subject: VPN not working after password reset
Description: I changed my password this morning. Now VPN is not accepting the new password. I need access urgently for client work.
Category: Network / VPN
Priority: High
Summary: User cannot login to VPN after password reset and needs urgent access.
Extracted entity: VPN, password reset, client work urgency
Suggested article: VPN login after password change
Draft response: Please clear saved VPN credentials, restart the VPN client, and login using the new password. If MFA is enabled, approve the login prompt. If the problem continues, we will reset your VPN profile.
Classification alone only gives the team. Summarization helps the support agent quickly understand the issue. Extraction captures system and urgency. Knowledge base retrieval gives a reliable troubleshooting step. Response drafting saves time. Together, these patterns create a useful business application.
|
Mistake |
Why it is a problem |
Better approach |
|
Using a chatbot for every problem |
Many tasks need classification, extraction, or retrieval instead of open conversation. |
Choose the pattern based on the output required. |
|
No output validation |
The model may return invalid JSON, wrong labels, or unsupported answers. |
Use parsers, schemas, rules, and tests. |
|
No source grounding |
Answers can hallucinate when they require private knowledge. |
Use RAG or approved knowledge base retrieval. |
|
Letting the LLM do calculations |
LLMs can make arithmetic and aggregation mistakes. |
Use SQL/Python for calculations, LLM for explanation. |
|
No human review for risky actions |
Wrong automation can affect customers or systems. |
Add approval gates for high-impact actions. |
|
Ignoring cost and latency |
Long prompts and unnecessary context increase cost. |
Optimize prompt, context, model choice, and caching. |
A useful exercise is to build a simple AI pattern selector. The user enters a business requirement, and the system recommends the best LLM pattern with an explanation.
def select_llm_pattern(requirement):
if mentions_documents_or_policy(requirement):
return "Document Q&A / RAG"
if asks_for_category_or_team(requirement):
return "Classification / Ticket Routing"
if asks_to_extract_fields(requirement):
return "Extraction"
if asks_for_shorter_version(requirement):
return "Summarization"
if asks_to_query_database(requirement):
return "SQL Generation / Data Analysis Assistant"
if asks_to_perform_actions(requirement):
return "Workflow Automation"
return "Chatbot or General Assistant"
This chapter explained the most important LLM application patterns used in practical AI systems. A chatbot is useful for conversation, but it is not the answer to every problem. Document Q&A uses retrieval to answer from trusted documents. Summarization reduces long content. Classification assigns labels. Extraction converts unstructured text into structured data. Report generation converts metrics into business language. Data analysis assistants use tools and verified results. Code assistants help developers but require review. SQL generation enables natural language access to databases but needs strong security. Email assistants improve communication. Customer support automation and ticket routing combine several patterns. Knowledge base assistants use approved content. Workflow automation performs multi-step actions with tools and approvals. Multi-modal applications handle text, images, audio, and video.
The key lesson is that LLM applications should be designed as systems, not just prompts. Each pattern has input, architecture, output, risks, and best practices. A good AI developer chooses the correct pattern, grounds the model when needed, validates the output, protects data, monitors quality, and adds human review where risk is high.
|
Term |
Meaning |
|
LLM application pattern |
A reusable design for solving a specific type of task using a language model. |
|
Chatbot |
A conversational AI interface that responds to user messages. |
|
Document Q&A |
A pattern where users ask questions and the system answers from documents. |
|
Summarization |
The process of converting long content into shorter useful content. |
|
Classification |
Assigning text to one or more predefined categories. |
|
Extraction |
Pulling specific structured fields from text or documents. |
|
Report generation |
Creating readable business reports from data or metrics. |
|
SQL generation |
Creating database queries from natural language questions. |
|
Knowledge base assistant |
An AI assistant that answers using approved knowledge articles. |
|
Workflow automation |
Using AI to understand instructions and trigger actions through tools or APIs. |
|
Multi-modal AI |
AI that can process multiple input types such as text, images, audio, and video. |
|
Pattern |
Best for |
Typical output |
Needs retrieval? |
Needs human review? |
|
Chatbot |
Conversation |
Natural response |
Sometimes |
Sometimes |
|
Document Q&A |
Answers from documents |
Grounded answer + source |
Yes |
For sensitive topics |
|
Summarization |
Long content reduction |
Summary/action items |
No, unless sources are external |
Sometimes |
|
Classification |
Labels and routing |
Category + confidence |
Sometimes |
For low confidence |
|
Extraction |
Structured fields |
JSON/table |
No, but validation needed |
For critical fields |
|
Report generation |
Business narrative |
Report |
Sometimes |
Often |
|
Data analysis assistant |
Data insights |
Explanation/chart/table |
Uses data tools |
Sometimes |
|
Code assistant |
Developer help |
Code/explanation/tests |
Sometimes |
Yes, code review |
|
SQL generation |
Database questions |
SQL/result explanation |
Schema retrieval |
For risky queries |
|
Email assistant |
Drafting replies |
Email draft |
Sometimes |
Usually before sending |
|
Support automation |
Ticket handling |
Reply/action/escalation |
Often |
For risky cases |
|
Workflow automation |
Multi-step actions |
System action |
Sometimes |
Yes for sensitive actions |
|
Multi-modal AI |
Text + image/audio/video |
Description/extraction/action |
Sometimes |
For high-risk domains |