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

# Vercel AI SDK

> Stream fast code edits with Morph using the Vercel AI SDK

# Morph + Vercel AI SDK

Stream code edits at 10,500+ tokens/second using the Vercel AI SDK with Morph's fast apply model. Use Vercel's AI Gateway for unified billing, rate limits, and failover across 100+ AI models.

## Setup

### Option 1: AI Gateway (Recommended)

1. Get an [AI Gateway API key](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys%3Futm_source%3Dai_sdk_code_generator_modal\&title=Get+an+AI+Gateway+API+Key) from Vercel
2. Add it to your environment variables as `OPENAI_API_KEY`
3. Install the AI SDK:

```bash theme={null}
npm install ai@beta
```

### Option 2: Direct API

1. Get a Morph API key from the [Morph dashboard](https://morphllm.com)
2. Add it to your environment variables as `MORPH_API_KEY`
3. Install the AI SDK:

```bash theme={null}
npm install ai@beta
```

## Implementation

<CodeGroup>
  ```typescript AI Gateway theme={null}
  import { streamText } from 'ai'
  import { createOpenAI } from '@ai-sdk/openai'

  const openai = createOpenAI({
    apiKey: process.env.OPENAI_API_KEY!,
    baseURL: 'https://gateway.ai.vercel.com/v1',
    headers: {
      'X-Vercel-AI-Provider': 'morph',
    },
  })

  export async function POST(req: Request) {
    const { editInstructions, originalCode, update } = await req.json()

    // Get the morph model through AI Gateway
    const model = openai('morph-v3-fast')

    // Call the language model with the prompt
    const result = streamText({
      model,
      messages: [
        {
          role: 'user',
          content: `<instruction>${editInstructions}</instruction>\n<code>${originalCode}</code>\n<update>${update}</update>`
        }
      ],
      topP: 1,
    })

    // Respond with a streaming response
    return result.toAIStreamResponse()
  }
  ```

  ```typescript Direct API theme={null}
  import { streamText } from 'ai'
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible'

  const morph = createOpenAICompatible({
    apiKey: "YOUR_API_KEY",
    name: 'morph',
    baseURL: 'https://api.morphllm.com/v1'
  })

  export async function POST(req: Request) {
    const { editInstructions, originalCode, update } = await req.json()

    // Get a language model
    const model = morph('morph-v3-fast')

    // Call the language model with the prompt
    const result = streamText({
      model.chat(),
      messages: [
        {
          role: 'user',
          content: `<instruction>${editInstructions}</instruction>\n<code>${originalCode}</code>\n<update>${update}</update>`
        }
      ],
      topP: 1,
    })

    // Respond with a streaming response
    return result.toAIStreamResponse()
  }
  ```

  ````

  ```typescript components/CodeEditor.tsx
  'use client'

  import { useCompletion } from 'ai/react'
  import { useState } from 'react'

  export function CodeEditor() {
    const [originalCode, setOriginalCode] = useState('')
    const [editInstructions, setEditInstructions] = useState('')
    
    const { completion, isLoading, complete } = useCompletion({
      api: '/api/morph',
    })

    const handleApplyEdit = async () => {
      await complete('', {
        body: { originalCode, editInstructions },
      })
    }

    return (
      <div className="grid grid-cols-2 gap-4 p-4">
        <div className="space-y-4">
          <textarea
            value={originalCode}
            onChange={(e) => setOriginalCode(e.target.value)}
            className="w-full h-64 p-3 border rounded-lg font-mono text-sm"
            placeholder="Original code..."
          />
          
          <textarea
            value={editInstructions}
            onChange={(e) => setEditInstructions(e.target.value)}
            className="w-full h-32 p-3 border rounded-lg text-sm"
            placeholder="Edit instructions..."
          />
          
          <button
            onClick={handleApplyEdit}
            disabled={isLoading}
            className="w-full bg-blue-600 text-white px-4 py-2 rounded-lg"
          >
            {isLoading ? 'Applying...' : 'Apply Edit'}
          </button>
        </div>

        <pre className="p-3 border rounded-lg font-mono text-sm bg-gray-50 overflow-auto">
          {completion || 'Edited code will appear here...'}
        </pre>
      </div>
    )
  }
  ````
</CodeGroup>

That's it! Stream fast code edits with Morph using the Vercel AI SDK.
