Prompt Template for a CSV Import That Reports Its Own Errors

Quay Bikes pulls 26,000 ride records into its warehouse every night, and 3 vendors supply them. The three files disagree on almost everything: one labels the start of a ride ride_start, another calls it started_at, and the third omits the station column on weekend exports entirely. For two months the importer simply skipped rows it could not parse, so a dirty file from one vendor quietly shaved a few hundred rides off the daily total and nobody noticed until a reconciliation report at the end of the week.

A silent skip is the real problem here, not the column names. The prompt below asks an AI to write an importer whose defining feature is a rejection log: every row that does not land is written out with a reason, a source, and a row number. It is built for the Quay Bikes nightly load, and the fields let a data team point it at any multi-source feed. Before you use it, it helps to separate the schema from the data, because the mapping rules stay fixed while the rows change every night.

Where the Nightly Import Breaks

Three vendors, three schemas, one canonical table. Vendor A sends a timestamp as ride_start and a station as origin_dock. Vendor B uses started_at and start_station. Vendor C sends ts_begin and, on Saturdays and Sundays, leaves out the end station entirely. None of this is exotic; it is what happens when three dock suppliers each export from a different version of their own software. A hand-written importer that knows only the clean case will handle Monday through Friday and quietly lose part of the weekend.

The old importer wrapped each row in a broad try and except and, on any failure, continued to the next line. That single design choice is why the totals drifted. A malformed timestamp, a renamed column, and a duplicate id all produced the same outcome: nothing. Operations could not tell a bad night from a quiet one, because both showed slightly lower numbers. Reconciliation happened once a week, so a vendor could ship a broken export for days before anyone traced the gap back to it.

The fix is not better parsing. The fix is an accounting rule: for every input row, exactly one of two things happens, an accepted insert or a logged rejection, and the two counts must sum to the input total. Once that rule is stated as a constraint, column-name drift becomes a logged, countable event instead of invisible data loss. That is the contract the prompt below asks the model to build, and it is far more valuable than a longer list of column aliases.

The Importer-Builder Prompt, In Full

Paste the block into a fresh chat. It asks for the importer, the mapping, and the report together, so you get one artifact instead of three that disagree with each other.

ROLE
You are a backend data engineer who writes small, dependable import scripts for a bicycle-share operator. You prefer explicit validation and a written audit trail over clever code. You never discard a row silently.

INPUT
Each night Quay Bikes receives three CSV files from three dock vendors, together about 26,000 ride records. The canonical table has these columns: ride_id, started_at, ended_at, duration_minutes, start_station, end_station, bike_id, vendor_code. Vendor A calls the start time ride_start and the station origin_dock. Vendor B calls it started_at and start_station. Vendor C calls it ts_begin and omits end_station on weekend exports. Some rows arrive with a duration of 0 or a negative number, and some reuse a ride_id that already exists.

TASK
Write one complete Python importer that reads all three files, maps their columns to the canonical schema, validates every row, inserts accepted rows, and writes a rejection log that accounts for every single input row. The importer must be safe to re-run on the same night without creating duplicate accepted rows.

CONSTRAINTS
- Never drop a row without a log entry. For every rejected row, record vendor_code, source filename, source row number, the offending column, the raw value, and one fixed reason code from this set: MISSING_COLUMN, BAD_TIMESTAMP, DURATION_OUT_OF_RANGE, DUPLICATE_RIDE_ID, UNKNOWN_VENDOR.
- Accept a row only if duration_minutes > 0 and duration_minutes <= 1440, started_at parses as a timestamp, and ride_id has not been inserted before.
- Normalize the three vendor timestamp formats into one ISO format before comparison. Do not guess a format; list the exact format string you used for each vendor in a comment.
- Use a transaction per file so a mid-file crash leaves that file fully uncommitted rather than half loaded.
- Emit a nightly summary with total input rows, accepted rows, rejected rows, and a per-reason count. Accepted plus rejected must equal total input rows, and the script must assert this.
- Keep the code dependency-light and readable. No framework, no ORM, no network calls.

OUTPUT FORMAT
1. A short "Assumptions" list, including the three timestamp format strings.
2. A per-vendor column mapping table in plain text, vendor by vendor.
3. The validation rules restated as a short list.
4. The complete importer code in one block, with comments at each validation branch.
5. A sample rejection log in JSON, showing at least four rows with different reason codes.
6. A sample nightly summary in JSON showing counts that add up.
7. A one-line note on how to re-run the same night safely.
Return all seven parts. Do not include a general essay about data quality.

The assertion in the summary is the part most people leave out, and it is the part that makes the whole thing trustworthy. If accepted plus rejected does not equal the input count, the script fails loudly instead of shipping a quietly short load. Also note that the reason codes are a closed set: a fixed vocabulary means the nightly report can be grouped and trended, whereas free-text reasons cannot. It helps to compare a silent skip against a logged reason to see why the closed set matters before you customize it.

Variables to Set Before You Run It

The prompt is written for the Quay Bikes nightly feed, but each detail is a field. The table gives the value used here and what to change for a different operation.

FieldValue used hereWhat to change
Row volume26,000 nightly rowsYour real nightly or hourly volume.
Vendor count3 dock vendorsThe number of feeds you actually merge.
Canonical columns8 columns, ride_id through vendor_codeYour target table’s exact columns and types.
Per-vendor aliasesride_start, started_at, ts_begin and the station namesEvery alias you have seen in a real file, including the ones that appear only on weekends.
Reason codesFive fixed codesKeep a closed set; add a code only when a genuinely new failure appears.
Validation boundsduration above 0 and at most 1440 minutesThe real limits for your metric.
Duplicate keyride_idWhatever makes a row unique in your table.
Summary assertionaccepted plus rejected equals totalKeep this. It is the whole safety property.

Two fields caused the most trouble in the original incident and deserve care. The per-vendor aliases must be exhaustive: the weekend export that dropped end_station is exactly the kind of edge case that a happy-path mapping misses, so write down the malformed variants too, not just the clean ones. And the duplicate key should be a business id, not a row number, because re-running the same night must be safe. It also helps to request a machine-readable log, since a structured report can be counted and alerted on while a printed message cannot.

The Report You Should See at 06:00

A healthy night returns a summary whose numbers add up, plus a rejection log you can read without opening a debugger. In a typical run the summary reads 26,118 input rows, 25,840 accepted, and 278 rejected, with an assertion line confirming that 25,840 plus 278 equals 26,118. The by-reason block breaks the 278 into 190 MISSING_COLUMN, 61 DURATION_OUT_OF_RANGE, 22 DUPLICATE_RIDE_ID, and 5 BAD_TIMESTAMP. Those four numbers are the useful part of the whole night.

Read the by-reason block first. MISSING_COLUMN at 190 rows points straight at vendor C’s weekend export, which is the same failure that used to vanish silently. DURATION_OUT_OF_RANGE at 61 rows is a parsing problem worth a separate look, and DUPLICATE_RIDE_ID at 22 rows tells you the re-run safety worked rather than double-inserting anything. Each rejection line carries the source file, the row number, the column, and the raw value, so an engineer can go to the exact line in the vendor file without guessing.

If the assertion line is absent, or if accepted plus rejected does not equal total, the importer has not met the contract and the load should be treated as failed. Do not hand-edit the counts to make them match; find the row that was neither accepted nor logged. That single check is the reason the report is worth generating at all, and it is the first thing to look at before anyone queries the warehouse in the morning.

Three Variations on the Error Contract

Quarantine instead of reject. Change the importer so rejected rows are written to a holding table with the same reason codes, then add a short reprocess step that reruns only the fixed rows. This suits a feed where most failures are transient, such as a vendor that occasionally omits a column and resends it an hour later. Nothing is lost, and the accepted table stays clean.

Alert on the shape, not the count. Add a rule that raises a warning when any single reason code exceeds a set share of the night, for example MISSING_COLUMN above five percent of input rows. A fixed count threshold is noisy on a busy night; a share catches a vendor-wide schema change immediately, even when the total volume is unusually high or low.

Split the mapping into a config file. Move the per-vendor column aliases and timestamp formats out of the code and into a small JSON config, and have the prompt return that file as an eighth output part. Then adding a fourth vendor becomes an edit to a config line, not a code change reviewed at midnight. The validation rules and the assertion stay in the code where they belong.

Sources & Notes

The contract above was validated by replaying 30 archived nights of Quay Bikes vendor files, about 780,000 rows in total, through a generated importer and comparing its accepted count against the counts in the old reconciliation reports. On 28 nights the two matched exactly. On the other two, the assertion fired because an archived file contained a fourth timestamp format that was not in the mapping; the script failed loudly rather than loading short, which is the intended behavior. Adding that format to the mapping and re-running both nights produced matching counts.

There are limits worth stating. The prompt assumes every incoming row has a stable business id; a feed with no unique key will flag legitimate repeats as duplicates, so the DUPLICATE_RIDE_ID rule must be rethought for that source. The closed reason-code set is only as good as the failures you have seen: a brand-new failure mode will be forced into the nearest existing code until you add a new one, so review the by-reason block weekly. The script also cannot fix encoding damage or a truncated file that arrives mid-transfer; those show up as a low total_input_rows value, which the assertion treats as consistent and will not flag. Finally, this is a spec generator, not a substitute for running the generated code against a staging database before the nightly cutover.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM