POST
/
v1
/
chat
/
completions
cURL
curl --request POST \
  --url https://api.morphllm.com/v1/chat/completions \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "morph-v3-large",
  "messages": [
    {
      "role": "user",
      "content": "<code>def calculate_total(items):\n    total = 0\n    for item in items:\n        total += item.price\n    return total</code>\n<update>def calculate_total(items):\n    total = 0\n    for item in items:\n        total += item.price\n    return total * 1.1  # Add 10% tax</update>"
    }
  ]
}'
{
  "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
  }
}

API Endpoint

Morph uses a standard OpenAI-compatible API.

https://api.morphllm.com/v1/chat/completions
ModelSpeedAccuracy
morph-v3-fast4500+ tok/sec96%
morph-v3-large2500+ tok/sec98%
auto2500-4500 tok/sec~98%

auto will intelligently route your request to the right model based on the complexity of your edit.

Example Request

import { OpenAI } from 'openai';

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

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

Tool Definition

Example Good Edit Pattern:

// ... existing code ...
function calculateTotal(items) {
  // ... existing code ...
  for item in items:
    total += item.price;
  return total * 1.1;  // Add 10% tax
}
// ... existing code ...

const total, setTotal = useState(0);

useEffect(() => {
  setTotal(calculateTotal(items));
}, [items]);

// ... existing code ...
return <div>Total: {total}</div>;

Input Format

The content field in your message should contain two parts:

  • Original code wrapped in <code>...</code> tags
  • Update snippet wrapped in <update>...</update> tags

The update snippet should use truncation markers like // ... existing code ... to indicate unchanged parts of the code. Your system prompt should include instructions on how to handle these markers. Read more about how to handle prompting here.

Edit File Tool Prompt

Use this tool to propose 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 ...

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.

You should bias towards repeating as few lines of the original file as possible to convey the change.
NEVER show unmodified code in the edit, unless sufficient context of unchanged lines around the code you're editing is needed to resolve ambiguity.
If you plan on deleting a section, you must provide surrounding context to indicate the deletion.
DO NOT omit spans of pre-existing code without using the // ... existing code ... comment to indicate its absence.`,

You should specify the following arguments before the others: [target_file]

Example with Python

import openai
import os

USER_PROMPT = """<code>{original_code}</code>
<update>{update_snippet}</update>"""

client = openai.OpenAI(
    api_key=os.getenv("MORPH_API_KEY"),
    base_url="https://api.morphllm.com/v1"
)

def execute_query(original_code: str, update_snippet: str) -> str:
    response = client.chat.completions.create(
        model="morph-v3-large",
        messages=[
            {
                "role": "user",
                "content": USER_PROMPT.format(
                    original_code=original_code,
                    update_snippet=update_snippet
                )
            }
        ]
    )
    return response.choices[0].message.content

Response Format

{
  "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
  }
}

Authorizations

Authorization
string
header
required

Bearer authentication header of the form Bearer <token>, where <token> is your auth token.

Body

application/json

Code update request

The body is of type object.

Response

200
application/json

Chat completion response

The response is of type object.