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

# Enterprise Apply

> Enterprise Apply API with custom model configurations

> [!WARNING]
>
> **🔒 CONFIDENTIAL - INTERNAL USE ONLY**
>
> This page contains proprietary enterprise API documentation and is linked to your account. Do not share any information mentioned here with anyone external to your company. This documentation is for internal development and integration purposes only.

# Quickstart

Switch to instruction-guided editing with 98% accuracy in 3 steps.

## Prerequisites

* Enterprise API key from your Morph account
* Access to `https://api.morphllm.com/v1/`

| Model | Speed | Accuracy | Input Limit | Output Limit |
| - | - | - | - | - |
| morph-v3-fast | 10,500+ tok/sec | **96%** | **16k tokens** | **16k tokens** |
| morph-v3-large | 5000+ tok/sec | **98%** | **16k tokens** | **16k tokens** |
| auto | 5000-10,500tok/sec | **98%** | **16k tokens** | **16k tokens** |

## 1. Configure Your Edit Tool

Set up your AI agent to generate the proper instructions guided format for the highest accuracy editing.

> [tab] XML Tool
>
> **Edit File Tool Description:**
>
> ````xml 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.
> ALWAYS make all edits to a file in a single edit_file instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.
> ````
>
> **Parameters:**
>
> * `target_filepath` (string, required): The path of 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] JSON Tool (Simple)
>
> **Tool Definition:**
>
> ````json 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.\nALWAYS make all edits to a file in a single edit_file instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.",
>   "parameters": {
>     "properties": {
>       "target_filepath": {
>         "type": "string",
>         "description": "Path of the 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_filepath", "instructions", "code_edit"]
>   }
> }
> ````

> [!WARNING]
>
> The `instructions` field should be generated by your AI model, not user input.
> Follow the tool description above nearly verbatim - terminology like "use it to disambiguate uncertainty in the edit" should be used.
> Example: "I am adding error handling to the user authentication function"

## 2. Send to Morph Enterprise API

```typescript enterprise_apply.ts theme={null}
import { OpenAI } from 'openai';

const client = new OpenAI({
  apiKey: 'your-enterprise-api-key',
  baseURL: 'https://api.morphllm.com/v1'
});

const testOriginalCode = `
const a = 1
const b = 2
function add(a, b) {
  return a + b
}

function subtract(a, b) {
  return a - b
}

const authenticateUser () => {
  return "Authenticated"
}
`;

// Test data - your agent should generate these
const testInstruction = "I will add the real user authentication function and remove the old authentication method";

const testUpdateSnippet = `
  // ... existing code ...
const authenticateUser = (email, password) => {
  const result = await verifyUser(email, password)
  if (result) {
    return "Authenticated"
  } else {
    return "Unauthenticated"
  }
}
`;

async function applyEnterpriseEdit(
  instruction: string, 
  originalCode: string, 
  updateSnippet: string
): Promise<string> {
  const response = await client.chat.completions.create({
    model: "morph-v3-fast",
    messages: [
      {
        role: "user",
        content: `<instruction>${instruction}</instruction>\n<code>${originalCode}</code>\n<update>${updateSnippet}</update>`
      }
    ]
  });
  
  return response.choices[0].message.content || '';
}

// Example usage
async function main() {
  try {
    const finalCode = await applyEnterpriseEdit(
      testInstruction, 
      testOriginalCode, 
      testUpdateSnippet
    );
    console.log("Final merged code:");
    console.log(finalCode);
  } catch (error) {
    console.error("Error applying edit:", error);
  }
}

// Run the example
main();
```

```python enterprise_apply.py theme={null}
import openai
import asyncio

client = openai.OpenAI(
    api_key="your-enterprise-api-key",
    base_url="https://api.morphllm.com/v1"
)

test_original_code = """
const a = 1
const b = 2
def add(a, b):
  return a + b
}

def subtract(a, b):
  return a - b
}

def authenticateUser ():
  return "Authenticated"
}
"""

# Test data - your agent should generate these
test_instruction = "I will add the real user authentication function and remove the old authentication method" # This is the instruction that your agent should generate

test_update_snippet = """
def authenticateUser (email, password) => {
  # ... existing code ...
  result = await verifyUser(email, password)
  if (result) {
    return "Authenticated"
  } else {
    return "Unauthenticated"
  }
}
"""

def apply_enterprise_edit(instruction: str, original_code: str, update_snippet: str):
    """Apply an enterprise edit using Morph's instruction-guided editing."""
    response = client.chat.completions.create(
        model="morph-v3-fast",
        messages=[
            {
                "role": "user",
                "content": f"<instruction>{instruction}</instruction>\n<code>{original_code}</code>\n<update>{update_snippet}</update>"
            }
        ]
    )
    
    return response.choices[0].message.content

# Example usage
if __name__ == "__main__":
    final_code = apply_enterprise_edit(
        test_instruction, 
        test_original_code, 
        test_update_snippet
    )
    print("Final merged code:")
    print(final_code)
```

## 3. Handle the Response

Extract the merged code from the enterprise API response.

**Response Format:**

```json theme={null}
final_code = response.choices[0].message.content
```

**Extract the Final Code:**

```typescript extract_code.ts theme={null}
const finalCode = response.choices[0].message.content;
// Write to file or return to your application
await fs.writeFile(targetFile, finalCode);
```

```python extract_code.py theme={null}
final_code = response.choices[0].message.content
# Write to file or return to your application  
with open(target_file, 'w') as f:
    f.write(final_code)
```

***

## Enterprise Features

> [card] Perfect Accuracy
>
> Instruction-guided editing achieves 98% accuracy on complex code changes

> [card] 44k Input Tokens
>
> Handle entire large files, complete modules, and complex codebases

> [card] 36k Output Tokens
>
> Generate complete implementations, full refactors, and comprehensive updates

**Migration from Standard API:**

> [!NOTE]
>
> Enterprise API requires an `<instruction>` field but maintains backward compatibility with existing `<update>` patterns.


## OpenAPI

````yaml POST /v1/chat/completions
openapi: 3.1.0
info:
  title: Morph API
  version: 1.2.0
  description: >-
    The Morph public API at api.morphllm.com: OpenAI- and Anthropic-compatible
    inference (chat completions, messages), Fast Apply code editing, Compact
    context compression, System One typed decisions, model listing, and
    dedicated endpoint management, agentic credit top-ups paid over x402, and
    organization member budgets. Model ids, prices, and context windows are
    served live at https://www.morphllm.com/api/models/json.
  contact:
    name: Morph
    url: https://morphllm.com
    email: info@morphllm.com
  license:
    name: Proprietary
    url: https://morphllm.com/privacy/tos
servers:
  - url: https://api.morphllm.com
    description: Production
security: []
tags:
  - name: chat
    description: >-
      OpenAI- and Anthropic-compatible chat inference, including Fast Apply and
      WarpGrep models.
  - name: compact
    description: Context compression for long agent conversations.
  - name: systemone
    description: 'Typed decisions: a state in, a probability distribution per question out.'
  - name: models
    description: Model listing.
  - name: dedicated
    description: Dedicated endpoint discovery, status, and cancellation.
  - name: credits
    description: Agentic credit top-ups paid in USDC over x402.
  - name: organization
    description: Organization member budgets.
  - name: telemetry
    description: Usage reporting hooks.
paths:
  /v1/chat/completions:
    post:
      tags:
        - chat
      summary: Create a chat completion
      description: >-
        Apply changes from big models into your files. Find your [API
        key](https://morphllm.com/dashboard). The endpoint is OpenAI-compatible
        and serves two request shapes, selected by `model`: Morph Apply
        (`morph-v3-fast`, `morph-v3-large`, `auto`) merges an edit snippet into
        an original file, and Warp Grep (`morph-warp-grep-v1`) runs an agentic
        repository search. Set `stream: true` to receive the completion as a
        `text/event-stream` of `chat.completion.chunk` deltas; the 200 response
        below documents the non-streaming shape.
      operationId: createChatCompletion
      requestBody:
        description: Chat completion request for Apply or Warp Grep (OpenAI-compatible)
        required: true
        content:
          application/json:
            example:
              model: morph-v3-fast
              messages:
                - role: user
                  content: |-
                    <instruction>I will add error handling</instruction>
                    <code>function divide(a, b) {
                      return a / b;
                    }</code>
                    <update>function divide(a, b) {
                      if (b === 0) throw new Error('Division by zero');
                      return a / b;
                    }</update>
              stream: false
              max_tokens: 150
              temperature: 0
            schema:
              anyOf:
                - $ref: '#/components/schemas/ChatCompletionRequest'
                - $ref: '#/components/schemas/WarpGrepRequest'
              description: >-
                Either a Morph Apply request or a Warp Grep request,
                discriminated by `model`.
              example:
                model: morph-v3-fast
                messages:
                  - role: user
                    content: |-
                      <instruction>I will add error handling</instruction>
                      <code>function divide(a, b) {
                        return a / b;
                      }</code>
                      <update>function divide(a, b) {
                        if (b === 0) throw new Error('Division by zero');
                        return a / b;
                      }</update>
                stream: false
                max_tokens: 150
                temperature: 0
      responses:
        '200':
          description: Chat completion response
          content:
            application/json:
              example:
                id: chatcmpl-123
                object: chat.completion
                created: 1677652288
                choices:
                  - index: 0
                    message:
                      role: assistant
                      content: |

                        def calculate_total(items):
                            total = 0
                            for item in items:
                                total += item.price
                            return total * 1.1  # Add 10% tax
                    finish_reason: stop
                usage:
                  prompt_tokens: 25
                  completion_tokens: 32
                  total_tokens: 57
              schema:
                $ref: '#/components/schemas/ChatCompletionResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalError'
      security:
        - bearerAuth: []
components:
  schemas:
    ChatCompletionRequest:
      type: object
      properties:
        model:
          type: string
          enum:
            - morph-v3-fast
            - morph-v3-large
            - auto
          default: morph-v3-fast
          description: ID of the Apply model to use, or `auto` to let the router choose
          example: morph-v3-fast
        messages:
          type: array
          items:
            $ref: '#/components/schemas/Message'
          default:
            - role: user
              content: |-
                <instruction>I will add error handling</instruction>
                <code>function divide(a, b) {
                  return a / b;
                }</code>
                <update>function divide(a, b) {
                  if (b === 0) throw new Error('Division by zero');
                  return a / b;
                }</update>
          description: >-
            Array containing a single user message with structured content using
            instruction-guided format
          example:
            - role: user
              content: |-
                <instruction>I will add error handling</instruction>
                <code>function divide(a, b) {
                  return a / b;
                }</code>
                <update>function divide(a, b) {
                  if (b === 0) throw new Error('Division by zero');
                  return a / b;
                }</update>
        stream:
          type: boolean
          default: false
          description: >-
            Enable streaming response. When true the response is a
            `text/event-stream` of OpenAI-style `chat.completion.chunk` deltas
            terminated by `data: [DONE]`.
          example: false
        max_tokens:
          type: integer
          description: Maximum number of tokens the Apply model may generate
          example: 150
        temperature:
          type: number
          default: 0
          description: >-
            Sampling temperature for the Apply request (0.0 for deterministic
            output)
          example: 0
      required:
        - model
        - messages
      title: Morph Apply
      description: >-
        Apply request — merges an edit snippet into the original file with a
        Morph Apply model.
      example:
        model: morph-v3-fast
        messages:
          - role: user
            content: |-
              <instruction>I will add error handling</instruction>
              <code>function divide(a, b) {
                return a / b;
              }</code>
              <update>function divide(a, b) {
                if (b === 0) throw new Error('Division by zero');
                return a / b;
              }</update>
        stream: false
        max_tokens: 150
        temperature: 0
    WarpGrepRequest:
      type: object
      properties:
        model:
          type: string
          enum:
            - morph-warp-grep-v1
          default: morph-warp-grep-v1
          description: ID of the Warp Grep model
          example: morph-warp-grep-v1
        messages:
          type: array
          items:
            $ref: '#/components/schemas/WarpGrepMessage'
          description: >-
            Multi-turn conversation with system prompt, user queries, assistant
            tool calls, and tool results
          example:
            - role: system
              content: You are a code search agent...
            - role: user
              content: |-
                <repo_structure>
                myapp/
                  src/
                    auth/
                </repo_structure>

                <search_string>
                Find JWT validation
                </search_string>
        temperature:
          type: number
          default: 0
          description: Sampling temperature (0.0 recommended for deterministic search)
          example: 0
        max_tokens:
          type: integer
          description: Maximum tokens per response
          default: 2048
          example: 2048
      required:
        - model
        - messages
      title: Warp Grep
      description: >-
        Warp Grep request — an agentic repository search turn driven by XML tool
        calls.
      example:
        model: morph-warp-grep-v1
        messages:
          - role: system
            content: You are a code search agent...
          - role: user
            content: |-
              <repo_structure>
              myapp/
                src/
                  auth/
              </repo_structure>

              <search_string>
              Find JWT validation
              </search_string>
        temperature: 0
        max_tokens: 2048
    ChatCompletionResponse:
      type: object
      properties:
        id:
          $ref: '#/components/schemas/ResponseId'
        object:
          $ref: '#/components/schemas/ResponseObject'
        created:
          $ref: '#/components/schemas/ResponseCreated'
        choices:
          $ref: '#/components/schemas/ResponseChoices'
        usage:
          $ref: '#/components/schemas/ResponseUsage'
      required:
        - id
        - object
        - created
        - choices
        - usage
      description: Completion returned by a Morph chat model.
      example:
        id: chatcmpl-123
        object: chat.completion
        created: 1677652288
        choices:
          - index: 0
            message:
              role: assistant
              content: |

                def calculate_total(items):
                    total = 0
                    for item in items:
                        total += item.price
                    return total * 1.1  # Add 10% tax
            finish_reason: stop
        usage:
          prompt_tokens: 25
          completion_tokens: 32
          total_tokens: 57
    Message:
      type: object
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
          description: Which participant produced this chat message
          example: user
        content:
          type: string
          description: >-
            The content of the message, containing code and update snippets. An
            Apply message uses the format: <instruction>First-person
            description</instruction><code>Complete original file
            content</code><update>Code snippet with // ... existing code ...
            markers</update>
          example: |-
            <instruction>I will add logic to add 10% tax</instruction>
            <code>def calculate_total(items):
                total = 0
                for item in items:
                    total += item.price
                return total</code>
            <update>def calculate_total(items):
                total = 0
                for item in items:
                    total += item.price
                return total * 1.1  # Add 10% tax</update>
      required:
        - role
        - content
      description: A single chat message.
      example:
        role: user
        content: |-
          <instruction>I will add logic to add 10% tax</instruction>
          <code>def calculate_total(items):
              total = 0
              for item in items:
                  total += item.price
              return total</code>
          <update>def calculate_total(items):
              total = 0
              for item in items:
                  total += item.price
              return total * 1.1  # Add 10% tax</update>
    WarpGrepMessage:
      type: object
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
          description: Which participant produced this Warp Grep turn
          example: user
        content:
          type: string
          description: >-
            Message content. User messages use <repo_structure> and
            <search_string> XML. Assistant messages contain <think> reasoning
            and XML tool calls (<grep>, <read>, <list_directory>, <finish>).
          example: |-
            <repo_structure>
            myapp/
              src/
                auth/
            </repo_structure>

            <search_string>
            Find where JWT tokens are validated
            </search_string>
      required:
        - role
        - content
      description: A single turn in a Warp Grep search conversation.
      example:
        role: user
        content: |-
          <repo_structure>
          myapp/
            src/
              auth/
          </repo_structure>

          <search_string>
          Find where JWT tokens are validated
          </search_string>
    ResponseId:
      type: string
      description: Unique identifier for the completion
      example: chatcmpl-123
    ResponseObject:
      type: string
      description: Always `chat.completion`
      example: chat.completion
    ResponseCreated:
      type: integer
      description: Unix timestamp of when the completion was created
      example: 1677652288
    ResponseChoices:
      type: array
      items:
        $ref: '#/components/schemas/Choice'
      description: List of completion choices
      example:
        - index: 0
          message:
            role: assistant
            content: |

              def calculate_total(items):
                  total = 0
                  for item in items:
                      total += item.price
                  return total * 1.1  # Add 10% tax
          finish_reason: stop
    ResponseUsage:
      type: object
      properties:
        prompt_tokens:
          type: integer
          description: Number of tokens in the prompt
          example: 25
        completion_tokens:
          type: integer
          description: Number of tokens in the completion
          example: 32
        total_tokens:
          type: integer
          description: Total number of tokens used
          example: 57
      description: Usage statistics for the completion request
      example:
        prompt_tokens: 25
        completion_tokens: 32
        total_tokens: 57
    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              example: invalid_request_error
              description: Machine-readable error code.
            message:
              type: string
              example: The request body is missing the `model` field.
              description: Human-readable explanation of the failure.
          required:
            - code
            - message
      required:
        - error
      description: Standard error envelope returned by every non-2xx response.
      example:
        error:
          code: invalid_request_error
          message: The request body is missing the `model` field.
    Choice:
      type: object
      properties:
        index:
          type: integer
          description: Index of the choice in the list
          example: 0
        message:
          type: object
          properties:
            role:
              type: string
              description: Author of the generated message, always `assistant`
              example: assistant
            content:
              type: string
              description: Text generated by the model for this choice
              example: |

                def calculate_total(items):
                    total = 0
                    for item in items:
                        total += item.price
                    return total * 1.1  # Add 10% tax
          description: The message generated by the model
          example:
            role: assistant
            content: |

              def calculate_total(items):
                  total = 0
                  for item in items:
                      total += item.price
                  return total * 1.1  # Add 10% tax
        finish_reason:
          type: string
          description: The reason the model stopped generating tokens
          example: stop
      required:
        - index
        - message
        - finish_reason
      description: A single completion choice returned by the model.
      example:
        index: 0
        message:
          role: assistant
          content: |

            def calculate_total(items):
                total = 0
                for item in items:
                    total += item.price
                return total * 1.1  # Add 10% tax
        finish_reason: stop
  responses:
    BadRequest:
      description: Malformed request — missing or invalid fields.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: invalid_request_error
              message: The request body is missing the `model` field.
    Unauthorized:
      description: Missing or invalid API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unauthorized
              message: Invalid API key provided.
    RateLimited:
      description: Rate limited — retry after the interval in the Retry-After header.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: rate_limited
              message: Too many requests. Retry in 12 seconds.
    InternalError:
      description: Internal error — safe to retry with backoff.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: internal_error
              message: Something went wrong on our side.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: opaque
      description: >-
        Morph API key, passed as `Authorization: Bearer sk-...`. Create keys at
        https://www.morphllm.com/dashboard/api-keys.

````

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