Build a Text Generation App in One Hour: A Practical Guide
This article explains how developers can build a working text generation application in about an hour by focusing on the application layer rather than model internals. It covers environment setup, the non-deterministic and context-limited nature of text generation, prompt structuring, a document Q&A and summarization case study, quality evaluation, cost and safety controls, and common pitfalls to avoid. Readers will find a short, repeatable path from a first API call to a demo-ready, testable, and iterable application.
一、Why “One Hour” Is a Reasonable Learning Goal
Many developers misunderstand what it takes to get started with text generation. They assume they must first master model internals, distributed training, and operator optimization before writing any code. In reality, the core challenge of application-layer development is not inside the model. It is how to package an uncertain generation capability into a deterministic, controllable, and testable business feature.
The one-hour goal is therefore not to learn everything. It is to complete the shortest end-to-end loop: environment ready → a single successful call → structured output → knowledge integration → evaluation and release.
This loop is achievable in a short time because the engineering elements of a text generation application are highly focused. They fall into four categories: the model access layer, the prompt and context layer, the business orchestration layer, and the quality assurance layer. Working through these layers in order helps avoid the common trap where something works once and can never be reproduced.
二、Environment Setup: Keep Uncertainty Out of Development
The most common environment problem is “it runs on my machine but not on my colleague’s.” It helps to manage the environment in three parts.
The first part is runtime isolation. Use a container platform or a virtual environment to pin dependency versions and avoid global pollution. An illustrative configuration looks like this:
# Illustrative only: shows structure, not any specific productservices:app:image: your-runtime:latestenvironment:- MODEL_ENDPOINT=${MODEL_ENDPOINT}- MODEL_API_KEY=${MODEL_API_KEY}ports:- "8080:8080"
The second part is separating configuration from secrets. Inject all access credentials through environment variables or a secret management capability. Never hardcode them into the repository. Also enable masking in your logging service so that prompts and user inputs are not written to disk in full.
The third part is observability from day one. Connect logging, metrics, and monitoring alerts on the first day, covering at least call latency, failure rate, token consumption, and timeout counts. Many teams leave monitoring to the end and then cannot tell whether a production issue comes from the prompt or from network jitter.
三、How Text Generation Works: Capability Boundaries and Key Mechanisms
At its core, text generation is conditional probability continuation based on context. This leads to three engineering characteristics.
First, it is non-deterministic. The same input can produce different outputs. You cannot verify it with the “assert equality” style of traditional unit tests. You need “constraint validation plus sampling-based evaluation.”
Second, context is limited. The model can only see what is placed in the context. When “the model doesn’t know,” it is often not a capability problem but a delivery problem: the information never reached the model. In engineering terms, use retrieval augmentation to chunk external knowledge and inject it.
Third, it is instruction-sensitive. Small changes to a prompt can cause noticeable swings in output. Prompts therefore need version control, with review and rollback just like code.
A reusable prompt structure is shown below:
[Role] You are a writing assistant for a specific business domain[Task] Generate a structured summary based on the provided material[Constraint] Use only information from the material; output "insufficient material" when uncertain[Output] JSON: {"summary": string, "points": string[], "confidence": number}
Ordering the prompt as “constraints first, examples second, length last” significantly reduces off-topic responses and hallucinations. If you need stable structured results, add a second validation step in the application layer: if parsing fails, retry once and append a prompt that says “strictly output valid JSON.”
四、Project Case: Delivering a Text Generation App from Scratch
The case goal is to build a “document Q&A plus summary generation” service that supports uploading documents, asking questions, and returning answers with sources.
Step one is data ingestion. Parse the documents, chunk them semantically, and write them into a vector retrieval capability (you can build one on a container platform or use a general-purpose retrieval service). Record source identifiers so answers can be traced back.
Step two is orchestration. When a request arrives, first classify the intent. Chit-chat goes directly to generation. Knowledge questions are retrieved first and then generated. High-risk requests go through stricter constraints. Pseudocode:
def handle(req):intent = classify(req.text)if intent == "knowledge":ctx = retrieve(req.text, top_k=5)if not ctx:return {"answer": "insufficient material"}return generate(build_prompt(req.text, ctx))return generate(build_prompt(req.text, []))
Step three is quality assurance. Build a small evaluation set (30 to 50 items is a reasonable starting point) and score it on four dimensions: accuracy, completeness, format compliance, and citation correctness. Run a regression pass every time you change a prompt or a model parameter to avoid fixing one issue and breaking three others.
Step four is cost and safety. Set limits on input and output length, apply concurrency throttling, and use timeout retries. Intercept sensitive terms and unauthorized access up front. Cache frequent Q&A results to reduce repeated consumption.
五、Common Pitfalls and an Advanced Path
The first pitfall is over-pursuing long prompts. The longer a prompt, the more likely its parts conflict. Keep stable constraints at the system level and put changing information at the user level.
The second pitfall is ignoring failure paths. Generation failures, empty retrieval results, and parsing exceptions all need fallback messages and degradation strategies.
The third pitfall is having no concept of versioning. Prompts, chunking strategies, and retrieval parameters should all be under version control so you can attribute causes.
For the advanced path, proceed in three steps: first improve the evaluation system, then introduce multi-turn dialogue and tool calls, and finally consider tiered routing between small and large models to balance quality and cost. If you use general capabilities such as object storage, message queues, logging, and monitoring alerts from Baidu AI Cloud to handle documents, asynchronous tasks, and operational observability, the application architecture becomes clearer and easier to extend.
With these methods, one hour is enough to complete a first text generation application that can be demonstrated, evaluated, and iterated on, laying a solid engineering foundation for more complex scenarios later.
