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:

    1. import pandas as pd
    2. df_sample = pd.read_csv("articles.csv", nrows=50)
    3. print(df_sample.info())
    4. 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:

    1. python -m venv .venv
    2. pip 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:

    1. import argparse
    2. import json
    3. import sys
    4. from collections import Counter
    5. from pathlib import Path
    6. import jieba
    7. import pandas as pd
    8. import plotly.express as px
    9. REQUIRED_COLUMNS = ["id", "title", "abstract", "year", "category"]
    10. STOPWORDS = {"的", "了", "和", "与", "在", "是", "我们", "本文", "可以", "一个", "进行", "通过"}
    11. def load_articles(path: Path) -> tuple[pd.DataFrame, int]:
    12. """Read and clean the CSV, returning valid data and the number of dropped rows."""
    13. if not path.exists():
    14. raise FileNotFoundError(f"Input file not found: {path}")
    15. df = None
    16. last_error = None
    17. for encoding in ("utf-8-sig", "gbk"):
    18. try:
    19. df = pd.read_csv(path, encoding=encoding)
    20. break
    21. except UnicodeDecodeError as exc:
    22. last_error = exc
    23. if df is None:
    24. raise ValueError(f"Unable to detect file encoding: {last_error}")
    25. missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]
    26. if missing:
    27. raise ValueError(f"Missing required columns: {missing}")
    28. total = len(df)
    29. df["year"] = pd.to_numeric(df["year"], errors="coerce")
    30. df["abstract"] = df["abstract"].fillna("")
    31. df["category"] = df["category"].fillna("Uncategorized")
    32. df = df.dropna(subset=["title", "year"])
    33. return df, total - len(df)
    34. def top_terms(df: pd.DataFrame, top_n: int = 20) -> list[tuple[str, int]]:
    35. """Tokenize titles and abstracts and count high-frequency terms."""
    36. counter = Counter()
    37. for text in (df["title"].astype(str) + " " + df["abstract"]).tolist():
    38. for token in jieba.lcut(text):
    39. token = token.strip().lower()
    40. if len(token) >= 2 and token not in STOPWORDS:
    41. counter[token] += 1
    42. return counter.most_common(top_n)
    43. def main() -> int:
    44. parser = argparse.ArgumentParser(description="Paper metadata statistics and visualization")
    45. parser.add_argument("--input", type=Path, default=Path("articles.csv"))
    46. parser.add_argument("--output", type=Path, default=Path("output"))
    47. args = parser.parse_args()
    48. try:
    49. df, dropped = load_articles(args.input)
    50. except (FileNotFoundError, ValueError) as exc:
    51. print(f"[ERROR] {exc}", file=sys.stderr)
    52. return 1
    53. args.output.mkdir(parents=True, exist_ok=True)
    54. category_counts = df["category"].value_counts().reset_index()
    55. category_counts.columns = ["category", "count"]
    56. summary = {
    57. "rows_loaded": len(df),
    58. "rows_dropped": dropped,
    59. "category_counts": category_counts.to_dict(orient="records"),
    60. "top_terms": [{"term": t, "count": c} for t, c in top_terms(df)],
    61. }
    62. (args.output / "summary.json").write_text(
    63. json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8"
    64. )
    65. fig = px.bar(category_counts, x="category", y="count", title="Paper Type Distribution")
    66. fig.write_html(args.output / "category.html", include_plotlyjs="cdn")
    67. print(f"Done: {len(df)} valid rows, {dropped} dropped, output directory {args.output}")
    68. return 0
    69. if __name__ == "__main__":
    70. 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:

    1. from fastapi import FastAPI, HTTPException, Query
    2. from analyze_articles import load_articles
    3. from pathlib import Path
    4. app = FastAPI()
    5. df, _ = load_articles(Path("articles.csv"))
    6. @app.get("/api/articles")
    7. def list_articles(
    8. q: str | None = Query(None, max_length=100),
    9. year: int | None = Query(None, ge=1990, le=2100),
    10. category: str | None = Query(None, max_length=50),
    11. page: int = Query(1, ge=1),
    12. page_size: int = Query(20, ge=1, le=100),
    13. ):
    14. result = df
    15. if q:
    16. mask = result["title"].str.contains(q, case=False, na=False, regex=False)
    17. mask |= result["abstract"].str.contains(q, case=False, na=False, regex=False)
    18. result = result[mask]
    19. if year is not None:
    20. result = result[result["year"] == year]
    21. if category:
    22. result = result[result["category"] == category]
    23. start = (page - 1) * page_size
    24. items = result.iloc[start:start + page_size][["id", "title", "year", "category"]]
    25. return {
    26. "total": len(result),
    27. "page": page,
    28. "page_size": page_size,
    29. "items": items.to_dict(orient="records"),
    30. }
    31. @app.get("/api/articles/{article_id}")
    32. def get_article(article_id: str):
    33. row = df[df["id"].astype(str) == article_id]
    34. if row.empty:
    35. raise HTTPException(status_code=404, detail="Article not found")
    36. return row.iloc[0].to_dict()

    Run and test:

    1. pip install "fastapi==0.115.*" "uvicorn==0.30.*"
    2. uvicorn app:app --reload
    3. curl "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:

    1. {
    2. "total": 132,
    3. "page": 1,
    4. "page_size": 20,
    5. "items": [
    6. {"id": "a0231", "title": "Example Title", "year": 2024, "category": "Review"}
    7. ]
    8. }

    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:

    1. Package the backend as a container image, use a fixed-version base image tag, and install dependencies from a lock file.
    2. Pass configuration such as data paths and ports through environment variables; do not write secrets into code or images.
    3. 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.
    4. Keep the previous image tag during release and switch back if anomalies occur.
    5. 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.