Prerequisite: You’ll need an account on Morph to obtain an API key.

One-Shot the edit_file tool into your repo

Click here for a prompt for your AI IDE

① Prompt Your Agent

Configure your AI agent with the proper system prompt to handle code editing effectively:

② The Edit File Tool

Implement the edit_file tool in your AI agent with the proper prompt and schema:

Example Edit Pattern:

// Original code:
function calculateTotal(items) {
  total = 0;
  for item in items:
    total += item.price;
  return total;
}

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

Best Practices:

  • Use // ... existing code ... to indicate unchanged sections
  • Provide sufficient context around edits for proper placement
  • Keep instructions concise and action-oriented
  • Minimize token usage by not repeating large unchanged sections

③ Pass to Morph API

When your agent calls the edit_file tool, send the original file content and update snippet to Morph:

Morph API Documentation

View our OpenAI-compatible API

API Base URL:

https://api.morphllm.com/v1

Implementation Example:

import { promises as fs } from 'fs';
import OpenAI from 'openai';

// Initialize the OpenAI client with Morph's API endpoint
const openai = new OpenAI({
  apiKey: process.env.MORPH_API_KEY || 'your-morph-api-key',
  baseURL: 'https://api.morphllm.com/v1'
});

async function editFile(params: {
  target_file: string;
  code_edit: string;
}): Promise<{ success: boolean; message: string; error?: any }> {
  try {
    // 1. Read the original file
    const originalContent = await fs.readFile(params.target_file, 'utf8');
    
    // 2. Send to Morph API
    const response = await openai.chat.completions.create({
      model: 'morph-v2',
      messages: [
        {
          role: 'user',
          content: `<code>${originalContent}</code>\n<update>${params.code_edit}</update>`
        }
      ]
    });
    
    // 3. Write the updated content back to the file
    await fs.writeFile(params.target_file, response.choices[0].message.content);
    
    return {
      success: true,
      message: `File ${params.target_file} was successfully updated`
    };
  } catch (error) {
    return {
      success: false,
      message: `Error: ${error.message}`,
      error
    };
  }
}

Input Format:

The Morph API expects two key components:

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

Why Morph?

Morph’s apply model offers significant advantages over search/replace or full file rewriting:

  • Speed: Process edits at 4500+ tokens per second
  • Native: Models can output code in a natural way without artificial constraints on output format which bias code results
  • Accuracy: Precise application of changes with context awareness
  • Cost-effective: >4x lower token usage compared to generating entire files

For access to our latest models, self-hosting, or business inquiries, please contact us at info@morphllm.com.