검증 루프: 자기 비판 프롬프트
Wikiprompt, 무료 프롬프트 백과사전에서
검증 루프: 자기 비판 프롬프트 코드를 생성하도록 AI에 지시하고, 버그에 대해 스스로 비판한 후 품질을 개선하기 위해 다시 작성하라는 프롬프트입니다.
프롬프트 내용저장
🌐
def process_payment(user_id, amount_cents, currency="USD", payment_method="card"):
# Assume a database connection and payment gateway are available
user = get_user(user_id)
if not user:
raise ValueError("User not found")
if amount_cents <= 0:
raise ValueError("Amount must be positive")
# Convert to major units for display
amount_display = amount_cents / 100
# Apply discount if user is premium
if user.get("premium"):
amount_cents = int(amount_cents * 0.9) # 10% discount
# Charge the payment
charge = gateway.charge(
amount_cents=amount_cents,
currency=currency,
payment_method=payment_method,
customer_id=user["stripe_id"]
)
# Record transaction
record_transaction(user_id, amount_cents, currency, charge.id)
return {"status": "success", "charge_id": charge.id, "amount": amount_display}
```
**3 potential bugs or edge cases:**
1. **Currency conversion missing** - If `currency` is not the user's default currency, the amount is charged in the wrong currency without conversion, leading to incorrect charges.
2. **Race condition on discount** - The discount calculation uses `amount_cents` after validation but before recording. If the same user makes concurrent requests, the discount could be applied multiple times or the original amount could be recorded incorrectly.
3. **No handling of gateway failure** - If `gateway.charge()` raises an exception (e.g., insufficient funds, network error), the function propagates the error but does not clean up or provide a meaningful response, and the transaction is not recorded.
**Rewritten function fixing these issues:**
```python
def process_payment(user_id, amount_cents, currency="USD", payment_method="card"):
# Validate inputs
if amount_cents <= 0:
raise ValueError("Amount must be positive")
user = get_user(user_id)
if not user:
raise ValueError("User not found")
# 1. Fix: Convert currency if needed
if currency != user.get("default_currency", "USD"):
# Assume exchange_rate function exists
exchange_rate = get_exchange_rate(user["default_currency"], currency)
amount_cents = int(amount_cents * exchange_rate)
# 2. Fix: Use atomic operation for discount (e.g., database lock or idempotency key)
# Use a unique transaction ID to prevent double-processing
transaction_id = generate_uuid()
if transaction_exists(transaction_id):
raise ValueError("Duplicate transaction")
# Apply discount inside a locked context
with db_lock(user_id):
if user.get("premium"):
amount_cents = int(amount_cents * 0.9)
# 3. Fix: Handle gateway errors gracefully
try:
charge = gateway.charge(
amount_cents=amount_cents,
currency=currency,
payment_method=payment_method,
customer_id=user["stripe_id"],
idempotency_key=transaction_id
)
except GatewayError as e:
# Log and re-raise with context
log_error(f"Payment failed for user {user_id}: {e}")
raise PaymentProcessingError(f"Payment failed: {e.message}") from e
# Record transaction only after successful charge
record_transaction(
transaction_id=transaction_id,
user_id=user_id,
amount_cents=amount_cents,
currency=currency,
charge_id=charge.id
)
# Return original amount for display (before conversion/discount)
return {"status": "success", "charge_id": charge.id, "amount": amount_cents / 100}
전체 프롬프트를 보려면 로그인하세요
Continue with:
By logging in, you agree to our Terms of Use and Privacy Policy
사용법
이 프롬프트는 coding와 함께 사용하도록 설계되었습니다. 위의 프롬프트 내용을 복사하여 원하는 AI 도구에 붙여넣으세요.
최상의 결과를 얻으려면 자리 표시자(대괄호 또는 대문자로 표시)를 특정 요구 사항으로 사용자 지정할 수 있습니다.
토론
댓글 0개