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

# Code

> Generate code with a self-correcting, multi-model loop — a coder writes it, a separate critic reviews it, the coder repairs against the feedback — and get a PrysmProof v2.

<Note>
  **POST** `https://api.prysm1.com/v2/code` · Requires authentication
</Note>

**Code Mode** writes code, reviews it with a *separate* critic model, and repairs against
that feedback until the review passes or a budget/iteration cap is hit
([Reflexion](https://arxiv.org/abs/2303.11366)-style). In `depth` policy several diverse
coders run in parallel and the best candidate is kept. The response carries the files, the
final review verdict, and a [PrysmProof v2](/concepts/prysmproof) that binds the task to the
code it produced.

You pick the objective with a **policy**; PRYSM picks the coder and the critic (or you force
them). See [How Code Mode works](/concepts/code-mode) for the full model.

<Warning>
  This endpoint lives under **`/v2`**, not `/v1`. The SDKs target it automatically with
  `client.code(...)`. **PRYSM never executes the generated code** — the default critic is a
  pure LLM reviewer.
</Warning>

## Authorization

<ParamField header="Authorization" type="string" required>
  Your secret key as a bearer token: `Bearer prysm_sk_...`
</ParamField>

## Body

<ParamField body="task" type="string" required>
  The coding task in natural language, e.g. *"Write a thread-safe LRU cache in Python with tests"*.
</ParamField>

<ParamField body="language" type="string">
  Target language (`python`, `typescript`, `rust`, …). Auto-detected from the task if omitted.
</ParamField>

<ParamField body="policy" type="string" default="balanced">
  The objective dial: `efficiency` (one cheap coder), `depth` (cross several diverse coders
  in parallel and keep the best), or `balanced`.
</ParamField>

<ParamField body="coder_model" type="string">
  Force the model that writes the code. Ignored if it isn't a known catalog model.
</ParamField>

<ParamField body="reviewer_model" type="string">
  Force the critic model that reviews the code. Ignored if it isn't a known catalog model.
</ParamField>

<ParamField body="max_iters" type="integer" default="3">
  Total iterations: the first generation plus up to `max_iters - 1` repairs.
</ParamField>

<ParamField body="review" type="boolean" default="true">
  Set `false` for a single shot — one coder, one draft, no critic loop.
</ParamField>

<ParamField body="max_tokens" type="integer" default="2048">
  Maximum tokens per underlying model call.
</ParamField>

<ParamField body="temperature" type="number" default="0.2">
  Sampling temperature passed to the underlying models. Lower is steadier for code.
</ParamField>

<ParamField body="max_cost_usd" type="number">
  A soft budget hint, in USD. The repair loop stops early once the estimated spend
  approaches this cap.
</ParamField>

<ParamField body="include_trace" type="boolean" default="true">
  Include the per-stage execution trace in `prysm.stages`. Set `false` for a leaner response.
</ParamField>

## Response

<ResponseField name="id" type="string">Unique code-run id, e.g. `prysm-a1b2c3d4`.</ResponseField>
<ResponseField name="object" type="string">Always `code`.</ResponseField>
<ResponseField name="created" type="integer">Unix timestamp (seconds).</ResponseField>
<ResponseField name="task" type="string">The task that was solved.</ResponseField>
<ResponseField name="language" type="string">The target language (detected or forced).</ResponseField>
<ResponseField name="policy" type="string">The policy that ran: `efficiency`, `balanced`, or `depth`.</ResponseField>
<ResponseField name="reason" type="string">Plain-English explanation of how the run was carried out.</ResponseField>
<ResponseField name="passed" type="boolean">Whether the final review passed.</ResponseField>
<ResponseField name="iterations" type="integer">How many generate→review cycles ran.</ResponseField>

<ResponseField name="files" type="array">
  The generated files.

  <Expandable title="files[]">
    <ResponseField name="path" type="string">Relative file path, e.g. `main.py`.</ResponseField>
    <ResponseField name="language" type="string">The file's language.</ResponseField>
    <ResponseField name="content" type="string">The full file contents.</ResponseField>
    <ResponseField name="bytes" type="integer">Length of `content` in bytes.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="review" type="object">
  The final critic verdict, or `null` when `review` was `false`.

  <Expandable title="review">
    <ResponseField name="passed" type="boolean">Whether the critic passed the code.</ResponseField>
    <ResponseField name="score" type="number">The critic's score, `0`–`1`.</ResponseField>
    <ResponseField name="issues" type="string[]">Concrete issues the critic raised (empty when clean).</ResponseField>
    <ResponseField name="reviewer" type="string">The critic model that produced the verdict.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  Aggregate token usage across every model call.

  <Expandable title="usage">
    <ResponseField name="prompt_tokens" type="integer">Total input tokens.</ResponseField>
    <ResponseField name="completion_tokens" type="integer">Total output tokens.</ResponseField>
    <ResponseField name="total_tokens" type="integer">Sum of the two.</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="prysm" type="object">
  The Code Mode extension block.

  <Expandable title="prysm">
    <ResponseField name="code" type="object">
      <Expandable title="code">
        <ResponseField name="policy" type="string">The policy that ran.</ResponseField>
        <ResponseField name="language" type="string">The target language.</ResponseField>
        <ResponseField name="passed" type="boolean">Whether the final review passed.</ResponseField>
        <ResponseField name="score" type="number">The final review score, `0`–`1`.</ResponseField>
        <ResponseField name="confidence" type="number">Blended confidence across the loop, `0`–`1`.</ResponseField>
        <ResponseField name="iterations" type="integer">How many generate→review cycles ran.</ResponseField>
        <ResponseField name="coder_models" type="string[]">Every coder that wrote a candidate.</ResponseField>
        <ResponseField name="reviewer_model" type="string">The critic model.</ResponseField>
        <ResponseField name="models_used" type="string[]">Every model that contributed (coders + critic).</ResponseField>
        <ResponseField name="latency_ms" type="integer">Wall-clock latency in milliseconds.</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="cost" type="object">
      <Expandable title="cost">
        <ResponseField name="total_usd" type="number">Total cost across all model calls, USD.</ResponseField>
        <ResponseField name="estimated" type="boolean">Always `true` — v2 cost is estimated from text length (\~4 chars/token).</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="proof" type="object">
      A verifiable [PrysmProof v2](/concepts/prysmproof) binding the task to the code. Verify
      it later via [`GET /v1/proof/{request_id}`](/api-reference/proof).

      <Expandable title="proof">
        <ResponseField name="request_id" type="string">The id to verify against.</ResponseField>
        <ResponseField name="timestamp" type="string">ISO-8601 UTC timestamp.</ResponseField>
        <ResponseField name="proof_hash" type="string">SHA-256 over the task, files, and stages, e.g. `sha256:a1b2c3d4e5f6...`.</ResponseField>
        <ResponseField name="policy" type="string">The policy that ran.</ResponseField>
        <ResponseField name="language" type="string">The target language.</ResponseField>
        <ResponseField name="passed" type="boolean">Whether the final review passed.</ResponseField>
        <ResponseField name="models_used" type="string[]">Every model that contributed.</ResponseField>
        <ResponseField name="confidence" type="number">Blended confidence across the loop.</ResponseField>
        <ResponseField name="verifiable" type="boolean">Always `true`.</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="stages" type="array">
      Per-stage execution trace (present when `include_trace` is `true`). Stages run as
      `plan` → `generate:0` → `review:0` → `generate:1` → `review:1` … Each stage has a
      `name`, a `results` array with one entry per model call (model id, ok, token counts,
      latency, cost, confidence, role — the raw text is omitted), and a `detail` object.
      A skipped critic (`review: false`) leaves `review:0` with an empty `results` array.
    </ResponseField>
  </Expandable>
</ResponseField>

## Errors

| Status | `error`                 | Meaning                                                |
| ------ | ----------------------- | ------------------------------------------------------ |
| `400`  | `no_task`               | `task` was empty or whitespace.                        |
| `401`  | —                       | Missing or invalid API key.                            |
| `502`  | `no_code_produced`      | Keys are configured but no model produced usable code. |
| `502`  | `code_error`            | The engine raised while generating or reviewing.       |
| `503`  | `no_provider_available` | No provider API keys are configured on the server.     |

<RequestExample>
  ```python Python theme={null}
  from prysm import Prysm

  client = Prysm()
  r = client.code(
      "Write a Python function to add two numbers",
      policy="balanced",
  )
  for f in r["files"]:
      print(f["path"]); print(f["content"])
  print(r["passed"], r["prysm"]["proof"]["proof_hash"])
  ```

  ```typescript Node theme={null}
  import { Prysm } from "@prysmai/sdk";

  const client = new Prysm();
  const r = await client.code(
    "Write a Python function to add two numbers",
    { policy: "balanced" },
  );
  for (const f of r.files) { console.log(f.path); console.log(f.content); }
  console.log(r.passed, r.prysm.proof.proof_hash);
  ```

  ```bash cURL theme={null}
  curl https://api.prysm1.com/v2/code \
    -H "Authorization: Bearer $PRYSM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "task": "Write a Python function to add two numbers",
      "policy": "balanced"
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "prysm-a1b2c3d4",
    "object": "code",
    "created": 1767312000,
    "task": "Write a Python function to add two numbers",
    "language": "python",
    "policy": "balanced",
    "reason": "balanced policy: one mid-tier coder, reviewed and repaired by a reasoning critic.",
    "passed": true,
    "iterations": 1,
    "files": [
      {
        "path": "main.py",
        "language": "python",
        "content": "def add(a, b):\n    \"\"\"Return the sum of two numbers.\"\"\"\n    return a + b\n",
        "bytes": 71
      }
    ],
    "review": {
      "passed": true,
      "score": 0.92,
      "issues": [],
      "reviewer": "deepseek-v4-pro"
    },
    "usage": {
      "prompt_tokens": 86,
      "completion_tokens": 120,
      "total_tokens": 206
    },
    "prysm": {
      "code": {
        "policy": "balanced",
        "language": "python",
        "passed": true,
        "score": 0.92,
        "confidence": 0.9,
        "iterations": 1,
        "coder_models": ["qwen-2.5-72b"],
        "reviewer_model": "deepseek-v4-pro",
        "models_used": ["qwen-2.5-72b", "deepseek-v4-pro"],
        "latency_ms": 3180
      },
      "cost": { "total_usd": 0.000412, "estimated": true },
      "proof": {
        "request_id": "a1b2c3d4-...-...",
        "timestamp": "2026-06-03T00:00:00+00:00",
        "proof_hash": "sha256:7f3a9c2b1e4d8a06",
        "policy": "balanced",
        "language": "python",
        "passed": true,
        "models_used": ["qwen-2.5-72b", "deepseek-v4-pro"],
        "confidence": 0.9,
        "verifiable": true
      },
      "stages": [
        {
          "name": "plan",
          "results": [],
          "detail": { "language": "python", "policy": "balanced", "coder_models": ["qwen-2.5-72b"], "reviewer_model": "deepseek-v4-pro" }
        },
        {
          "name": "generate:0",
          "results": [
            { "model": "qwen-2.5-72b", "ok": true, "in_tokens": 42, "out_tokens": 78, "latency_ms": 1620, "cost_usd": 0.00021, "confidence": 0.8, "role": "coder" }
          ],
          "detail": { "iteration": 0 }
        },
        {
          "name": "review:0",
          "results": [
            { "model": "deepseek-v4-pro", "ok": true, "in_tokens": 44, "out_tokens": 42, "latency_ms": 1560, "cost_usd": 0.0002, "confidence": 0.92, "role": "reviewer" }
          ],
          "detail": { "passed": true, "score": 0.92 }
        }
      ]
    }
  }
  ```
</ResponseExample>
