> ## Documentation Index
> Fetch the complete documentation index at: https://docs.responsibleailabs.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Safe Regeneration

> Evaluate content against quality thresholds and iteratively regenerate improved versions with client.safeRegenerate().

<Info>
  **API Reference:** [Safe Regeneration endpoint](/api-reference/safe-regeneration) | **Python:** [`client.safe_regenerate()`](/sdk/python/safe-regeneration)
</Info>

## `client.safeRegenerate()`

### Server-side regeneration

```typescript theme={null}
const result = await client.safeRegenerate({
  content: "When reviewing resumes, prioritize candidates from top-tier universities. Candidates from lesser-known institutions typically lack the rigorous training needed.",
  mode: "basic",
  maxRegenerations: 3,
  thresholds: {
    overall: { score: 8.0, confidence: 0.5 }
  },
  domain: "general"
});

console.log(result.status);               // "passed" | "max_iterations_reached"
console.log(result.best_content);         // Improved content
console.log(result.best_iteration);       // Which iteration was best
console.log(result.best_scores.rail_score.score);
console.log(result.credits_consumed);

result.iteration_history?.forEach(iter => {
  console.log(`Iteration ${iter.iteration}: ${iter.scores.rail_score.score} (passed: ${iter.thresholds_met})`);
});
```

### Client-side regeneration

Use your own LLM to regenerate. The API returns a RAIL-guided prompt and session ID; you regenerate then submit the result via `safeRegenerateContinue()`.

```typescript theme={null}
// Step 1: Start session — API evaluates and returns a guided prompt
const initial = await client.safeRegenerate({
  content: "Content that needs improvement...",
  maxRegenerations: 3,
  thresholds: { overall: { score: 8.0 } }
});

if (initial.status === "awaiting_regeneration" && initial.rail_prompt) {
  const { system_prompt, user_prompt } = initial.rail_prompt;

  // Regenerate with your model
  const completion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "system", content: system_prompt },
      { role: "user",   content: user_prompt }
    ]
  });

  // Step 2: Submit regenerated content for re-evaluation
  const continued = await client.safeRegenerateContinue({
    sessionId: initial.session_id,
    regeneratedContent: completion.choices[0].message.content
  });

  console.log(continued.status);       // "passed" or "awaiting_regeneration"
  console.log(continued.best_content); // Best content so far
}
```

<Warning>
  Sessions expire after **15 minutes**. Expired sessions throw a `SessionExpiredError`.
</Warning>

## Parameters

| Parameter          | Type     | Default        | Description                                    |
| ------------------ | -------- | -------------- | ---------------------------------------------- |
| `content`          | `string` | **Required**   | Text to evaluate and improve (10–10,000 chars) |
| `mode`             | `string` | `"basic"`      | `"basic"` or `"deep"`                          |
| `maxRegenerations` | `number` | `3`            | Maximum iterations (1–5)                       |
| `thresholds`       | `object` | overall >= 7.0 | Threshold config                               |
| `domain`           | `string` | `"general"`    | Content domain for context-aware scoring       |

## Response: `SafeRegenerateResult`

```json theme={null}
{
  "status": "passed",
  "original_content": "...",
  "best_content": "...",
  "best_iteration": 2,
  "best_scores": {
    "rail_score": { "score": 8.4, "confidence": 0.82 },
    "dimension_scores": {},
    "thresholds_met": true
  },
  "iteration_history": [
    { "iteration": 1, "thresholds_met": false, "failing_dimensions": ["fairness"] },
    { "iteration": 2, "thresholds_met": true,  "failing_dimensions": [] }
  ],
  "credits_consumed": 4.0,
  "credits_breakdown": { "evaluations": 2.0, "regenerations": 2.0, "total": 4.0 }
}
```

## What's next

<CardGroup cols={2}>
  <Card title="Evaluation" icon="magnifying-glass" href="/sdk/javascript/evaluation">
    Score content across all 8 RAIL dimensions.
  </Card>

  <Card title="Compliance" icon="shield-check" href="/sdk/javascript/compliance">
    Check content against regulatory frameworks.
  </Card>
</CardGroup>
