> ## 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.

# Policy Engine

> Declarative rules जो RAIL scores को actions में बदलते हैं: block, warn, flag, या allow।

Evaluation आपको बताता है कि score क्या है। Policy engine आपकी application को बताता है कि उसका क्या करना है: "अगर score 7.5 से नीचे चला जाए, तो response को block कर दो।"

किसी policy को लगाने के दो तरीके हैं:

* **Application policy (recommended).** enforcement mode, thresholds, dimension weights, compliance, और safe-regeneration को हर [application](/concepts/applications) के लिए dashboard में एक बार configure करें। यह उस application की keys से की गई हर evaluation पर अपने आप enforce होती है, बिना आपके code में किसी per-request rule के। live policy देखें [`GET /config`](/api-reference/config) से; हर evaluation एक [`policy_outcome`](/api-reference/evaluation) लौटाती है।
* **SDK policy (local).** code में rules declare करें और SDK को अपने process के अंदर उन पर action लेने दें। local-only logic या उन rules के लिए useful जिन्हें आप केंद्रीय रूप से manage नहीं करना चाहते।

<Info>
  **Application policy:** [`GET /config`](/api-reference/config) | **Python SDK:** [`client.eval()` with `policy=`](/sdk/python/policy-engine) | **Sessions:** [RAILSession](/sdk/python/sessions)
</Info>

## Evaluation vs policy

|                 | Evaluation                                          | Policy Engine                               |
| --------------- | --------------------------------------------------- | ------------------------------------------- |
| **Returns**     | Scores, confidence, explanations                    | Action: `block` / `warn` / `flag` / `allow` |
| **Role**        | Observation                                         | Enforcement                                 |
| **कब use करें** | आप scores चाहते हैं और खुद तय करते हैं क्या करना है | आप चाहते हैं SDK अपने आप rules enforce करे  |

## यह कैसे काम करता है

```mermaid theme={null}
flowchart TD
    Eval["Evaluation result\n(scores per dimension)"] --> Engine["Policy Engine"]
    Engine --> R1{"Rule 1\nsafety &lt; 7?"}
    R1 -- yes --> Block["action: block"]
    R1 -- no --> R2{"Rule 2\nfairness &lt; 6?"}
    R2 -- yes --> Flag["action: flag"]
    R2 -- no --> R3{"Rule 3\nreliability &lt; 5?"}
    R3 -- yes --> Warn["action: warn"]
    R3 -- no --> Allow["action: allow"]
```

Rules priority order में evaluate होते हैं। जो rule सबसे पहले match करता है वही primary action तय करता है। नीचे की priority वाले rules जो भी match करते हैं, अपने actions को secondary के तौर पर जोड़ देते हैं, ताकि कोई भी failure चुपचाप छूट न जाए।

## Policy actions

| Action  | कब use करें                                         | Example                                                 |
| ------- | --------------------------------------------------- | ------------------------------------------------------- |
| `block` | response user तक नहीं पहुंचनी चाहिए                 | किसी customer-facing chatbot पर `safety < 5`            |
| `warn`  | response आगे जा सकती है, caller को बताना चाहिए      | `reliability < 6` - response में uncertainty हो सकती है |
| `flag`  | block किए बिना async human review के लिए queue करें | `fairness < 7` - bias review के लिए flag                |
| `allow` | साफ़ तौर पर पास (unmatched content के लिए default)  | rule list के अंत में catch-all                          |

## Policy declare करना

कोई rule तब fire होता है जब उस dimension का score अपनी `threshold` से **नीचे** हो — `threshold` pass होने के लिए जरूरी न्यूनतम score है। उदाहरण के लिए, `Rule(dimension="safety", threshold=7.0, action="block")` हर उस response को block करता है जिसका safety score 7.0 से कम हो।

<CodeGroup>
  ```python Python theme={null}
  from rail_score_sdk import RailScoreClient, Policy, Rule

  client = RailScoreClient(api_key="...")

  policy = Policy(rules=[
      Rule(dimension="safety",      threshold=7.0, action="block"),
      Rule(dimension="fairness",    threshold=6.0, action="flag"),
      Rule(dimension="reliability", threshold=5.0, action="warn"),
  ])

  result = client.eval(
      content="...",
      mode="basic",
      policy=policy,
  )

  print(result.policy_outcome.action)           # "block" | "warn" | "flag" | "allow"
  print(result.policy_outcome.triggered_rules)  # Which rules fired
  print(result.policy_outcome.blocked)          # True if action == "block"
  ```

  ```typescript JavaScript theme={null}
  import { RailScoreClient } from "@responsible-ai-labs/rail-score";

  const client = new RailScoreClient({ apiKey: "..." });

  const policy = {
    rules: [
      { dimension: "safety",      threshold: 7.0, action: "block" },
      { dimension: "fairness",    threshold: 6.0, action: "flag"  },
      { dimension: "reliability", threshold: 5.0, action: "warn"  },
    ],
  };

  const result = await client.eval({ content: "...", mode: "basic", policy });

  console.log(result.policyOutcome.action);
  console.log(result.policyOutcome.blocked);
  ```
</CodeGroup>

## Reusable policies

एक policy एक बार define करें और client से attach कर दें ताकि वह हर `eval()` call पर अपने आप लागू हो:

```python theme={null}
HEALTHCARE_POLICY = Policy(rules=[
    Rule(dimension="safety",       threshold=8.5, action="block"),
    Rule(dimension="reliability",  threshold=7.5, action="block"),
    Rule(dimension="privacy",      threshold=8.0, action="block"),
    Rule(dimension="transparency", threshold=6.0, action="warn"),
])

client = RailScoreClient(
    api_key="...",
    default_policy=HEALTHCARE_POLICY,
)

result = client.eval(content="...", mode="basic")  # Policy applies automatically

if result.policy_outcome.blocked:
    return "I'm unable to provide that information — please consult a healthcare professional."
```

## Session-level policies

एक session पूरी conversation भर quality track करता है। आप ऐसी policy set कर सकते हैं जो aggregate conversation quality पर trigger हो, जो कई turns में धीरे-धीरे आने वाली drift पकड़ने के लिए useful है:

```python theme={null}
from rail_score_sdk import RailScoreClient, RAILSession, Policy, Rule

turn_policy = Policy(rules=[
    Rule(dimension="safety", threshold=5.0, action="block"),
])

session_policy = Policy(rules=[
    Rule(dimension="safety", threshold=7.0, action="flag", aggregate="avg"),
])

session = RAILSession(
    client=client,
    turn_policy=turn_policy,
    session_policy=session_policy,
)

for user_message in conversation:
    response = await generate_response(user_message)
    outcome = session.record(content=response, mode="basic")

    if outcome.turn_blocked:
        send_fallback()
    elif outcome.session_flagged:
        notify_human_reviewer(session.session_id)
    else:
        send(response)
```

## असली policy examples

<Accordion title="Healthcare chatbot">
  ```
  block when safety       < 8.5
  block when reliability   < 7.5
  block when privacy       < 8.0
  warn  when transparency  < 6.0
  ```
</Accordion>

<Accordion title="Hiring assistant">
  ```
  block when fairness    < 8.0
  flag  when inclusivity < 7.0
  warn  when safety      < 6.0
  ```
</Accordion>

<Accordion title="Customer support bot">
  ```
  block when safety      < 7.0
  warn  when reliability < 5.0
  flag  when user_impact < 6.0
  ```
</Accordion>

## आगे क्या

<CardGroup cols={2}>
  <Card title="Python: Policy Engine" icon="python" href="/sdk/python/policy-engine">
    Policy, Rule, और policy callbacks का पूरा API।
  </Card>

  <Card title="Python: Sessions" icon="python" href="/sdk/python/sessions">
    RAILSession lifecycle और aggregate policies।
  </Card>

  <Card title="Concepts: Middleware" icon="layer-group" href="/concepts/middleware">
    zero-boilerplate enforcement के लिए policies को provider wrappers के साथ जोड़ें।
  </Card>

  <Card title="Concepts: Evaluation" icon="magnifying-glass" href="/concepts/evaluation">
    policy rules लगाने से पहले scores को समझें।
  </Card>
</CardGroup>
