← Back to Labs

Fix the Retry Loop

prompt engineering outputFix the Code

This retry loop retries a failed extraction without any feedback about what went wrong. Fix it to include the failed extraction and specific validation errors in the retry prompt.

async function extractWithRetry(
  documentText: string,
  maxRetries: number = 3
): Promise<InvoiceData> {
  let lastResult: InvoiceData | null = null;
  let lastErrors: string[] = [];

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const messages: Message[] = [
      { role: "user", content: documentText },
    ];

    // BUG: On retry, we must include what failed and why.
    if (attempt > 0 && lastResult) {
      messages.push({
        role: "user",
        content: ,
      });
      messages.push({
        role: "user",
        content: ,
      });
    }

    const response = await client.messages.create({
      model: "claude-sonnet-4-20250514",
      max_tokens: 4096,
      messages,
      tools: [extractionTool],
      tool_choice: { type: "tool", name: "extract_invoice" },
    });

    lastResult = parseToolResult(response);
    lastErrors = validateExtraction(lastResult);

    if (lastErrors.length === 0) return lastResult;
  }

  throw new Error(`Extraction failed after ${maxRetries} attempts: ${lastErrors.join(", ")}`);
}
Next Exercise →