Enterprise Apply
Enterprise Apply API with custom model configurations
curl --request POST \
--url https://api.morphllm.com/v1/chat/completions \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data @- <<EOF
{
"model": "morph-v3-fast",
"messages": [
{
"role": "user",
"content": "<instruction>I will add error handling</instruction>\n<code>function divide(a, b) {\n return a / b;\n}</code>\n<update>function divide(a, b) {\n if (b === 0) throw new Error('Division by zero');\n return a / b;\n}</update>"
}
],
"stream": false,
"max_tokens": 150,
"temperature": 0
}
EOFimport requests
url = "https://api.morphllm.com/v1/chat/completions"
payload = {
"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
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'morph-v3-fast',
messages: [
{
role: 'user',
content: '<instruction>I will add error handling</instruction>\n<code>function divide(a, b) {\n return a / b;\n}</code>\n<update>function divide(a, b) {\n if (b === 0) throw new Error(\'Division by zero\');\n return a / b;\n}</update>'
}
],
stream: false,
max_tokens: 150,
temperature: 0
})
};
fetch('https://api.morphllm.com/v1/chat/completions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.morphllm.com/v1/chat/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'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
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.morphllm.com/v1/chat/completions"
payload := strings.NewReader("{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.morphllm.com/v1/chat/completions")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.morphllm.com/v1/chat/completions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}"
response = http.request(request)
puts response.read_body{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "\ndef calculate_total(items):\n total = 0\n for item in items:\n total += item.price\n return total * 1.1 # Add 10% tax\n"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 32,
"total_tokens": 57
}
}{
"error": {
"code": "invalid_request_error",
"message": "The request body is missing the `model` field."
}
}{
"error": {
"code": "unauthorized",
"message": "Invalid API key provided."
}
}{
"error": {
"code": "rate_limited",
"message": "Too many requests. Retry in 12 seconds."
}
}{
"error": {
"code": "internal_error",
"message": "Something went wrong on our side."
}
}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.- XML Tool
- JSON Tool (Simple)
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.
target_filepath(string, required): The path of the target file to modifyinstructions(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.
{
"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"]
}
}
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
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();
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:final_code = response.choices[0].message.content
const finalCode = response.choices[0].message.content;
// Write to file or return to your application
await fs.writeFile(targetFile, finalCode);
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
Perfect Accuracy
44k Input Tokens
36k Output Tokens
<instruction> field but maintains backward compatibility with existing <update> patterns.Authorizations
Morph API key, passed as Authorization: Bearer sk-.... Create keys at https://www.morphllm.com/dashboard/api-keys.
Body
Chat completion request for Apply or Warp Grep (OpenAI-compatible)
- Morph Apply
- Warp Grep
Either a Morph Apply request or a Warp Grep request, discriminated by model.
ID of the Apply model to use, or auto to let the router choose
morph-v3-fast, morph-v3-large, auto "morph-v3-fast"
Array containing a single user message with structured content using instruction-guided format
Show child attributes
Show child attributes
[
{
"role": "user",
"content": "<instruction>I will add error handling</instruction>\n<code>function divide(a, b) {\n return a / b;\n}</code>\n<update>function divide(a, b) {\n if (b === 0) throw new Error('Division by zero');\n return a / b;\n}</update>"
}
]
Enable streaming response. When true the response is a text/event-stream of OpenAI-style chat.completion.chunk deltas terminated by data: [DONE].
false
Maximum number of tokens the Apply model may generate
150
Sampling temperature for the Apply request (0.0 for deterministic output)
0
Response
Chat completion response
Completion returned by a Morph chat model.
Unique identifier for the completion
"chatcmpl-123"
Always chat.completion
"chat.completion"
Unix timestamp of when the completion was created
1677652288
List of completion choices
Show child attributes
Show child attributes
[
{
"index": 0,
"message": {
"role": "assistant",
"content": "\ndef calculate_total(items):\n total = 0\n for item in items:\n total += item.price\n return total * 1.1 # Add 10% tax\n"
},
"finish_reason": "stop"
}
]
Usage statistics for the completion request
Show child attributes
Show child attributes
{
"prompt_tokens": 25,
"completion_tokens": 32,
"total_tokens": 57
}
curl --request POST \
--url https://api.morphllm.com/v1/chat/completions \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data @- <<EOF
{
"model": "morph-v3-fast",
"messages": [
{
"role": "user",
"content": "<instruction>I will add error handling</instruction>\n<code>function divide(a, b) {\n return a / b;\n}</code>\n<update>function divide(a, b) {\n if (b === 0) throw new Error('Division by zero');\n return a / b;\n}</update>"
}
],
"stream": false,
"max_tokens": 150,
"temperature": 0
}
EOFimport requests
url = "https://api.morphllm.com/v1/chat/completions"
payload = {
"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
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'morph-v3-fast',
messages: [
{
role: 'user',
content: '<instruction>I will add error handling</instruction>\n<code>function divide(a, b) {\n return a / b;\n}</code>\n<update>function divide(a, b) {\n if (b === 0) throw new Error(\'Division by zero\');\n return a / b;\n}</update>'
}
],
stream: false,
max_tokens: 150,
temperature: 0
})
};
fetch('https://api.morphllm.com/v1/chat/completions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.morphllm.com/v1/chat/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'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
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.morphllm.com/v1/chat/completions"
payload := strings.NewReader("{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.morphllm.com/v1/chat/completions")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.morphllm.com/v1/chat/completions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"morph-v3-fast\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"<instruction>I will add error handling</instruction>\\n<code>function divide(a, b) {\\n return a / b;\\n}</code>\\n<update>function divide(a, b) {\\n if (b === 0) throw new Error('Division by zero');\\n return a / b;\\n}</update>\"\n }\n ],\n \"stream\": false,\n \"max_tokens\": 150,\n \"temperature\": 0\n}"
response = http.request(request)
puts response.read_body{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "\ndef calculate_total(items):\n total = 0\n for item in items:\n total += item.price\n return total * 1.1 # Add 10% tax\n"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 32,
"total_tokens": 57
}
}{
"error": {
"code": "invalid_request_error",
"message": "The request body is missing the `model` field."
}
}{
"error": {
"code": "unauthorized",
"message": "Invalid API key provided."
}
}{
"error": {
"code": "rate_limited",
"message": "Too many requests. Retry in 12 seconds."
}
}{
"error": {
"code": "internal_error",
"message": "Something went wrong on our side."
}
}