From Q&A to Task Execution: Engineering LLM Applications for Production
As AI shifts from answering questions to completing tasks, developers face new demands for accuracy, permissions, and observability. This article compares traditional search, general-purpose Q&A models, and agent applications, then walks through four engineering capabilities that make LLM applications production-ready: retrieval-augmented generation (RAG) to ground answers in evidence, hallucination suppression with verifiable outputs, agent orchestration with controlled tool use, and layered engineering practices for safe deployment. It includes practical guidance, pseudocode, evaluation metrics, risk classification, and a three-stage implementation roadmap.
1. Introduction: From “Giving Answers” to “Getting Things Done”
When a user asks, “Book me a table for four near my office tomorrow at 6 PM,” a traditional search engine can only return a list of restaurant links that the user must open, compare, and call one by one to confirm. A general-purpose Q&A model can offer advice like “you should call the restaurant ahead of time,” but the task still falls to the user. A new generation of AI applications can directly invoke a booking tool to make the reservation and then ask the user only to confirm. The interaction goal has shifted from “telling you what to do” to “getting the task done for you.”
For developers, this shift means a fundamental change in application form:
- Traditional search: retrieves existing pages and leaves the judgment to the user;
- Generative Q&A: produces text from parametric knowledge, and answers may be inaccurate;
- Agent applications: invoke internal tools or business APIs to produce real results that must be executable and traceable.
Agents turn “completing a task” into an engineering objective, but risks such as hallucination, mis-operation, and privilege overreach move up with it. This article covers four key capabilities:
- Grounding the model with retrieval augmentation so it can rely on evidence;
- Suppressing hallucinations through verification mechanisms so outputs can be checked;
- Enabling the model to act through agent orchestration;
- Using engineering practices so the system can safely go live.
All code in this article is language-agnostic illustrative pseudocode.
2. Technical Comparison of Three AI Product Forms
| Dimension | Traditional Search | General-Purpose Q&A Model | Agent Application |
|---|---|---|---|
| Interaction | Keyword search, browse links one by one | Natural language Q&A | Issue a task; the system plans and executes |
| Core output | List of links and snippets | Generated text | Text results plus real operations (placing orders, generating files, updating tickets) |
| Content source | Internet web pages | Parametric knowledge in training data | Business data plus real-time tool results |
| Trustworthiness | Depends on source authority and timeliness | Subject to hallucination; knowledge has a cutoff date | Depends on tool reliability and whether execution logic is controllable |
| User burden | Filter, judge, and act on your own | Still needs self-verification | Confirm only at key points |
| Main risk | Outdated information, uneven quality | Factual errors, fabricated citations | Mis-operation, privilege overreach, data leakage |
As the output gets closer to a “real action,” the requirements on accuracy, permissions, and observability rise accordingly. When a general-purpose Q&A model serves directly as an information-retrieval entry point, it is prone to outdated or even fabricated content, because its knowledge has a cutoff date and it cannot access real-time data. A more robust approach is to use retrieval augmentation to compensate for its knowledge gaps, then introduce controlled tool calling to extend its action capability.
3. The Foundation: Retrieval-Augmented Generation (RAG)
3.1 Why General-Purpose Q&A Falls Short
General-purpose LLMs are trained on massive public corpora and perform well at common-sense expression and natural language understanding, but using them directly in enterprise business scenarios typically has three shortcomings:
- Knowledge lag: training data has a cutoff date, so later product changes, policy adjustments, and price changes cannot be reflected;
- Inaccessible private data: contracts, policies, product manuals, customer records, and other internal materials are not in the training corpus;
- Hallucination tendency: when facing uncertain questions, the model tends to generate “plausible-looking” content rather than explicitly admitting it does not know.
Relying on fine-tuning to inject knowledge over the long term is not viable. Parametric knowledge is hard to trace, updating requires retraining, and writing sensitive data into model parameters introduces compliance risk.
3.2 The Basic Idea of Retrieval Augmentation
The core of Retrieval-Augmented Generation (RAG) is to externalize “memory”: after a user asks a question, the system first retrieves relevant snippets from an external knowledge base, then feeds them together with the question to the model to generate an answer. The model shifts from “answering from memory” to “answering based on materials,” gaining three properties:
- Evidence-based: answers are built on real materials;
- Traceable: every conclusion can be located back to the source text;
- Easy to update: only the knowledge base needs updating, with no model retraining required.
3.3 Offline Indexing Pipeline
Offline indexing determines the upper limit of retrieval quality:
- Data collection: connect internal systems, document libraries, web pages, transcribed audio/video text, and so on, and record metadata such as source, publish time, and visibility scope;
- Parsing and cleaning: extract text and tables from PDFs and scanned documents, and remove headers, footers, and duplicate content; OCR can help recognize scanned documents;
- Chunking: split into blocks along semantic boundaries such as headings and paragraphs, with a certain overlap between adjacent blocks (e.g., 10%–20% of block length) to avoid cutting off key information. Blocks that are too large introduce noise, while blocks that are too small lose context, so tuning is needed based on material type;
- Vectorization: use an embedding model to convert text blocks into vectors. Vector retrieval excels at semantic similarity, for example matching “leave application” with “time-off process”;
- Index building: build both a vector index and a keyword inverted index, and store the original text, source, and metadata for later filtering and citation.
def build_index(docs):"""Offline indexing: parse → clean → chunk → embed → write to index"""chunks = []for doc in docs:text = clean(parse(doc)) # parse and cleantitle_path = extract_heading_path(text) # record heading hierarchy, e.g. Chapter 2 > 2.3 Attendancefor seg in split(text, size=400, overlap=60): # split along semantic boundaries with overlapchunks.append({"text": seg,"meta": {"doc_id": doc.id,"title_path": title_path,"source": doc.source, # source, used for citation"updated_at": doc.updated_at, # update time, used for timeliness checks"acl": doc.acl # visibility scope, used for permission filtering}})vectors = embed([c["text"] for c in chunks]) # batch embeddingindex.upsert([(c, v) for c, v in zip(chunks, vectors)])
3.4 Online Retrieval: Hybrid Recall and Reranking
Online queries are recommended to follow five steps:
- Query understanding: correct typos, complete omitted information, and split multi-intent questions into multiple subqueries;
- Hybrid recall: run vector retrieval and keyword retrieval in parallel. Keyword retrieval is more sensitive to exact matches such as model numbers, IDs, and technical terms, compensating for the shortcomings of pure semantic retrieval;
- Permission filtering: filter visible documents by user identity. This step must happen at the retrieval stage rather than the generation stage, otherwise sensitive content could leak once it enters the model context;
- Reranking: use a cross-encoder to score candidate snippets one by one and select the most relevant few;
- Generation: organize the answer based on retrieved snippets and annotate citations.
def retrieve(query, user):"""Online retrieval: query understanding → hybrid recall → permission filtering → reranking"""subqueries = rewrite(query) # split multi-intent into multiple subqueriescandidates = []for q in subqueries:candidates += index.vector_search(embed(q), top_k=50)candidates += index.keyword_search(q, top_k=50)candidates = dedup(candidates) # merge and deduplicate# permission filtering must be done before feeding the results into the modelvisible = [c for c in candidates if user.can_access(c["meta"]["acl"])]ranked = rerank(query, visible) # cross-encoder rerankingreturn ranked[:8] # keep only the most relevant few snippets
3.5 Continuous Maintenance
- Incremental sync: when documents change, update the corresponding chunks and refresh the index; take deleted documents offline promptly;
- Timeliness priority: for questions involving prices, policies, and version numbers, prefer newer materials and note the material’s update time in the answer;
- Version management: retain document versions to enable tracing “which version of the material a given answer was based on at the time”;
- Regular evaluation: use a fixed Q&A set to regression-test chunking strategy, recall count, and reranking effectiveness.
4. Hallucination Suppression: Making Answers Verifiable
4.1 Sources of Hallucination
- Errors or outdated information in the training corpus itself;
- A time gap between the knowledge cutoff and the user’s question;
- When a question exceeds the model’s knowledge, the model tends to “fabricate” rather than admit it does not know;
- Loose prompt constraints that let the model improvise freely.
Retrieval augmentation can only mitigate the problem, and hallucination cannot be fully eliminated. What engineering can do is layer the defenses to make outputs verifiable and accountable.
4.2 Six Lines of Defense
- Evidence constraints: explicitly state in the prompt “answer only based on the provided materials; state honestly when materials are insufficient.” This is the most important and lowest-cost line of defense;
- Refusal and clarification: when evidence relevance falls below a threshold, do not force an answer; instead ask a follow-up or state that “nothing was found in the available materials”;
- Structured output validation: use a JSON Schema to constrain fields, types, and value ranges; on validation failure, retry or degrade;
Citation traceability: attach a source to every key conclusion, such as document name, section path, and update time. Example:
Per Section 3.2 of the 2024 revised edition of the Travel Expense Policy: the per-night accommodation cap for major cities is 600.
Conflict resolution: when different materials reach contradictory conclusions, present them side by side with their respective sources and timestamps rather than merging them arbitrarily;
- Human backstop for high-risk scenarios: for scenarios involving money, legal, or medical matters, position the output as a draft or suggestion for review by a qualified professional.
4.3 Measurable Evaluation
Optimizing for hallucination cannot rely on intuition; it needs a quantifiable metrics system:
| Metric | Meaning | Target |
|---|---|---|
| Answer accuracy | Proportion of answers that match the reference answer | Higher is better |
| Citation hit rate | Proportion of citations that actually support the conclusion | Higher is better |
| Unsupported answer rate | Proportion of cases that give an affirmative conclusion despite insufficient materials | Lower is better |
| Correct refusal rate | Proportion of questions that should be refused but are actually refused | Higher is better |
| Citation coverage | Proportion of key conclusions that carry a source among all key conclusions | Higher is better |
Specific practices:
- Build an offline evaluation set covering common questions, edge cases, and “not-in-knowledge-base” questions;
- Run regression tests after every change to prompts, chunking strategy, or model;
- Feed online user-correction cases back into the evaluation set to form a closed loop.
5. Agent Orchestration: Enabling the Model to Act
5.1 Core Components
An agent is a system that uses an LLM as its decision core and can autonomously plan and invoke tools to achieve a goal. It typically has four components:
- Planning: break “book a table for four tomorrow afternoon” into steps such as “understand time and party size → query available venues → submit reservation → return result”;
- Tool use: the model requests external capabilities through function calling in a predefined interface format. The real data returned by tools eliminates the model’s guessing about real-time information;
- Memory: short-term storage of the current task context and intermediate results, and long-term accumulation of user preferences (e.g., usual seat type, frequently visited areas);
- Reflection: when execution results do not meet expectations, adjust parameters, switch tools, or ask the user for clarification based on error information.
5.2 ReAct Loop and Structured Constraints
The ReAct paradigm widely used in industry lets the model alternate between “reasoning” and “acting”: think about the next step, call a tool to get results, then decide whether to continue or stop based on those results. Engineering implementation requires three constraints:
- Parameter validation: constrain tool input types, enum values, and value ranges with a JSON Schema; model-generated parameters must pass validation before execution;
- Step and timeout limits: set a maximum number of iterations and a total time budget to prevent infinite loops;
- Idempotency keys: generate a unique identifier for calls that may produce side effects; on retries after a network timeout, reuse the same identifier to avoid duplicate orders.
import json# Tool contract: name, purpose, parameter schema, and risk levelTOOL_ORDER_SEAT = {"name": "order_seat","description": "Reserve a seat for a given party size and return an order number","parameters": {"type": "object","properties": {"date": {"type": "string", "format": "date"}, # format like 2024-06-01"time": {"type": "string", "format": "time"}, # format like 18:30"size": {"type": "integer", "minimum": 1, "maximum": 20},"remark": {"type": "string"}},"required": ["date", "time", "size"],"additionalProperties": False},"risk": "write" # produces a business side effect, requires user confirmation}def run_tool(tool, args, context, confirmed=False):validate_schema(args, tool["parameters"]) # strict schema validation on parametersif tool["risk"] == "write" and not confirmed:return {"status": "need_confirm", "args": args} # write operations return to user for confirmation firstkey = f"{context.task_id}:{tool['name']}" # idempotency key: repeated calls in the same task won't double-bookreturn gateway.invoke(tool["name"], args, idem_key=key)
The tool layer should ideally be accessed uniformly through an API gateway, which centrally handles authentication, rate limiting, timeouts, and idempotency control. Tool descriptions should clearly state the purpose, the meaning of inputs, and the applicable boundaries; vague descriptions directly cause the model to select the wrong tool.
5.3 Risk Classification and Human Confirmation
Tool permissions are managed by risk classification:
| Risk level | Typical operations | Control strategy |
|---|---|---|
| Read-only | Query inventory, retrieve knowledge, compute | Execute directly and log the action |
| Reversible write | Create drafts, submit approval requests, add to cart | Show an operation summary before execution; user confirms with one click |
| Hard-to-reverse write | Payments, outbound sending, outbound phone calls | Require human confirmation; add a second verification (SMS code, one-time password) when necessary |
Write operations should support rollback or compensation, such as canceling an order or retracting a message, and should faithfully report execution results to the user.
5.4 Orchestration Example
def solve(task):plan = model.plan(task) # planning: decompose into a sequence of stepsmemory = [] # short-term memory: intermediate resultsfor step in plan.steps:for _ in range(MAX_STEPS): # iterate a limited number of times per stepaction = model.decide(step, memory)if action.type == "tool":result = run_tool(action.tool, action.args, task.ctx)if result["status"] == "need_confirm":# suspend the task and hand the operation summary to the user for confirmation; cancel on timeoutreturn ask_user_confirm(result["args"], task.ctx)elif action.type == "answer":return compose_answer(memory, citations=task.evidence)memory.append({"step": step.id, "action": action, "result": result})return compose_answer(memory, citations=task.evidence)
5.5 Boundaries of Voice Interaction
Voice interaction can significantly improve the user experience, such as issuing commands while driving. Technically, one pipeline typically includes speech recognition (ASR), intent understanding, tool calling, and speech synthesis (TTS), and it must handle the characteristics of spoken language:
- Spoken-language correction: parse “tomorrow evening around 6:30” into a normalized date and time;
- Information clarification: ask follow-ups when information is missing, e.g., “How many people will be dining?”;
- Structured confirmation: repeat key information by voice, e.g., “You’re booked for a table for four tomorrow at 18:30; let me know if you need any changes.”
If AI is to call real phone numbers and communicate with humans on a user’s behalf, relevant laws, regulations, and platform rules must be followed, ensuring the other party is informed and keeping complete call records for review.
6. From Materials to Deliverables: A Document-Driven Content Production Pipeline
6.1 Requirements and Deliverables Matrix
Students, researchers, and content creators often face the situation where the same material must produce multiple deliverables—for example, course slides need to become mind maps, review cards, and quizzes, while meeting notes need to become to-do lists and briefing reports.
| Input material | Deliverables that can be generated | Generation method |
|---|---|---|
| Course slides, textbooks | Mind maps, study guides, memory cards, quizzes | Model outputs a structured outline; program renders it |
| Long articles, papers, reports | Layered summaries, key-point lists, briefings | Abstractive summarization |
| Interview transcripts, recorded interviews | Quote highlights, character profiles, podcast scripts | Extract then rewrite |
| Meeting notes | Resolutions, to-do tasks (owner/deadline), follow-up emails | Structured extraction |
| Web pages, mixed image-text content | Publishing copy, alternative titles, image captions | Rewrite per channel conventions |
6.2 Two Design Principles
- Templating: the deliverable type is defined by a template that specifies structure and fields, and the model only fills in the content. This keeps the output format stable and makes programmatic rendering easy;
- Structure first: strongly structured deliverables such as mind maps, cards, and quizzes should be output by the model as structured nodes or items, then rendered into diagrams or layouts by the program, avoiding layout corruption caused by letting the model generate layout code directly.
ARTIFACT_SPECS = {"mindmap": { # mind map: output a node tree, rendered by the frontend"schema": {"type": "object","properties": {"title": {"type": "string"},"children": {"type": "array", "items": {"$ref": "#"}} # recursive node},"required": ["title"]}},"quiz": { # quiz: stem, options, answer, source"schema": {"type": "array","items": {"type": "object","properties": {"stem": {"type": "string"},"options": {"type": "array", "minItems": 2},"answer": {"type": "integer"},"source": {"type": "string"} # cite the original location the question is based on},"required": ["stem", "options", "answer", "source"]}}}}def generate_artifacts(material, types):knowledge = extract_knowledge(material) # extract knowledge points and structure first, parse only onceoutputs = []for t in types:spec = ARTIFACT_SPECS[t]raw = model.generate(prompt=build_prompt(spec, knowledge),schema=spec["schema"] # constrain the model's output structure)outputs.append(validate(raw, spec["schema"])) # retry or degrade on validation failurereturn outputs
6.3 Summarization Strategy by Level
Summaries can be graded by length and abstraction level:
- Extractive summary: directly selects key sentences from the original text; high fidelity and almost no new information introduced;
- Abstractive summary: the model paraphrases in its own words; better readability but requires citation verification.
The approach is to extract first, then rewrite, and finally cross-check key data against the original text for consistency.
6.4 Style Control and Quality Validation
- Style control: constrain the audience (students, management, readers), tone (formal, colloquial), length, and terminology preferences through instruction templates; require numbers, dates, and names to be preserved verbatim;
- Consistency validation: run automated checks on generated results, including whether numbers and dates match the original, whether key points cover the original’s key paragraphs, and whether quiz answers are unique and correct;
- One-click multi-output: parsing and knowledge extraction run only once, and deliverables are rendered in batches by template. For example, the same material can simultaneously output “a one-page briefing, a set of mind maps, and a set of review cards,” avoiding repeated model calls and reducing token costs.
7. Engineering Deployment: Making the System Safe to Launch
7.1 Layered Architecture
It is recommended to decouple by responsibility:
- Model layer: responsible for understanding and generation, including dialogue, reasoning, and structured output;
- Knowledge layer: responsible for retrieval augmentation, including document ingestion, parsing and chunking, indexing, and reranking;
- Tool layer: responsible for connecting to business systems, centrally handling authentication, rate limiting, idempotency, and auditing through an API gateway;
- Business layer: carries specific scenario logic, such as parameter completion, validation rules, risk classification, and human confirmation;
- Interaction layer: provides text, voice, and multi-platform interfaces, and displays citations and execution status.
The benefit of layering is that the model can be swapped out while knowledge and tools evolve independently. The cloud infrastructure hosting these components can be deployed on demand using compute, storage, and networking products from cloud platforms such as Baidu AI Cloud; refer to the official documentation for specific specifications.
7.2 Model Routing
Different stages have very different requirements for model capability, so there is no need to use the most capable, most expensive model everywhere:
- Tasks such as intent classification, entity extraction, and query rewriting can use lightweight models;
- Tasks such as multi-step reasoning and long-form generation then use higher-capability models;
- High-frequency requests with stable results can be cached and reused to reduce latency and cost.
7.3 Observability
- Logging: record the user’s question, retrieved snippets, the model’s raw output, tool-call parameters and return codes, to make issues reproducible;
- Metrics: monitor time-to-first-token, end-to-end latency, tool-call success rate, model token counts, and human-confirmation pass rate;
- Alerting: notify promptly when tool error rates or hallucination-related complaints spike, and retain the most recent complete call chains for troubleshooting.
7.4 Stability and Degradation
- Set timeouts and limited retries for tool calls; retries reuse the idempotency key;
- When the retrieval service is unavailable, degrade to “answer based only on the model’s general knowledge with a clear notice,” or route to a human;
- When a single step fails, the agent should retry or take an alternative path based on error information rather than fabricating a result directly.
7.5 Security and Compliance
- Least privilege: grant the agent’s credentials only the minimum permissions necessary to complete the task;
- Sensitive-data masking: redact personal information such as ID numbers, phone numbers, and bank card numbers in logs;
- Audit traceability: record the operator, time, parameters, and result of all write operations to meet audit requirements;
- Data boundaries: documents uploaded by users are used only within their authorized scope, with a clear data-retention period;
- Human backstop: for operations involving funds and external commitments, insist on human confirmation, and position AI output as decision support.
8. Implementation Roadmap and Conclusion
It is recommended to proceed in three stages:
- Knowledge Q&A stage: build a retrieval-augmented knowledge base that outputs answers with citations, establish an evaluation set, and validate the quality of the knowledge layer;
- Content production stage: connect the document-parsing and templated-generation pipeline so the same material produces multiple deliverables in batches;
- Task execution stage: introduce agents under the premise that business systems expose controlled APIs, execute tool calls by risk classification, first covering read-only tasks and then gradually opening up write operations that require confirmation.
When selecting technology, focus on six dimensions:
- Retrieval quality (recall rate, reranking effectiveness);
- Hallucination control (refusal mechanisms, citation capability);
- Tool ecosystem (API openness, idempotency support);
- Security and compliance (permission systems, audit logs);
- Observability;
- Cost structure.
To judge whether an AI application truly creates value, do not look at how much it can say, but at whether it can reliably complete the user’s task under conditions that are controllable, verifiable, and rollback-capable.
