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

# Code Apply API

> Direct code apply endpoint with structured parameters for automated workflows

## Overview

The Code Apply API provides a direct interface for applying code edits using the Morph model. This endpoint intelligently merges code changes at **10,500+ tokens/second** with **99.2% accuracy**, designed specifically for AI agents and development tools.

Unlike the chat-based API, this endpoint accepts structured parameters directly, making it easier to integrate into automated workflows and development environments.

## Quickstart

<Steps>
  <Step title="1. Add an edit_file tool to your agent">
    Add the `edit_file` tool to your agent. Use one of the formats below.

    <Tabs>
      <Tab title="General Prompt">
        ````xml Tool Description theme={null}
        Use this tool to make an edit to an existing file.

        This will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.
        When writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.

        For example:

        // ... existing code ...
        FIRST_EDIT
        // ... existing code ...
        SECOND_EDIT
        // ... existing code ...
        THIRD_EDIT
        // ... existing code ...

        You should still bias towards repeating as few lines of the original file as possible to convey the change.
        But, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.
        DO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.
        If you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \n Block 1 \n Block 2 \n Block 3 \n code```, and you want to remove Block 2, you would output ```// ... existing code ... \n Block 1 \n  Block 3 \n // ... existing code ...```.
        Make sure it is clear what the edit should be, and where it should be applied.
        Make edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.
        ````

        **Parameters:**

        * `target_file` (string, required): The target file to modify
        * `instructions` (string, required): A single sentence written in the first person describing what you're changing. Used to help disambiguate uncertainty in the edit.
        * `code_edit` (string, required): Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.
      </Tab>

      <Tab title="JSON Tool (Claude)">
        ````json Tool Definition theme={null}
        {
          "name": "edit_file",
          "description": "Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\nIf you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \\n Block 1 \\n Block 2 \\n Block 3 \\n code```, and you want to remove Block 2, you would output ```// ... existing code ... \\n Block 1 \\n  Block 3 \\n // ... existing code ...```.\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.",
          "input_schema": {
            "type": "object",
            "properties": {
              "target_file": {
                "type": "string",
                "description": "Name or path of target file to modify."
              },
              "instructions": {
                "type": "string",
                "description": "A single sentence instruction describing what you are going to do for the sketched edit. This is used to assist the less intelligent model in applying the edit. Use the first person to describe what you are going to do. Use it to disambiguate uncertainty in the edit."
              },
              "code_edit": {
                "type": "string",
                "description": "Specify ONLY the precise lines of code that you wish to edit. NEVER specify or write out unchanged code. Instead, represent all unchanged code using the comment of the language you're editing in - example: // ... existing code ..."
              }
            },
            "required": ["target_file", "instructions", "code_edit"]
          }
        }
        ````
      </Tab>

      <Tab title="Output Parsing (No Tool)">
        Instead of using tool calls, you can have the agent output code edits in markdown format that you can parse:

        ````markdown Agent Instruction theme={null}
        Use this approach to make edits to existing files by outputting code edits in a specific markdown format.

        This will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.
        When writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.

        For example:

        // ... existing code ...
        FIRST_EDIT
        // ... existing code ...
        SECOND_EDIT
        // ... existing code ...
        THIRD_EDIT
        // ... existing code ...

        You should still bias towards repeating as few lines of the original file as possible to convey the change.
        But, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.
        DO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.
        If you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \n Block 1 \n Block 2 \n Block 3 \n code```, and you want to remove Block 2, you would output ```// ... existing code ... \n Block 1 \n  Block 3 \n // ... existing code ...```.
        Make sure it is clear what the edit should be, and where it should be applied.
        Make edits to a file in a single response instead of multiple responses to the same file. The apply model can handle many distinct edits at once.

        When you want to edit a file, output your code edits using this markdown format:

        ```filepath=path/to/file.js instruction=A single sentence describing what you're changing
        // ... existing code ...
        YOUR_CODE_EDIT_HERE
        // ... existing code ...
        ```

        The instruction should be written in the first person describing what you're changing. Used to help disambiguate uncertainty in the edit.
        ````
      </Tab>
    </Tabs>

    <Warning>
      **IMPORTANT:** The `instructions` param should be generated by the model, not hardcoded.
      Example: "I am adding error handling to the user auth and removing the old auth functions"
    </Warning>
  </Step>

  <Step title="2. Call the API">
    Send the original code and edit snippet to the Code Apply endpoint:

    ```python theme={null}
    import requests

    url = "https://api.morphllm.com/v1/code/apply"
    api_key = "[YOUR_API_KEY]"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    data = {
        "initial_code": initial_code,
        "edit_snippet": edit_snippet,
    }

    response = requests.post(url, headers=headers, json=data)
    return response.json()
    ```
  </Step>

  <Step title="3. Get the merged code">
    Extract the final merged code from the response:

    ```python theme={null}
    merged_code = response.json()["merged_code"]
    ```

    **Response format:**

    ```json theme={null}
    {
      "merged_code": "string",
      "usage": {
        "prompt_tokens": "number",
        "completion_tokens": "number",
        "total_tokens": "number"
      }
    }
    ```
  </Step>
</Steps>

## Models

Choose the model that best fits your use case:

<Table>
  <TableHead>
    <TableRow>
      <TableHeader>Model</TableHeader>
      <TableHeader>Speed</TableHeader>
      <TableHeader>Accuracy</TableHeader>
      <TableHeader>Best For</TableHeader>
    </TableRow>
  </TableHead>

  <TableBody>
    <TableRow>
      <TableCell>
        <code>morph-v3-fast</code>
      </TableCell>

      <TableCell>10,500+ tok/sec</TableCell>
      <TableCell>97%</TableCell>
      <TableCell>Real-time applications, best for most coding agents and files</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>morph-v3-large</code>
      </TableCell>

      <TableCell>5000+ tok/sec</TableCell>
      <TableCell>98.8%</TableCell>
      <TableCell>Complex changes, highest accuracy, best for complex edits</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>auto</code>
      </TableCell>

      <TableCell>5000-10,500tok/sec</TableCell>
      <TableCell>\~98.8%</TableCell>

      <TableCell>
        <strong>Recommended</strong> - automatically selects optimal model
      </TableCell>
    </TableRow>
  </TableBody>
</Table>

## Request Format

```json theme={null}
{
  "initial_code": "string",
  "edit_snippet": "string", 
  "instructions": "string (optional)",
  "model": "string (optional)",
  "stream": "boolean (optional)"
}
```

### Parameters

* **`initial_code`** (required): The complete original code that needs modification
* **`edit_snippet`** (required): Code snippet showing the changes with `// ... existing code ...` markers for unchanged sections
* **`instructions`** (optional): Brief description of what you're changing to help disambiguate the edit
* **`model`** (optional): Model to use (`morph-v3-fast`, `morph-v3-large`, or `auto` - defaults to `auto`)
* **`stream`** (optional): Whether to stream the response (defaults to `false`)

## Response Format

### Non-Streaming Response

```json theme={null}
{
  "mergedCode": "string",
  "usage": {
    "prompt_tokens": "number",
    "completion_tokens": "number", 
    "total_tokens": "number"
  }
}
```

### Streaming Response

For streaming requests (`stream: true`), the response follows the Server-Sent Events (SSE) format with incremental code updates.

## Example Request

```bash theme={null}
curl -X POST "https://api.morphllm.com/v1/code/apply" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "initial_code": "function divide(a, b) {\n  return a / b;\n}",
    "edit_snippet": "function divide(a, b) {\n  if (b === 0) {\n    throw new Error('\''Cannot divide by zero'\'');\n  }\n  return a / b;\n}",
    "instructions": "Add error handling to prevent division by zero"
  }'
```

## Example Response

```json theme={null}
{
  "merged_code": "function divide(a, b) {\n  if (b === 0) {\n    throw new Error('Cannot divide by zero');\n  }\n  return a / b;\n}",
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 28,
    "total_tokens": 73
  }
}
```

## Error Codes

<Table>
  <TableHead>
    <TableRow>
      <TableHeader>HTTP Status</TableHeader>
      <TableHeader>Error Code</TableHeader>
      <TableHeader>Description</TableHeader>
    </TableRow>
  </TableHead>

  <TableBody>
    <TableRow>
      <TableCell>
        <code>200</code>
      </TableCell>

      <TableCell>-</TableCell>
      <TableCell>Success - code successfully applied</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>400</code>
      </TableCell>

      <TableCell><code>bad\_request</code></TableCell>
      <TableCell>Bad request - missing required parameters or malformed request</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>401</code>
      </TableCell>

      <TableCell><code>unauthorized</code></TableCell>
      <TableCell>Authentication required - invalid or missing API key</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>500</code>
      </TableCell>

      <TableCell><code>code\_apply\_error</code></TableCell>
      <TableCell>Internal error during code application</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>
        <code>503</code>
      </TableCell>

      <TableCell><code>service\_unavailable</code></TableCell>
      <TableCell>Model not available - service temporarily unavailable</TableCell>
    </TableRow>
  </TableBody>
</Table>

## Key Features

* **High Performance**: Up to 10,500+ tokens/second with morph-v3-fast
* **High Accuracy**: 99.2% accuracy with intelligent code merging
* **Preserves Structure**: Maintains code formatting, indentation, and comments
* **Streaming Support**: Real-time streaming for large code changes
* **Multiple Models**: Choose between speed and accuracy based on your needs
* **Direct Integration**: Simple JSON API designed for automated workflows

<CardGroup cols={2}>
  <Card title="Integration Guide" icon="code" href="/guides/integration">
    Learn how to integrate the Code Apply API into your workflow
  </Card>

  <Card title="Chat Completions API" icon="messages" href="/api-reference/endpoint/apply">
    Use the OpenAI-compatible chat interface instead
  </Card>
</CardGroup>
