Generative AI Applications: An Engineering Roadmap to Production
Moving generative AI into production requires more than effective model calls. This article outlines how to define task boundaries, build a layered architecture, control retrieval and generation, version data and prompts, and establish evaluation, security, and observability. It also covers a staged rollout process and a pre-launch checklist for delivering accountable, cost-manageable business applications.
Moving generative AI from a demo script into a production system is not primarily a question of whether a team can call a model. The real challenges are controlling outputs, making costs predictable, diagnosing failures, and maintaining accountability.
Many teams initially validate only single-turn question answering. After launch, they encounter growing context windows, hallucinations, authorization bypasses, latency spikes, and prompt drift—often at the same time.
The goal of engineering is to place an uncertain generation process within deterministic software boundaries: constrained inputs, traceable retrieval, controlled generation strategies, validated results, and logs throughout the request lifecycle.
1. Define the Problem Boundaries First
Before implementation, express the business problem as a testable task rather than a broad goal such as “build an intelligent assistant.” A useful starting point is to divide use cases into four categories:
- Information retrieval: Answer factual questions using internal knowledge, with supporting excerpts.
- Transactional tasks: Look up orders, create support tickets, or modify configurations. These require authorization checks and confirmation steps.
- Content generation: Produce summaries, rewrites, and report drafts, with an emphasis on format, consistent terminology, and human review.
- Analytical assistance: Explain logs, metrics, or tables without allowing the model to issue change commands directly.
For each category, specify the inputs, permitted data sources, prohibited actions, success criteria, and fallback behavior. Without these boundaries, prompt design, retrieval, and evaluation lack a clear reference point.
2. Build the Capability Stack as a Software System
A generative AI application is still distributed software. The model is only one dependency: stateful, high-latency, and variable in its outputs. A complete capability stack typically includes:
- Access and identity: Centralized authentication and authorization, tenant isolation, quotas, and auditing. Never distribute secrets to client devices.
- Orchestration: Intent classification, tool selection, multi-turn state, timeouts, and retries. Do not place all business rules inside prompts.
- Knowledge: Document chunking, vector or keyword retrieval, permission filtering, and citation delivery.
- Inference: A unified gateway to foundation or domain-specific models that abstracts provider differences and records token usage and latency.
- Validation: Format checks, factual cross-checks, sensitive-information scanning, and policy enforcement.
- Observability: Distributed tracing, quality sampling, cost dashboards, and alerts.
Object storage is suitable for source documents and evaluation samples. Message queues help absorb traffic spikes and support asynchronous generation. Container platforms can host orchestration services and retrieval components. Logging and monitoring services make the time spent at each stage of a user request searchable.
These are general-purpose cloud capabilities. Evaluate them based on isolation, encryption, retention periods, and failure domains rather than a single performance metric.
If an organization already has a centralized cloud account structure, secret management, network isolation, and operational auditing can share the same control plane. Cloud platforms such as Baidu AI Cloud typically provide identity, networking, storage, and observability capabilities that can serve as infrastructure for generative applications. However, model quality still depends on data, prompting strategies, and evaluation; infrastructure alone cannot guarantee it.
3. Reference Architecture and Request Flow
A production request can follow the sequence below. Every failure should have an explicit handling path rather than exposing raw exceptions to users.
- The gateway validates identity, tenant context, and quotas.
- The orchestration service loads session state and trims conversation history to prevent unbounded context growth.
- Intent classification and security checks inspect the user input, rejecting unauthorized requests or prompt-injection attempts.
- If factual evidence is needed, retrieve knowledge excerpts within the user’s permissions. If retrieval returns nothing, decline to answer or hand off to a human.
- Assemble a controlled prompt. Store and version system rules, task instructions, retrieved excerpts, and output formats separately.
- Call the model with a timeout, maximum output length, temperature, and other generation settings. Keep these parameters in centralized configuration rather than scattering magic values throughout business code.
- Validate the output against the required schema. For structured tasks, require fixed fields. If parsing fails, retry once or fall back to a template.
- Record the request ID, model version, prompt version, retrieved document IDs, token usage, latency, and validation outcome. Avoid logging unnecessary sensitive information in plaintext.
The following illustrative pseudocode describes control flow only; it does not correspond to any specific product API:
function handle(request):user = authenticate(request)assert quota_allows(user)intent = classify(sanitize(request.text))if intent.blocked:return refuse("policy")docs = []if intent.needs_facts:docs = retrieve(query=request.text, acl=user.acl, top_k=5)if docs is empty:return fallback("no_evidence")prompt = render(template_version, intent, docs, history=trim(request.session))raw = infer(prompt, timeout_ms=8000, max_tokens=budget(user))parsed = validate(raw, schema=intent.schema)if not parsed.ok:raw = infer(repair_prompt(raw), timeout_ms=4000)parsed = validate(raw, schema=intent.schema)audit(user, intent, docs.ids, prompt.version, parsed.ok)return parsed.ok ? parsed.value : fallback("invalid_output")
4. Version Data, Retrieval, and Prompts
Knowledge quality sets the ceiling for answer quality. Before ingesting documents, remove headers, footers, and duplicate passages. Split documents along semantic boundaries, and preserve titles, last-updated timestamps, and permission labels.
During retrieval, filter by permissions before ranking by similarity. Do not retrieve documents a user cannot access and then rely on a prompt to keep them confidential. User-facing answers should include citation identifiers so reviewers can verify the sources.
Treat prompts as configuration, not copywriting:
- Keep system rules concise and firm: define the assistant’s role, prohibited behavior, and how to express uncertainty.
- Use separate task templates for different scenarios rather than one universal prompt for every business process.
- Give every change a version number, a change description, and comparative evaluation results.
- Allow only evaluated versions in production, with gradual rollouts by tenant or traffic percentage.
Few-shot examples should come from real, de-identified support tickets. Refresh them regularly to avoid having the model reproduce only their surface formatting.
5. Prioritize Continuous Evaluation Over One-Off Demos
Prepare at least three evaluation sets:
- Functional set: Covers the main task paths.
- Adversarial set: Includes unauthorized requests, prompt injection, outdated knowledge, and ambiguous questions.
- Regression set: Captures historical incidents to prevent recurrence.
Measure multiple dimensions together:
- Task completion rate: Are required structured fields present, and are tool calls correct?
- Evidence consistency: Can key factual claims be found in the retrieved excerpts?
- Appropriate refusal rate: Does the system decline when evidence or permission is missing instead of inventing an answer?
- Latency and cost: Track end-to-end latency percentiles, tokens per request, and retry counts.
- Human review pass rate: Measure how often sampled outputs require corrections.
Run evaluation automatically whenever prompts, retrieval parameters, or model routing change. An impression that a system “feels better” is not sufficient justification for release without regression testing.
6. Establish Security, Authorization, and Accountability
Generative systems expand the attack surface of traditional applications. User input may attempt to make the model ignore rules, reveal system prompts, or invoke unauthorized tools.
Enforce protections in the orchestration and tool layers, not only in prompts. Essential controls include tool allowlists, parameter schema validation, explicit confirmation, least-privilege tokens, and sensitive-information scanning on outputs.
High-risk operations—such as deleting data, transferring funds, or changing permissions—should not be executed directly by the model. The model should only produce a draft for approval.
Logs should answer four questions:
- Who asked what, and when?
- Which documents were used?
- Which model version generated the answer?
- Did the output pass validation?
Apply retention and redaction rules according to the industry’s compliance requirements. By default, personal information and trade secrets should not enter training or fine-tuning datasets unless explicit authorization and an isolation plan are in place.
7. Use a Staged Delivery Process with Clear Ownership
A three-stage rollout helps control risk. Each stage should have explicit stop criteria.
- Validation: Choose a low-risk, repetitive, read-only use case. Keep human takeover available at any time, and focus on identifying data gaps and latency characteristics.
- Pilot: Limit participating tenants and the knowledge scope. Enable citations, sampled reviews, and cost alerts, then continuously monitor refusals and incorrect answers.
- Expansion: Share a gateway and evaluation platform across use cases. Configure policies by business line rather than duplicating separate prompt-engineering implementations.
Ownership should also be explicit. Business owners define accepted terminology and response standards. Data owners maintain document freshness. Platform engineers operate the gateway and observability systems. Security owners approve tool permissions.
Assigning all responsibility to the person writing prompts will not produce a stable system over the long term.
8. Pre-Launch Checklist
- Every use case has an input/output contract, fallback behavior, and a human handoff path.
- Retrieval applies permission checks first, and answers are traceable to document IDs.
- Prompts, model routing, and retrieval parameters are versioned and have passed regression evaluation.
- Secrets are kept off clients, and tool calls use allowlists and confirmation steps.
- Alerts cover timeouts, rate limiting, circuit breakers, and queue backlogs.
- Costs can be attributed by tenant, and abnormal consumption can trigger automatic blocking.
- Logs support auditing and have been redacted appropriately.
- High-risk write operations produce drafts only and are not executed automatically.
The value of generative AI comes from engineering constraints around uncertain outputs. Well-defined task boundaries, knowledge permissions, regression evaluation, and operational observability turn model capabilities into deliverable business systems. Without these foundations, even a compelling demo is unlikely to remain reliable in production.
