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

# Edit a finished report

> Make targeted edits to a completed DeepResearch report or deliverable with a plain-English instruction, scoped to a highlighted passage, a section, or the whole document.

Make small, targeted edits to a completed DeepResearch report or deliverable using a plain-English instruction, without re-running the research.

Use editing to fix a figure, tighten or reword a paragraph, adjust tone, add a caveat, update a table row, or add a cited point from sources the task already gathered. It works on both the written markdown report and generated deliverables (spreadsheets, decks, documents, and other files). You can scope an edit to a highlighted passage or a named section, or leave the scope open across the whole document.

Editing is built for surgical revisions, not regeneration. Edits apply exact replacements so untouched text stays byte-for-byte identical, and a single edit is capped in how much of the report it may change. If you need a major rewrite or new research outside what the task gathered, start a new [DeepResearch task](https://docs.valyu.ai/api-reference/endpoint/deepresearch-create.md).

Agent note: when you already have a completed DeepResearch markdown report (`editable: true` in status) and need a targeted refinement ("cut the executive summary to 3 bullets", "add the Q3 revenue figure with its citation", "update a slide or spreadsheet tab"), call `POST /v1/deepresearch/tasks/{id}/edit` instead of starting a new research task. Pass `wait_seconds` up to 20; if the response is `202`, poll `GET /v1/deepresearch/tasks/{id}/edits/{edit_id}` until `status` is `applied`, `declined` or `failed`, then read the updated output from `GET /v1/deepresearch/tasks/{id}/status`. Only start a new task if the change requires new research (`edit.out_of_evidence`) or a large rewrite (`edit.rewrite_requested`). Docs index: [/llms.txt](https://docs.valyu.ai/llms.txt). Append `.md` to any page URL for Markdown.

## Two ways to edit

* **On the Valyu Platform:** Open a completed report, highlight a passage (or pick a section), and type what you want changed in plain English. You can also target generated deliverable files on the task.
* **From an AI agent or application:** An agent that uses DeepResearch as a research subagent can call [`POST /v1/deepresearch/tasks/{id}/edit`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-edit-create) directly in natural language to refine the report it got back (for example, `"Cut the executive summary to 3 bullets"` or `"Add the Q3 revenue figure with its citation"`) without re-running the research.

## Worked agent flow

A typical agent loop creates a DeepResearch task, waits for completion, submits a natural-language edit, polls the edit if needed, and reads the updated version from task status.

Set `wait_seconds` (0 to 20) to wait inline for fast edits: if the edit finishes in time, the endpoint returns `200` with the completed edit record; otherwise it returns `202` with `edit_id` and `retry_after_seconds` so you can poll [`GET /v1/deepresearch/tasks/{id}/edits/{edit_id}`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-edit-get). Send an `Idempotency-Key` header so retrying after a network timeout returns the same edit rather than starting a second one.

```python Python theme={null}
import os
import time
import uuid
import requests

API = "https://api.valyu.ai/v1/deepresearch"
HEADERS = {
    "x-api-key": os.environ["VALYU_API_KEY"],
    "Content-Type": "application/json",
}

# 1. Create a research task
create_res = requests.post(
    f"{API}/tasks",
    headers=HEADERS,
    json={
        "query": "Compare Q3 2026 revenue and margin guidance for Datadog, Dynatrace and New Relic.",
        "mode": "standard",
        "output_formats": ["markdown", "pdf"],
    },
    timeout=30,
)
create_res.raise_for_status()
task_id = create_res.json()["deepresearch_id"]

# 2. Poll task status until completed
while True:
    status = requests.get(f"{API}/tasks/{task_id}/status", headers=HEADERS, timeout=30).json()
    if status["status"] == "completed":
        break
    if status["status"] in ("failed", "cancelled"):
        raise RuntimeError(f"Task ended with status {status['status']}")
    time.sleep(5)

assert status.get("editable"), "Task is not editable"
base_version = status["version"]

# 3. Submit a natural-language edit
edit_res = requests.post(
    f"{API}/tasks/{task_id}/edit",
    headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
    json={
        "instruction": "Cut the executive summary to 3 bullets and add the Q3 revenue figure with its citation.",
        "focus": {
            "section": "Executive Summary",
            "scope": "strict",
        },
        "base_version": base_version,
        "citations": "stable",
        "wait_seconds": 15,
    },
    timeout=30,
)
edit_res.raise_for_status()
edit = edit_res.json()

# 4. If 202 (still running), poll the edit record until terminal status
while edit["status"] == "running":
    time.sleep(edit.get("retry_after_seconds", 3))
    poll_res = requests.get(
        f"{API}/tasks/{task_id}/edits/{edit['edit_id']}",
        headers=HEADERS,
        timeout=30,
    )
    poll_res.raise_for_status()
    edit = poll_res.json()

if edit["status"] != "applied":
    raise RuntimeError(f"Edit {edit['status']}: {edit.get('decline') or edit.get('error')}")

print("Applied version:", edit["version"], "-", edit["summary"])

# 5. Read the updated report from task status
updated = requests.get(f"{API}/tasks/{task_id}/status", headers=HEADERS, timeout=30).json()
print(updated["version"], updated["output"][:300])
```

```typescript TypeScript theme={null}
const API = "https://api.valyu.ai/v1/deepresearch";
const headers = {
  "x-api-key": process.env.VALYU_API_KEY!,
  "Content-Type": "application/json",
};

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

// 1. Create a research task
const createRes = await fetch(`${API}/tasks`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    query: "Compare Q3 2026 revenue and margin guidance for Datadog, Dynatrace and New Relic.",
    mode: "standard",
    output_formats: ["markdown", "pdf"],
  }),
});
const { deepresearch_id: taskId } = await createRes.json();

// 2. Poll task status until completed
let status: any;
while (true) {
  status = await (await fetch(`${API}/tasks/${taskId}/status`, { headers })).json();
  if (status.status === "completed") break;
  if (status.status === "failed" || status.status === "cancelled") {
    throw new Error(`Task ended with status ${status.status}`);
  }
  await sleep(5000);
}

// 3. Submit a natural-language edit
const editRes = await fetch(`${API}/tasks/${taskId}/edit`, {
  method: "POST",
  headers: { ...headers, "Idempotency-Key": crypto.randomUUID() },
  body: JSON.stringify({
    instruction: "Cut the executive summary to 3 bullets and add the Q3 revenue figure with its citation.",
    focus: {
      section: "Executive Summary",
      scope: "strict",
    },
    base_version: status.version,
    citations: "stable",
    wait_seconds: 15,
  }),
});
let edit = await editRes.json();

// 4. If 202 (still running), poll until terminal status
while (edit.status === "running") {
  await sleep((edit.retry_after_seconds ?? 3) * 1000);
  edit = await (await fetch(`${API}/tasks/${taskId}/edits/${edit.edit_id}`, { headers })).json();
}

if (edit.status !== "applied") {
  throw new Error(`Edit ${edit.status}: ${JSON.stringify(edit.decline ?? edit.error)}`);
}

console.log(`Applied version ${edit.version}: ${edit.summary}`);

// 5. Read the updated report from task status
const updated = await (await fetch(`${API}/tasks/${taskId}/status`, { headers })).json();
console.log(updated.version, updated.output.slice(0, 300));
```

```bash cURL theme={null}
# 1. Create a task
curl -s -X POST https://api.valyu.ai/v1/deepresearch/tasks \
  -H "x-api-key: $VALYU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Compare Q3 2026 revenue and margin guidance for Datadog, Dynatrace and New Relic.",
    "mode": "standard",
    "output_formats": ["markdown", "pdf"]
  }'

# 2. Poll status until status is "completed" and check "editable": true
curl -s https://api.valyu.ai/v1/deepresearch/tasks/TASK_ID/status \
  -H "x-api-key: $VALYU_API_KEY"

# 3. Submit an edit (returns 200 if finished within wait_seconds, or 202 while running)
curl -s -X POST https://api.valyu.ai/v1/deepresearch/tasks/TASK_ID/edit \
  -H "x-api-key: $VALYU_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7" \
  -d '{
    "instruction": "Cut the executive summary to 3 bullets and add the Q3 revenue figure with its citation.",
    "focus": {
      "section": "Executive Summary",
      "scope": "strict"
    },
    "base_version": 1,
    "citations": "stable",
    "wait_seconds": 15
  }'

# 4. If 202, poll the edit until status is applied, declined or failed
curl -s https://api.valyu.ai/v1/deepresearch/tasks/TASK_ID/edits/EDIT_ID \
  -H "x-api-key: $VALYU_API_KEY"

# 5. Read the new head version
curl -s https://api.valyu.ai/v1/deepresearch/tasks/TASK_ID/status \
  -H "x-api-key: $VALYU_API_KEY"
```

### Example responses

When an edit is still running after `wait_seconds`, `POST /v1/deepresearch/tasks/{id}/edit` returns `202`:

```json theme={null}
{
  "edit_id": "ed_01j9x4k2m8n7p3q5r6s8t0v2w4",
  "deepresearch_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "running",
  "target": {
    "kind": "report"
  },
  "base_version": 1,
  "focus": {
    "section": "Executive Summary",
    "scope": "strict"
  },
  "created_at": "2026-11-19T14:20:00.000Z",
  "retry_after_seconds": 3
}
```

When the edit completes (either as `200` from `POST /edit` or from `GET /edits/{edit_id}`), the full edit record shows the new `version`, a `summary`, the applied `changes`, any `unapplied` parts of the instruction, `stats`, `warnings`, and the re-rendered `pdf_url` if the task had a PDF:

```json theme={null}
{
  "edit_id": "ed_01j9x4k2m8n7p3q5r6s8t0v2w4",
  "deepresearch_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "applied",
  "target": {
    "kind": "report"
  },
  "base_version": 1,
  "version": 2,
  "focus": {
    "section": "Executive Summary",
    "scope": "strict"
  },
  "created_at": "2026-11-19T14:20:00.000Z",
  "summary": "Condensed the Executive Summary to 3 bullets and added Datadog's Q3 revenue figure with citation [14].",
  "changes": [
    {
      "line": 5,
      "removed": [
        "- Datadog grew revenue across every segment in 2024.",
        "- Gross margin stayed above 80%.",
        "- Net retention held near 115%.",
        "- Free cash flow rose year over year.",
        "- The platform added 400 new products.",
        "- Guidance was raised twice during the year."
      ],
      "added": [
        "- Datadog reported Q3 revenue of $718M [14].",
        "- Gross margin stayed above 80%.",
        "- Guidance was raised twice during the year."
      ]
    }
  ],
  "unapplied": [],
  "stats": {
    "changed_ratio": 0.0812,
    "chars_before": 18240,
    "chars_after": 17911,
    "hunks": 1,
    "lines_removed": 6,
    "lines_added": 3,
    "citations_added": 1,
    "citations_retired": 0,
    "steps": 4,
    "edits_applied": 1,
    "edits_rejected": 0
  },
  "warnings": [],
  "pdf_url": "https://api.valyu.ai/v1/deepresearch/tasks/a1b2c3d4-e5f6-7890-abcd-ef1234567890/assets/report.pdf?version=2"
}
```

Each item in `changes` is one changed block of lines, in order:

| Field | Type | Description |
| - | - | - |
| `line` | integer | The 1-based line in the base version's output (the version the edit started from) where the change begins. |
| `removed` | string\[] | The whole lines removed from the base version, in order. Empty for a pure insertion. |
| `added` | string\[] | The whole lines that replace them in the new version, in order. Empty for a pure deletion. |

`changes` lists at most 50 blocks, and each `removed` or `added` array holds at most 40 lines. `stats` always counts the full edit (`hunks`, `lines_removed`, `lines_added`), so compare it with `changes` to tell whether the list was cut short. To see the complete new text, read the new `version` of the task.

## Edit the report or a deliverable

Set `target` to choose whether to edit the written report or one of the task's generated deliverable files.

### Written report (default)

Omit `target` or send `{"kind": "report"}`.

* **Exact replacements:** The editor makes targeted replacements so untouched passages stay byte-for-byte identical.
* **Charts and images preserved:** Existing charts and images are not removed unless your instruction is about them.
* **PDF re-rendered:** If the task produced a PDF, the updated version gets a newly rendered PDF returned in `pdf_url`.
* **Stale deliverable warning:** If you edit the report on a task that also has deliverable files, the edit record includes a `deliverables_stale` warning to indicate that the files were not changed to match.

### Generated deliverables

Pass `{"kind": "deliverable", "deliverable_id": "f_01"}`, using the `id` from `deliverables[]` in the task status response (deliverable IDs have the form `f_01`, `f_02`, and so on).

A deliverable edit (`xlsx`, `docx`, `pptx`, and so on) patches the program that generated the file and re-runs the same checks before publishing the new file.

```json theme={null}
{
  "instruction": "Add a YoY growth % column to the Revenue Comparison sheet and format it as a percentage with one decimal place.",
  "target": {
    "kind": "deliverable",
    "deliverable_id": "f_01"
  },
  "base_version": 2,
  "wait_seconds": 20
}
```

## Focus an edit on a passage or section

Use the optional `focus` object to direct an edit at a highlighted passage or a specific section. You can combine fields or pass only `section` or `text`.

| Field | Type | Constraints | Purpose |
| - | - | - | - |
| `start_char`, `end_char` | integer | Must be given together; `end_char > start_char` | UTF-16 character offsets into the `output` markdown of `base_version` (as returned by `GET /status`). |
| `text` | string | Up to 20,000 chars | The highlighted text. Offsets are trusted when `text` matches; otherwise `text` is located using `prefix`, `suffix`, `section`, and the offset hint. |
| `prefix`, `suffix` | string | Up to 2,000 chars each | Text immediately before and after the passage to disambiguate repeated phrases. |
| `section` | string | 1 to 300 chars | A section heading. Sent on its own, it focuses that entire section. |
| `scope` | string | `"prefer"` (default) or `"strict"` | `"prefer"` guides the editor to the focused area; `"strict"` rejects any change outside the focus. |

Example targeting a highlighted passage with context:

```json theme={null}
{
  "instruction": "Soften this claim to note that guidance excludes pending acquisitions.",
  "focus": {
    "start_char": 1840,
    "end_char": 1965,
    "text": "Management expects operating margin to expand by 250 bps in FY2027.",
    "prefix": "## Outlook\n\n",
    "suffix": " Capital expenditure is projected to remain flat.",
    "section": "Outlook",
    "scope": "strict"
  },
  "base_version": 1
}
```

If the focus text or section cannot be matched, the API returns `422` with code `focus.not_found`. If `text` appears in multiple places and cannot be disambiguated, the API returns `422` with code `focus.ambiguous` and a `candidates[]` list so your UI or agent can pick the exact occurrence. In both cases, nothing is run.

## Citations and gathered evidence

New citations introduced by an edit can only point to sources that the task actually gathered during research. The editor can search the task's own gathered evidence to bring in a cited point that was not included in the first draft. If your instruction asks for facts that the task never gathered, the edit finishes with `status: "declined"` and code `edit.out_of_evidence`.

Control how citation numbers are updated with the `citations` parameter:

* `"stable"` (default): Kept sources retain their existing citation numbers, newly cited sources are numbered after the highest number used, and dropped citations are retired. Use this when external notes or readers already reference citation numbers.
* `"compact"`: Renumber citations sequentially by first appearance in the report.

## Rules and limits

* **Owner only:** Only the task owner can submit edits, read edit records, read non-head versions, or restore versions. Shared and public viewers receive `403`.
* **Completed markdown reports only:** The task must have `status: "completed"` and be a markdown report, not a structured JSON-schema output. Check `editable: true` in [`GET /v1/deepresearch/tasks/{id}/status`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-status).
* **One edit at a time:** Only one edit or restore can run at a time per task. Concurrent requests receive `409` with `edit.in_progress`.
* **Optimistic concurrency:** Pass `base_version` to ensure you are editing the version you read. If another edit or restore moved the head forward, you get `409` with `edit.revision_conflict`.
* **Strict JSON body:** Unknown fields in the request body are rejected with `400` `edit.invalid_request`. `instruction` must be 1 to 4,000 characters and `wait_seconds` must be between 0 and 20.
* **Idempotency:** Pass an `Idempotency-Key` header on `POST /edit`. Replaying the request with the same key returns the same edit.

## Error and decline codes

Request-level problems return an HTTP error (`4xx`) before an edit runs. Content-level refusals finish with HTTP `200` and `status: "declined"`, with details in `decline: { code, message, suggestion }`.

### HTTP errors

| HTTP | Code | Meaning | What to do |
| - | - | - | - |
| `400` | `edit.invalid_request` | Invalid field values, unknown JSON fields, or invalid offset pair | Fix the request body; do not retry unchanged |
| `403` | - | Caller does not own the task (for example a shared or public viewer) | Use the task owner's API key |
| `404` | - | Task or edit not found, or editing is not enabled | Verify the task ID and edit ID |
| `409` | `edit.task_not_completed` | Task is still running, queued, paused, failed, or cancelled | Wait until task `status` is `completed` |
| `409` | `edit.in_progress` | Another edit or restore is currently running on this task | Poll `active_edit` from task status and retry after it finishes |
| `409` | `edit.revision_conflict` | `base_version` is behind the current head version | Read the latest head via `GET /status` and resubmit with the new `version` |
| `409` | `edit.unsupported_task` | Task output is not an editable markdown report (for example JSON-schema output) | Check `editable` on status; start a markdown task if you need report editing |
| `422` | `focus.not_found` | Focus passage, offsets, or section could not be matched | Check `base_version` markdown offsets or broaden `focus` |
| `422` | `focus.ambiguous` | Focus matched more than one location (nothing was run) | Read `candidates[]` from the error body and resubmit with offsets or `prefix`/`suffix` |
| `429` | `edit.busy` | Temporary capacity limit | Retry later with backoff |

### Declined and failed edit records

When an edit finishes with `status: "declined"`, inspect `decline.code` and `decline.suggestion`:

| Code | Meaning | What to do |
| - | - | - |
| `edit.rewrite_requested` | Requested change exceeds the edit size cap | Break into smaller targeted edits, or start a new DeepResearch task for a full rewrite |
| `edit.out_of_evidence` | Requires facts not present in the task's gathered sources | Start a new DeepResearch task to gather the missing evidence |
| `edit.contradictory` | Instruction contradicts itself or the report's constraints | Clarify and resubmit the instruction |
| `edit.unsafe_instruction` | Instruction cannot be safely applied | Revise the instruction |
| `edit.not_applicable` | Instruction does not apply to the chosen target or focused passage | Check `target` and `focus`, then resubmit |
| `edit.no_change` | Target already satisfies the instruction; no new version was created | No action needed |

If an edit fails with `status: "failed"` and error code `edit.interrupted` (`retryable: true`), the edit was interrupted by a service restart. Submit the edit again with a new `Idempotency-Key`.

## Version history and restore

Every applied edit creates a new version, and older versions stay readable and restorable as a safety net. History is never deleted.

* **Check the current version:** Completed task responses from [`GET /v1/deepresearch/tasks/{id}/status`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-status) include `editable`, `version` (the current head), `version_count`, `revised_at`, and `active_edit`.
* **Read an older version:** Call `GET /v1/deepresearch/tasks/{id}/status?version=N` to retrieve that version's `output`, `sources`, `pdf_url`, `deliverables`, and `is_latest`. Asset and deliverable routes (`GET /v1/deepresearch/tasks/{id}/assets/report.pdf?version=N` and deliverable file routes) also accept `?version=N`. Only the task owner can read a non-head version.
* **List all versions:** Call [`GET /v1/deepresearch/tasks/{id}/versions`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-versions-list) to inspect each version (`original`, `edit`, or `restore`) along with its `edit_id`, `instruction`, `summary`, `stats`, `is_head`, and `pdf_url`.
* **Restore a previous version:** Call [`POST /v1/deepresearch/tasks/{id}/versions/{n}/restore`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-versions-restore). Restore is synchronous with no model call and creates a new head version equal to version `n`:

```bash theme={null}
curl -s -X POST https://api.valyu.ai/v1/deepresearch/tasks/TASK_ID/versions/1/restore \
  -H "x-api-key: $VALYU_API_KEY"
```

```json theme={null}
{
  "version": 3,
  "restored_from": 1
}
```

## API reference

> [card] [Create edit](https://docs.valyu.ai/api-reference/endpoint/deepresearch-edit-create.md)
>
> `POST /v1/deepresearch/tasks/{id}/edit`

> [card] [Get edit](https://docs.valyu.ai/api-reference/endpoint/deepresearch-edit-get.md)
>
> `GET /v1/deepresearch/tasks/{id}/edits/{edit_id}`

> [card] [List edits](https://docs.valyu.ai/api-reference/endpoint/deepresearch-edit-list.md)
>
> `GET /v1/deepresearch/tasks/{id}/edits`

> [card] [List versions](https://docs.valyu.ai/api-reference/endpoint/deepresearch-versions-list.md)
>
> `GET /v1/deepresearch/tasks/{id}/versions`

> [card] [Restore version](https://docs.valyu.ai/api-reference/endpoint/deepresearch-versions-restore.md)
>
> `POST /v1/deepresearch/tasks/{id}/versions/{n}/restore`

> [card] [Get status](https://docs.valyu.ai/api-reference/endpoint/deepresearch-status.md)
>
> Read `editable`, `version`, `active_edit`, or fetch `?version=N`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.