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

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

<Tabs>
  <Tab title="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>

  <Tab title="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"]
      }
    }
    ````
  </Tab>
</Tabs>

<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"
</Warning>

## 2. Send to Morph Enterprise API

<CodeGroup>
  ```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)
  ```
</CodeGroup>

## 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:**

<CodeGroup>
  ```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)
  ```
</CodeGroup>

***

## Enterprise Features

<CardGroup cols={3}>
  <Card title="Perfect Accuracy" icon="target">
    Instruction-guided editing achieves 98% accuracy on complex code changes
  </Card>

  <Card title="44k Input Tokens" icon="file-text">
    Handle entire large files, complete modules, and complex codebases
  </Card>

  <Card title="36k Output Tokens" icon="code">
    Generate complete implementations, full refactors, and comprehensive updates
  </Card>
</CardGroup>

**Migration from Standard API:**

<Note>
  Enterprise API requires an `<instruction>` field but maintains backward compatibility with existing `<update>` patterns.
</Note>
