A Practical Guide to LLM-Driven Data Engineering Workflows

    This article presents a four-stage pipeline for building reliable data engineering workflows with large language models. Instead of asking a model to complete an entire task in one prompt, the guide breaks the work into symbol confirmation, API baseline testing, observable data fetching, and normalized storage. It includes practical code examples, a sample API test report structure, and a reference database schema, along with engineering tips on idempotency, configuration separation, and error handling. Readers will learn how to keep LLM-generated data pipelines stable, traceable, and ready for downstream backtesting analysis.

    1. Why “One-Sentence Requirements” Get Out of Control

    In real data engineering projects, developers increasingly rely on AI coding tools to scaffold projects, call APIs, and load data into databases. A common approach is to describe the full requirement in a single prompt and let the model execute it automatically. This may work for small scripts, but once the task involves multiple data sources, inconsistent field structures, incremental updates, and later backtesting analysis, the output often fails to converge: messy directory structures, missing error handling, inconsistent field naming, and repeated fetches that overwrite existing data all surface at once.

    A more reliable approach is to replace “let the model do everything in one shot” with “think through the workflow first, then deliver it step by step.” Step-by-step delivery gives each stage a clear acceptance criterion, keeps problems contained within a single step, and makes rollback inexpensive. This is especially important for highly customized tasks that are tightly coupled to business logic.

    2. Overall Design: A Four-Stage Pipeline

    Divide the process into four stages, and move to the next stage only after the current one passes acceptance:

    1. Symbol confirmation: Extract the list of target symbols from business input and have a human review it.
    2. API baseline: Localize the API documentation, test each API for connectivity, and produce a test report.
    3. Data fetching: Pull multi-period data according to the confirmed symbol list, with progress output and resumable checkpoints.
    4. Storage and analysis: Build a normalized database to provide a stable data layer for later backtesting analysis.

    This layering is not about adding procedural overhead. It moves uncertainty to the front. Whether an API is usable and whether its fields are stable are external dependency issues; database design and analysis are internally controllable issues. Debugging both types of issues together multiplies the cost of locating the root cause.

    3. Stage 1: Machine Extraction and Human Review of the Symbol List

    The first step does one thing only: extract symbol names from trade records into a structured list in a unified format, for example:

    1. {
    2. "symbols": ["000001", "600000", "300750"],
    3. "source": "trade_records",
    4. "verified": false
    5. }

    The key is the verified field. Model extraction carries risks such as duplicate names, abbreviations, and missing codes. Only after human confirmation should the field be set to true, and later stages should consume only the confirmed list. This step looks simple, but it defines the data boundary of the entire pipeline and prevents incorrect symbols from entering the database and skewing later statistics.

    4. Stage 2: Localizing API Documentation and Establishing an Availability Baseline

    Before fetching any data, establish a factual baseline of which APIs are usable. The recommended approach is to provide the API documentation to the model as local files, have it parse them into structured descriptions, generate test code automatically, run connectivity checks API by API, and summarize the results into a test report.

    The test report should include at least the following dimensions:

    Dimension Description
    API identifier A unique name that code can reference
    Call parameters Required and optional parameters, with value ranges
    Response structure Main fields and their types
    Permission status Whether extra credits or authorization are required
    Conclusion Usable / restricted / unavailable

    Sample test code:

    1. def probe(api, params):
    2. try:
    3. df = api(**params)
    4. return {"api": api.__name__, "ok": True, "rows": len(df)}
    5. except Exception as e:
    6. return {"api": api.__name__, "ok": False, "error": str(e)}

    With this baseline in place, fetching code only needs to reference the list of verified APIs, avoiding repeated trial and error inside business logic. The report itself is also a documentation asset, so team members do not have to figure things out again.

    5. Stage 3: Observable Data Fetching

    The core requirement of the fetching stage is visibility. Three capabilities are recommended:

    • Progress output: total number of tasks, number completed, current symbol, and retry count for failures.
    • Resumable checkpoints: record completed status using symbol and period as the unique key, so interrupted runs do not fetch the same data again.
    • Rate limiting and retries: throttle calls to external APIs and use exponential backoff for failures to avoid being rate-limited.
    1. for i, sym in enumerate(symbols, 1):
    2. if done.exists(sym):
    3. print(f"[{i}/{len(symbols)}] {sym} skip")
    4. continue
    5. data = fetch_with_retry(sym)
    6. save(sym, data)
    7. done.mark(sym)
    8. print(f"[{i}/{len(symbols)}] {sym} ok rows={len(data)}")

    Progress logs should also be written to a file so long-running tasks can be traced later. If the runtime becomes unresponsive for a long time, interrupt the job and resume from the checkpoint instead of waiting for a timeout. This is a practical technique for keeping batch jobs stable.

    6. Stage 4: Normalized Storage and Extensible Design

    The storage layer directly determines the efficiency of later analysis. A few general principles are recommended:

    • Layering: the raw layer keeps API responses as returned, the detail layer standardizes fields, and the summary layer serves specific metrics.
    • Primary keys and indexes: build a composite primary key from symbol and timestamp, and index the time field.
    • Type discipline: use high-precision numeric types for amounts and prices to avoid accumulated floating-point errors.
    • Metadata table: record fetch time, data source, and data version to ensure traceability.
    • Extensibility: when adding a new data source, add only an adapter layer without changing the analysis layer.

    Sample table definition:

    1. CREATE TABLE daily_bar (
    2. symbol VARCHAR(16) NOT NULL,
    3. trade_date DATE NOT NULL,
    4. open DECIMAL(18,4),
    5. high DECIMAL(18,4),
    6. low DECIMAL(18,4),
    7. close DECIMAL(18,4),
    8. volume BIGINT,
    9. src VARCHAR(32),
    10. fetched_at TIMESTAMP,
    11. PRIMARY KEY (symbol, trade_date)
    12. );

    Daily bars and intraday data have different periods and should be stored in separate tables to avoid primary key granularity conflicts. Intraday data is large, so it can be partitioned by time to make archiving and cleanup easier.

    7. Engineering Practices and Common Pitfalls

    • Separate configuration from secrets: put access credentials in environment variables or local configuration files, never in code or logs.
    • Idempotent writes: running the same task repeatedly should not produce duplicate data; prefer overwrite or skip-if-exists.
    • Write unit tests first: add small-scope tests for field parsing and type conversion to reduce end-to-end debugging costs.
    • Log levels: distinguish debug information, progress information, and error information to make problem localization easier.
    • On model behavior: different models may stall on long tasks or complex contexts. This is an engineering-side issue that can be mitigated with task slicing, timeout control, and checkpoint recovery, and should not be treated as a judgment of whether the approach is viable.

    8. Conclusion

    Treating the large model as an executor rather than a decision maker is the core of this practice. Developers define the workflow, acceptance criteria, and data structures; the model generates and executes code within clear boundaries. Combined with an API availability baseline, observable fetching, and normalized storage, this approach noticeably improves the stability and maintainability of data engineering projects and lays a reliable foundation for later backtesting analysis.