From Code Generation to Task Delivery: A Reproducible Practice Guide
Code LLMs can generate scripts, APIs, and pages from natural-language requirements, but runnable code is not the same as a delivered task. Using a CSV of roughly 6,000 paper metadata records, this article shows how to turn model output into reproducible deliverables: define inputs and outputs for each subtask, probe the data, build an analysis and Plotly visualization script, add a FastAPI search API, define frontend state, and prepare deployment and risk checks. The focus is on acceptance criteria that readers can run and verify on their own data, not on model training or benchmark comparisons.
1. Problem and Scope
Code LLMs can already generate scripts, interfaces, and pages from natural-language requirements. But generated code that runs does not mean the task has been delivered. Delivery requires three conditions: input data and requirements are clearly defined, artifacts can be independently verified, and there is a clear fallback path when something fails. This article uses a typical scenario to show how to turn model output into reproducible deliverables.
The scenario is a CSV containing roughly 6,000 paper metadata records. The task is to produce category statistics and keyword analysis, generate a visualization page, and provide a web page that supports search and filtering. This article does not discuss model training, nor does it compare leaderboard results across models. The acceptance criteria below need to be confirmed by running them on your own data; no measured performance numbers are provided here.
2. Task Decomposition and Data Profiling
After splitting the requirement into subtasks, each subtask needs to specify its input, output, and failure handling. The table below shows the decomposition for this scenario:
| Subtask | Input | Output | Failure handling |
|---|---|---|---|
| Data profiling | articles.csv | Field list and sample rows | Stop execution and ask for field descriptions |
| Statistical analysis | Cleaned data | summary.json | Record dropped rows; do not skip silently |
| Visualization | Statistics in summary.json | category.html | Keep summary.json; the page can be regenerated later |
| Search API | Cleaned data | REST API | Return a clear error when the API fails to start |
The assumed data fields are: id (string, unique), title, abstract (possibly empty), year (integer year), category (paper type), keywords (comma-separated), and publish_date.
Before writing the formal script, use a sample read to confirm the structure:
import pandas as pddf_sample = pd.read_csv("articles.csv", nrows=50)print(df_sample.info())print(df_sample.head(3).to_string())
info() outputs the number of fields, the non-null count for each column, and data types. If the year column appears as object type, it usually means non-numeric content is mixed in, which needs to be handled during cleaning. Fifty rows can only reveal structural issues; rare values and encoding problems need to be checked on the full file.
Acceptance criteria:
- All required fields appear in the output.
- The year column can be converted to numeric.
- The content of the three sample rows matches the field meanings without misalignment.
3. Analysis Script and Visualization
Runtime environment: Python 3.10 or later. The dependency versions below are for reference only; verify them in your own environment:
python -m venv .venvpip install "pandas==2.2.*" "jieba==0.42.1" "plotly==5.22.*"
The first run of jieba generates a dictionary cache, so it takes slightly longer; subsequent runs are much faster.
The complete code for analyze_articles.py is as follows:
import argparseimport jsonimport sysfrom collections import Counterfrom pathlib import Pathimport jiebaimport pandas as pdimport plotly.express as pxREQUIRED_COLUMNS = ["id", "title", "abstract", "year", "category"]STOPWORDS = {"的", "了", "和", "与", "在", "是", "我们", "本文", "可以", "一个", "进行", "通过"}def load_articles(path: Path) -> tuple[pd.DataFrame, int]:"""Read and clean the CSV, returning valid data and the number of dropped rows."""if not path.exists():raise FileNotFoundError(f"Input file not found: {path}")df = Nonelast_error = Nonefor encoding in ("utf-8-sig", "gbk"):try:df = pd.read_csv(path, encoding=encoding)breakexcept UnicodeDecodeError as exc:last_error = excif df is None:raise ValueError(f"Unable to detect file encoding: {last_error}")missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]if missing:raise ValueError(f"Missing required columns: {missing}")total = len(df)df["year"] = pd.to_numeric(df["year"], errors="coerce")df["abstract"] = df["abstract"].fillna("")df["category"] = df["category"].fillna("Uncategorized")df = df.dropna(subset=["title", "year"])return df, total - len(df)def top_terms(df: pd.DataFrame, top_n: int = 20) -> list[tuple[str, int]]:"""Tokenize titles and abstracts and count high-frequency terms."""counter = Counter()for text in (df["title"].astype(str) + " " + df["abstract"]).tolist():for token in jieba.lcut(text):token = token.strip().lower()if len(token) >= 2 and token not in STOPWORDS:counter[token] += 1return counter.most_common(top_n)def main() -> int:parser = argparse.ArgumentParser(description="Paper metadata statistics and visualization")parser.add_argument("--input", type=Path, default=Path("articles.csv"))parser.add_argument("--output", type=Path, default=Path("output"))args = parser.parse_args()try:df, dropped = load_articles(args.input)except (FileNotFoundError, ValueError) as exc:print(f"[ERROR] {exc}", file=sys.stderr)return 1args.output.mkdir(parents=True, exist_ok=True)category_counts = df["category"].value_counts().reset_index()category_counts.columns = ["category", "count"]summary = {"rows_loaded": len(df),"rows_dropped": dropped,"category_counts": category_counts.to_dict(orient="records"),"top_terms": [{"term": t, "count": c} for t, c in top_terms(df)],}(args.output / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")fig = px.bar(category_counts, x="category", y="count", title="Paper Type Distribution")fig.write_html(args.output / "category.html", include_plotlyjs="cdn")print(f"Done: {len(df)} valid rows, {dropped} dropped, output directory {args.output}")return 0if __name__ == "__main__":sys.exit(main())
The exception handling in this code falls into three categories. A missing file, an unrecognized encoding, or missing fields all return a clear error message and a nonzero exit code instead of throwing a raw stack trace. Missing abstracts are replaced with empty strings, and missing categories are grouped as “Uncategorized”. Rows with invalid titles or years are dropped, and the row count is written to summary.json for reconciliation.
Visualization uses Plotly to generate a bar chart. The chart includes hover tooltips and zooming; moving the mouse over a bar shows the specific value. The HTML loads plotly.js through a CDN by default. In an offline environment, change include_plotlyjs="cdn" to include_plotlyjs=True; the file becomes larger but no longer depends on the network.
Acceptance criteria:
- When the script runs normally, the exit code is 0 and the terminal shows the valid row count and dropped row count.
- In summary.json, the sum of count in category_counts equals rows_loaded.
- After deleting one required field and running again, the terminal shows “Missing required columns” and the exit code is 1.
- If the dropped-row ratio exceeds a threshold you set (for example, 5%), inspect the raw data manually.
- Open category.html in a browser and confirm that hovering over a bar shows the value.
4. Full-Stack Skeleton: Search API and Frontend State
Statistics can only answer “what does the whole look like.” Readers also need to find specific papers by keyword and conditions, so a search API is needed. This article uses FastAPI to provide three endpoints:
GET /api/articles: filter by keyword, year, and category, with pagination.GET /api/articles/{id}: return details for a single paper.GET /api/facets: return available year and category lists for frontend filters.
The API code below reuses load_articles from the analysis script to avoid duplicating cleaning logic and to prevent NaN values from entering JSON responses:
from fastapi import FastAPI, HTTPException, Queryfrom analyze_articles import load_articlesfrom pathlib import Pathapp = FastAPI()df, _ = load_articles(Path("articles.csv"))@app.get("/api/articles")def list_articles(q: str | None = Query(None, max_length=100),year: int | None = Query(None, ge=1990, le=2100),category: str | None = Query(None, max_length=50),page: int = Query(1, ge=1),page_size: int = Query(20, ge=1, le=100),):result = dfif q:mask = result["title"].str.contains(q, case=False, na=False, regex=False)mask |= result["abstract"].str.contains(q, case=False, na=False, regex=False)result = result[mask]if year is not None:result = result[result["year"] == year]if category:result = result[result["category"] == category]start = (page - 1) * page_sizeitems = result.iloc[start:start + page_size][["id", "title", "year", "category"]]return {"total": len(result),"page": page,"page_size": page_size,"items": items.to_dict(orient="records"),}@app.get("/api/articles/{article_id}")def get_article(article_id: str):row = df[df["id"].astype(str) == article_id]if row.empty:raise HTTPException(status_code=404, detail="Article not found")return row.iloc[0].to_dict()
Run and test:
pip install "fastapi==0.115.*" "uvicorn==0.30.*"uvicorn app:app --reloadcurl "http://127.0.0.1:8000/api/articles?q=大模型&year=2024&page=1"
A successful list request returns a structure like the following; the values are illustrative only:
{"total": 132,"page": 1,"page_size": 20,"items": [{"id": "a0231", "title": "Example Title", "year": 2024, "category": "Review"}]}
The frontend needs to maintain the following state:
| State | Type | Description |
|---|---|---|
| query | String | Search box content; updated only when search is clicked |
| filters | Object (year, category) | When any filter changes, page resets to 1 |
| page | Number | Starts from 1 |
| items, total | Array, number | Returned by the API |
| status | idle, loading, ok, error | Controls loading hints, empty state, and error messages |
| selectedId | String or null | When non-null, opens the detail modal |
Acceptance criteria:
- When page_size is 0 or greater than 100, the API returns 422.
- Requesting a nonexistent id returns 404.
- When search results are empty, the page shows an empty state rather than a blank area.
- When the API returns 500, the page shows an error message and a retry button.
- After closing the detail modal, the search term and filters remain unchanged.
- Under the same conditions, the total shown on the page matches the total returned by the API.
5. Deployment and Risk Checklist
After local verification passes, consider going live. The deployment steps are:
- Package the backend as a container image, use a fixed-version base image tag, and install dependencies from a lock file.
- Pass configuration such as data paths and ports through environment variables; do not write secrets into code or images.
- Upload static pages and frontend assets to object storage and configure a CDN. Set longer cache times for hashed assets and shorter cache times for HTML files to make updates easier.
- Keep the previous image tag during release and switch back if anomalies occur.
- Run the script’s acceptance checks in the CI pipeline; do not release if checks fail.
You can choose any mainstream cloud provider’s container platform and object storage services; this article does not recommend a specific vendor. Before going live, confirm the following risks item by item:
- Cost: Set limits on container replica counts and alerts for CDN traffic.
- Permissions: Grant object storage write permissions only to the release account; the runtime service keeps read-only permissions.
- Data security: Abstracts may contain unpublished or copyrighted text; confirm the scope that can be made public before launch.
- Code review: Manually review model-generated code for dependency versions, file path concatenation, and query statements. If data is migrated to a database, queries must use parameterized statements to prevent injection.
- Result reconciliation: Reconcile statistics against the original CSV; checking only whether the page opens is not enough.
- Licensing: The team needs to confirm the source and license terms of generated code.
- Rollback criteria: Define rollback standards in advance, for example, switching back to the previous version when the API error rate exceeds a certain threshold.
Code LLMs can handle a large amount of writing work, but whether delivery holds depends on whether acceptance criteria are clearly written and whether each step can be independently run and checked. Apply these two points to every subtask, and readers can judge whether model output is ready to use directly.
