ChatGPT Prompt to Convert Code Between Languages

The Migration Sitting in Your Backlog

A small ecommerce team runs a legacy PHP storefront, and the tax logic lives in one 240-line class that reads a cart, applies a jurisdiction table, handles a few regional exemptions, and rounds to the nearest cent. The team is rebuilding checkout in Python and needs that calculator ported without changing behavior, because a one-cent rounding difference across thousands of orders turns into a reconciliation problem at quarter end. Nobody wants to hand-rewrite 240 lines and then guess which edge cases survived the trip.

Language models are good at this, but only when you stop treating it as a translation exercise and start treating it as a specification transfer. Below is one complete prompt for moving the PHP tax class to Python, the fields you swap for your own port, the output to expect, and the variations that fit other language pairs.

The Port Prompt

Send the block as a single message. The behavior contract is what keeps the model from quietly “improving” your logic while it converts it.

You are a senior engineer who ports production code between languages without changing behavior.

Port the PHP shopping cart tax calculator below to Python 3.11.

Source language: {{SOURCE_LANG}}
Target language: {{TARGET_LANG}}
Runtime constraints: {{CONSTRAINTS}}
Test framework for the new code: {{TEST_FRAMEWORK}}

Behavior contract that must not change:
- Inputs: a list of cart line items (sku, unit price in cents, quantity) and a shipping region code.
- Output: a breakdown object with subtotal, tax total, and per-region tax lines, all in integer cents.
- Rounding: half-up to the nearest cent, applied per line, not on the grand total.
- Exemptions: certain sku prefixes are tax-exempt in some regions.
- Error behavior: raise on unknown region codes instead of defaulting to zero.

Rules:
1. Preserve the exact rounding order and exemption logic. Do not refactor the algorithm.
2. Use type hints on every function and a dataclass for the output.
3. Keep functions small, but do not change the computation order.
4. Add no dependency beyond the Python standard library.
5. Write idiomatic Python, but flag anywhere you kept the source style for behavioral reasons.
6. Output the full module, then a table mapping each original PHP method to its Python equivalent.
7. List every behavioral assumption you had to make.
8. After the code, generate pytest cases covering each region, each exemption, and the rounding boundary.

Source code:
{{SOURCE_CODE}}

Rule one is the point of the whole exercise. Ask a model to “convert this code” and it often returns something cleaner, shorter, and subtly wrong, because it “fixes” the rounding order or merges two loops. Pinning the behavior contract makes the port auditable instead of merely reasonable.

Fields to Replace

TokenWhat to enterExample
{{SOURCE_LANG}}Origin language and versionPHP 8.1
{{TARGET_LANG}}Destination and versionPython 3.11
{{CONSTRAINTS}}Runtime or dependency limitsStandard library only, must run in AWS Lambda
{{TEST_FRAMEWORK}}How you test the targetpytest
{{SOURCE_CODE}}Paste the file as-isThe 240-line TaxCalculator class

Write the contract with numbers, not adjectives. A line such as “rounding is half-up, per line” is testable; “handle money carefully” is not, and the model will invent its own policy the moment you leave it vague.

Reading the Response

Expect a full module, a method-mapping table, an assumptions list, and a starter test file. A trimmed slice of the shape:

from dataclasses import dataclass

@dataclass
class TaxLine:
    region: str
    rate_bps: int
    taxable_cents: int
    tax_cents: int

@dataclass
class TaxBreakdown:
    subtotal_cents: int
    tax_cents: int
    lines: list[TaxLine]

def round_half_up(cents: float) -> int:
    return int(cents + 0.5) if cents >= 0 else -int(-cents + 0.5)

def calculate_tax(items, region: str) -> TaxBreakdown:
    ...

Method map:
  PHP calculateTotal   -> Python calculate_tax
  PHP applyExemptions  -> Python is_exempt
  PHP roundLine        -> Python round_half_up

Assumptions:
- The region table is passed in, not read from a database.
- Sku prefixes are matched case-insensitively, as in the source.

Check three things before you trust the port. First, that the rounding helper matches the source on negative values. Second, that the exemption check kept the same prefix-matching rules. Third, that the method map is one-to-one, because a missing row usually means the model silently dropped a branch.

When You Have a Snippet and No Spec

A separate scenario: you have one function and no written contract. Do not jump straight to a rewrite. Ask the model to extract the contract first. Send the function with the line “Before converting, write the observable behavior of this code as a numbered list of inputs and outputs.” Review that list, correct anything wrong, then convert using the list as the contract. This two-step version costs one extra message and catches the mismatches that make a silent port dangerous.

Why the Contract-First Port Works

Three choices carry the result. First, naming the exact rounding rule removes the model’s default urge to round only at the end. Second, forbidding refactors keeps the diff small, so a reviewer can line up old and new logic side by side. Third, the method-mapping table turns the port into an audit checklist, because every source method needs a destination row. Together they turn a fuzzy translation into a reviewable change you can ship behind tests.

Porting Traps

  • Silent numeric drift. Integer cents and floating dollars do not mix. Keep the contract in integer cents end to end.
  • Changed rounding order. Rounding per line versus on the total can shift a cart by a cent. Keep it per line and test the boundary.
  • Lost error paths. PHP might return null where Python should raise. State the error behavior explicitly.
  • Refactor creep. A cleaner port is not the goal. Behavior parity is. Defer cleanup to a second pass.
  • Untested exemptions. Exemption rules are where ports quietly break. Require one test per exemption.

Adapting the Same Skeleton

  • JavaScript to TypeScript: change the target and ask for strict types plus a schema for the output object.
  • Python to Go: add “Return an error value instead of raising, following Go conventions.”
  • Redesign instead of a port: if you actually want a rewrite, say so and ask for “a second version that simplifies the algorithm, with a note on which behaviors change.”
  • Framework migration: add “Map the request handling layer to FastAPI routes and keep the tax logic untouched.”
  • Property tests: add “Propose three invariants that must hold, such as tax never exceeding subtotal in standard regions.”

Run the generated tests against the old output on a sample of real carts before you cut over; that differential run is the only proof the port is faithful. For prompt structure background, see ChatGPT Settings for Coding, and when an unfamiliar module blocks the port, start with this prompt to explain a codebase. If the new code throws at runtime, work through the ChatGPT debug workflow.

Sources & Notes

Prompt pattern written for ChatGPT (GPT-4o and later) and portable to Claude and Gemini with minor wording changes. The port example follows a conventional PHP-to-Python migration for a serverless checkout service; rounding and currency conventions vary by jurisdiction and should be confirmed against your own accounting rules. Tested behavior: stating a behavior contract up front reduces silent logic changes far more than a bare instruction to “convert” the code. No external data or package versions were fetched, and the example module is illustrative. Always diff the ported logic against the original on real inputs before deploying.

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