LogoFreestyle

Using Morph LLM for Fast Apply

Adding Morph Models to your App Builder to make it apply code faster and more accurately.

Morph LLM is an external service that is not a part of Freestyle. Freestyle data security, reliability and performance guarantees do not apply to Morph LLM. Please review Morph LLM's terms of service and make a decision independently of Freestyle.

What

Morph Fast Apply is a tool that you give to your AI agent that allows it to edit code or files. When building AI agents that edit code or files you have 3 options:

  1. Rewrite entire files (slow, expensive, loses context, hallucinates updates) - 100+ seconds per file edit
  2. Use search-and-replace (brittle, fails on whitespace/formatting, needs self correction loops) - 86% accurate with Claude 4 Sonnet: 35s per file edit
  3. Fast Apply via an edit_file tool (fast, accurate, semantic) - 98% accurate with Morph + Claude 4 Sonnet: 6s per file edit

When

This guide is for once you already have a working AI App Builder, and you want to upgrade it. By default, all dev servers on Freestyle come with an edit file tool that uses the search-and-replace architecture. However, if you want faster UX, higher accuracy and less hallucinations, Morph is a great option to upgrade to.

How

  1. Get a Morph LLM API key. You can sign up for Morph LLM at morphllm.com. Once you have an account, you can get your API key from the dashboard.

  2. Remove the edit_file tool from your AI App Builder. If you are using the Freestyle Dev Server MCP, you can do this by removing the provided edit_file tool from the tools it returns.

  3. Create a Morph Tool. Below is an example using Morph LLM with Mastra to create a Morph Tool.

The Morph Tool calls Morph LLM using the OpenAI protocol, so you can use it with any compatible OpenAI client.

The tool below uses the FreestyleDevServerFilesystem to read and write files in the dev server's filesystem. This allows the AI agent to edit files directly in the dev server. The internals of the search-and-replace method built into Freestyle Dev Servers use the same systems.

import { createTool } from "@mastra/core/tools";
import { z } from "zod";

import OpenAI from "openai";
import { FreestyleDevServerFilesystem } from "freestyle-sandboxes";

const openai = new OpenAI({
  apiKey: process.env.MORPH_API_KEY,
  baseURL: "https://api.morphllm.com/v1",
});

export const morphTool = (fs: FreestyleDevServerFilesystem) =>
  createTool({
    id: "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 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.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.",
    inputSchema: z.object({
      target_file: z.string().describe("The target filepath to modify."),
      instructions: z
        .string()
        .describe(
          "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."
        ),
      editSnippet: z
        .string()
        .describe(
          "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 ..."
        ),
    }),
    execute: async ({
      context: { target_file, instructions, editSnippet },
    }) => {
      let file;
      try {
        file = await fs.readFile(target_file);
      } catch (error) {
        throw new Error(
          `File not found: ${target_file}. Error message: ${error instanceof Error ? error.message : String(error)}`
        );
      }
      const response = await openai.chat.completions.create({
        model: "morph-v3-large",
        messages: [
          {
            role: "user",
            content: `<instruction>${instructions}</instruction>\n<code>${file}</code>\n<update>${editSnippet}</update>`,
          },
        ],
      });

      const finalCode = response.choices[0].message.content;

      if (!finalCode) {
        throw new Error("No code returned from Morph API.");
      }
      // Write to file or return to your application
      await fs.writeFile(target_file, finalCode);
    },
  });

Considerations

  • Speed and Accuracy: Morph Fast Apply is significantly faster and more accurate than the search-and-replace method. It can handle complex edits with less risk of hallucination.
  • External Vendor: Morph LLM is an external service, so ensure you review their terms of service and understand the implications of using it in your application.
  • Integration: Adding Morph to your AI App Builder is very straightforward. There is no need to change AI Logic, and if you don't like the results, you can always revert to the search-and-replace method.
  • Cost: Using Morph LLM may incur additional costs, however it also saves you tokens in more expensive models. Its worth tracking and analyzing the ROI of using Morph LLM in your AI App Builder.

Closing

You can find out more about Morph LLM and how to use it in your AI App Builder by checking out the Morph LLM Documentation

Freestyle AI

Documentation assistant

Experimental: AI responses may not always be accurate—please verify important details with the official documentation.

How can I help?

Ask me about Freestyle while you browse the docs.