From Foundation Models to Production Systems: Engineering Practices for Generative AI
Generative AI has shifted software development from training task-specific models to designing context, prompts, tools, and feedback loops around general-purpose models. This article explains the core model, orchestration, and application layers, then examines enterprise challenges such as hallucinations, data privacy, performance, cost, security, and observability. It also presents practical guidance for prompt engineering, RAG pipelines, agent workflows, evaluation, and long-term governance.
1. A Technology Turning Point and the Shift in Development Paradigms
At the end of 2022, the public release of a large language model product marked the transition of generative AI from the laboratory to large-scale practical use. Before this shift, natural language processing relied mainly on specialized small models and rule-based templates. Their capabilities were often limited to narrowly defined tasks.
Large language models, powered by large-scale pretraining and instruction tuning, demonstrated strong capabilities in language understanding, generation, reasoning, and code completion. They made the idea of “conversation as an interface” possible.
For developers, this was more than a tool upgrade. It represented a fundamental change in mindset: from “training a model for every task” to “designing context and instructions for a general-purpose model.”
From an engineering perspective, developers no longer need to repeatedly build task-specific solutions or train dedicated models. Instead, they must determine how to embed general-purpose model capabilities into business logic, constrain model behavior with prompts and external tools, and design feedback loops and evaluation mechanisms.
Generative AI shifts software development from a function-driven approach to a capability-driven approach. At the same time, it introduces new complexity. Model outputs are probabilistic, costs can be difficult to control, and security boundaries may be unclear. Engineering systems must adapt accordingly.
2. Core Capabilities and Abstraction Layers
Large language model applications can be understood through three layers:
Model layer: Foundation models provide capabilities such as semantic understanding, text generation, logical reasoning, and code completion. These capabilities depend on training data, parameter scale, alignment methods, and context length. Developers typically access models through standardized interfaces without needing to understand their internal implementation.
Orchestration layer: This is where developers apply most of their creativity. Prompt templates, few-shot examples, tool calling, multi-step reasoning, and structured output constraints can package general-purpose model capabilities into specific business functions. The quality of this layer directly affects application stability and business fit.
Application layer: This layer combines external data, business logic, user interaction, and backend systems to form a complete product. It must handle common engineering concerns such as permissions, caching, queues, storage, and monitoring while working closely with the model orchestration layer.
The following pseudocode illustrates a basic interaction pattern:
# Pseudocode: generic model invocation and prompt orchestrationdef chat_with_model(user_input, context):messages = [{"role": "system", "content": "You are an enterprise knowledge base assistant. Answer only based on the provided materials."},{"role": "user", "content": f"Materials: {context}\nQuestion: {user_input}"}]response = model.chat(messages=messages,temperature=0.2, # Reduce randomnessmax_tokens=1024,stop=["\nUser:"] # Prevent turn-boundary violations)return response
This example does not depend on any specific vendor interface. It demonstrates a general orchestration approach. In production, model calls should be wrapped in a unified service so that different models or model versions can be switched more easily.
3. Key Technical Challenges in Enterprise Adoption
3.1 Hallucinations and Controllability
Large language models may generate content that appears reasonable but is factually incorrect. This is unacceptable in many enterprise scenarios. Engineering teams generally need a combination of controls.
- Retrieval-augmented generation (RAG): Authoritative knowledge is split into chunks, converted into vectors, and indexed. Before generating an answer, the system retrieves relevant passages and injects them as context, while instructing the model to answer only from those passages.
- Confidence constraints: Prompts should clearly instruct the model to respond that it cannot determine the answer when the provided materials do not contain sufficient information. A lower temperature can also reduce randomness.
- Automated evaluation: Build evaluation sets covering core business scenarios and score outputs for accuracy, completeness, and safety. Model updates should pass automated evaluation before release.
3.2 Data Security and Privacy
Enterprise data often contains sensitive information. Sending it directly to a remote model can create compliance and security risks. Common measures include:
- Private deployment: Deploy the model within the organization’s own computing environment so that data remains within the organization’s security boundary.
- Data masking: Replace sensitive fields such as names, phone numbers, and addresses before sending requests, then restore them afterward when appropriate.
- Network isolation: Use virtual private networks, access-control policies, and encrypted transmission to secure the communication path.
- Audit logging: Record every model invocation, including inputs and outputs, for accountability and compliance audits.
When cloud services are used, general cloud capabilities such as object storage, logging, monitoring, and alerting can help create a complete data management loop and reduce fragmented manual operations.
3.3 Performance and Cost
Inference latency and token consumption directly affect user experience and operating costs. Common optimization techniques include:
- Caching: Use semantic caching for repeated or similar questions and return previous results when appropriate.
- Model routing: Select models based on task complexity. Lightweight models can handle simple classification and extraction, while larger models can be reserved for complex reasoning.
- Streaming output: Reduce perceived latency by returning the first tokens quickly.
- Asynchronous processing and batching: Put non-real-time tasks into a message queue, process them in batches, and return results asynchronously to reduce peak pressure.
Monitoring should cover metrics such as time to first token, total response time, requests per second, token consumption, error rate, and cache hit rate. These metrics must be quantified before the system can be optimized continuously.
4. Engineering Practices
4.1 Standardizing Prompt Engineering
Prompts should be treated as code assets and managed through version control. A high-quality prompt template commonly includes:
- Role definition: Specify the role the model should play, such as a senior code review expert.
- Task description: Clearly explain the task and define the input format.
- Output constraints: Specify the output structure, such as JSON, Markdown, or a list, as well as the required length and style.
- Few-shot examples: Provide two or three input-output pairs to clarify expected boundaries.
- Positive and negative examples: Show both desired behavior and behavior that should be avoided.
Teams should establish a prompt template library and maintain multiple candidate versions for the same task. Offline evaluation can then be used to select the best version. After deployment, user feedback should be continuously recorded and used for further iteration.
4.2 RAG and Knowledge Base Management
Private enterprise knowledge may be distributed across documents, support tickets, databases, and web pages. Building a RAG pipeline generally involves the following steps:
- Document parsing and cleaning: Convert PDF, Word, HTML, and other formats into plain text while removing formatting noise.
- Chunking: Split content by semantic paragraphs or fixed lengths, while retaining overlapping context to prevent information from being fragmented.
- Embedding: Use a text embedding model to convert each chunk into a semantic vector.
- Retrieval and reranking: Retrieve candidate passages using vector similarity, then use a reranking model to improve their order and relevance.
- Context assembly: Insert the most relevant passages into the prompt in an appropriate order while controlling the total context length.
Knowledge bases must be updated regularly to remain current. Frequently asked questions can also be maintained as curated question-and-answer pairs to reduce retrieval errors.
4.3 Workflow and Agent Orchestration
Complex tasks often require multiple steps, such as analyzing a customer ticket, checking historical records, calling an internal API, and generating a recommended resolution.
A “plan-execute-reflect” workflow can be designed as follows:
User request→ Task planner (decompose the task)→ Tool calls/data queries (possibly multiple times)→ Result aggregation and validation→ Self-correction (retry calls when inconsistencies are found)→ Final response
This pattern is suitable for automated operations, customer support tickets, and business process automation. However, the number of iterations must be strictly limited. Timeouts and failure fallbacks should be configured to prevent infinite loops. Every tool call should also be logged for traceability and auditing.
4.4 Observability and Evaluation
Production AI applications require full-stack observability. In addition to standard system metrics, teams should record:
- Model version and prompt version;
- Input context length and token consumption;
- Generated content;
- User feedback, such as likes, dislikes, and corrections;
- Custom evaluation scores.
Automated evaluation sets should cover accuracy, safety, robustness, and adversarial behavior. A shadow deployment approach can be used when releasing a new version: run the new and old versions in parallel for a period of time, compare their outputs, and switch traffic only after stability has been confirmed. This can significantly reduce the business risks associated with model upgrades.
4.5 Security, Compliance, and Content Governance
Large model applications are vulnerable to prompt injection attacks, in which malicious users attempt to make the model ignore its instructions or perform unauthorized actions. Defensive measures include:
- Input detection: Identify sensitive information and match common prompt injection patterns in user input.
- Output filtering: Scan generated content for prohibited terms and personally identifiable information.
- Least privilege: Ensure that tools and APIs available to the model follow the principle of least privilege and cannot perform unauthorized operations.
- Human fallback: Retain human review for high-risk decisions.
From a compliance perspective, organizations must define data usage boundaries, clarify responsibility for model outputs, and establish content governance procedures. Public-facing generative AI services require especially strong content review and complaint-handling processes.
5. Future Trends
Generative AI is evolving from single-turn conversations toward multimodal and multi-agent collaboration. Multimodal models can process text, images, audio, and video together, significantly expanding potential application scenarios. Multi-agent systems can assign different roles—such as planner, executor, and reviewer—to collaborate on complex tasks.
Small models running at the edge and larger cloud-based models can complement each other, particularly in privacy-sensitive and latency-sensitive scenarios.
At the same time, model evaluation and governance systems will become more mature. Enterprises need model lifecycle management covering model selection, testing, deployment, monitoring, and retirement. Automated evaluation, red-team testing, and continuous learning will increasingly become part of the basic infrastructure.
6. Conclusion
Generative AI will not solve every problem automatically, but it is reshaping the underlying logic of application development. Developers must return to engineering fundamentals, focusing on reliability, security, maintainability, and continuous iteration.
For enterprises, the key to turning the benefits of generative AI into business value lies in selecting an appropriate technology stack, building complete data and security infrastructure, and developing internal capabilities. Baidu AI Cloud provides foundation model and cloud capabilities that can help enterprises establish supporting systems for model services, data governance, and security controls more quickly. However, this does not eliminate the need for sound engineering. Real competitive advantage still comes from deep understanding of business scenarios and disciplined implementation.
