# Morph API Documentation > https://docs.morphllm.com > Base URL: https://api.morphllm.com/v1 > OpenAI-compatible. Use any OpenAI SDK pointed at the base URL with a Morph API key. > Fast Models also serve Anthropic's Messages format at POST /v1/messages, so Anthropic SDKs and Claude Code work by changing the base URL. See #anthropic-api. ## Products - [Endpoints](https://docs.morphllm.com/endpoints): Choose general inference or reserved dedicated capacity. - [General inference](https://docs.morphllm.com/general-inference): Call public models through https://api.morphllm.com/v1 with a Morph API key. - [Dedicated endpoints](https://docs.morphllm.com/dedicated-endpoints): Create with `morph dedicated create`, inspect with `status`, monitor with `logs`, and cancel with `stop`. Use the returned endpoint URL plus /v1 and served model name for inference. Reserved GPU plans bill while idle and do not scale to zero. Cancellation before activation is immediate; active service follows its agreement and returned cancellation date. - [Ultra plan](https://docs.morphllm.com/ultra-plan): $200 a month for unlimited Kimi K3.1 and DeepSeek V4.1 Flash with no token meter. Each subscription has per-minute limits on uncached input and output tokens for each model, and requests can return 429 when Morph is at capacity. Other models bill per token. - [Credit top-ups](https://docs.morphllm.com/api-reference/endpoint/credits-topup-create): Agents buy credits with USDC. `morph billing topup ` (or POST https://api.morphllm.com/api/v1/credits/topups with {"amount":"25.00"}) returns an `x402_url`; pay it with an x402 client that supports the auth-capture scheme on Base, then `morph billing topup-status --wait` (or GET /api/v1/credits/topups/{checkoutId}) until `credited` is true. - [Member budgets](https://docs.morphllm.com/api-reference/endpoint/org-member-budget-set): Org admins cap each member's monthly spend on the org's keys from the dashboard Members page or PUT https://api.morphllm.com/api/v1/org/members/{userId}/budget with {"monthlyLimit":"50.00"} (GET /api/v1/org/members/budgets lists members, budgets and spend). A member at their budget gets 429 member_budget_exceeded on org keys until the next UTC month or until the budget is raised. - [Fast Apply](#fast-apply): Code editing at 10,500 tok/s, 98% accuracy - [Compact](#compact): Context compression at 33,000 tok/s, byte-identical output - [WarpGrep](#warpgrep): Semantic code search subagent, ~6 seconds per query - [Reflex](https://docs.morphllm.com/models/reflex): Typed decisions from text, JSON, and images; POST /v1/systemone with model reflex. - [Model Router](#model-router): Prompt complexity classifier, picks cheap vs powerful model - [Fast Models](#fast-models): Open-weight general models (Kimi K3.1 Pro, GLM-5.3, GLM-5.2, GLM-5.3-Flash, DeepSeek V4.1 Flash) - [Anthropic API](#anthropic-api): `/v1/messages` for Anthropic SDKs and Claude Code - [Agent Tools](#agent-tools): edit_file and codebase_search tool definitions for AI agents --- # Fast Apply POST /v1/chat/completions Apply code edits at 10,500 tok/s with 98% accuracy. Takes original code + a partial update snippet and returns the fully merged file. ## Models | Model | Speed | Accuracy | Best For | |-------|-------|----------|----------| | `morph-v3-fast` | 10,500+ tok/s | 96% | Real-time, quick edits | | `morph-v3-large` | 5,000+ tok/s | 98% | Complex changes, highest accuracy | | `auto` | 5,000-10,500 tok/s | ~98% | **Recommended** - auto-selects | ## Message Format ``` Brief description of what you're changing Original complete file content Code snippet showing only changes with // ... existing code ... markers ``` - ``: Optional but recommended. First-person, clear description. - ``: The complete original code. - ``: Only what changes. Use `// ... existing code ...` for unchanged sections. ## Example (TypeScript) ```typescript import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.morphllm.com/v1", }); const response = await openai.chat.completions.create({ model: "morph-v3-fast", messages: [{ role: "user", content: `Add error handling for division by zero function divide(a, b) { return a / b; } function divide(a, b) { if (b === 0) throw new Error('Cannot divide by zero'); // ... existing code ... }`, }], }); const mergedCode = response.choices[0].message.content; ``` ## Example (Python) ```python from openai import OpenAI client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.morphllm.com/v1") response = client.chat.completions.create( model="morph-v3-fast", messages=[{ "role": "user", "content": f"{instruction}\n{original_code}\n{code_edit}" }] ) merged_code = response.choices[0].message.content ``` ## Example (cURL) ```bash curl -X POST "https://api.morphllm.com/v1/chat/completions" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "morph-v3-fast", "messages": [{ "role": "user", "content": "Add error handling\nfunction divide(a, b) {\n return a / b;\n}\nfunction divide(a, b) {\n if (b === 0) throw new Error(\"Cannot divide by zero\");\n // ... existing code ...\n}" }] }' ``` The response is a standard OpenAI chat completion. `choices[0].message.content` contains the fully merged file. --- # Compact POST /v1/compact Compress chat history and code context at 33,000 tok/s. Every surviving line is byte-for-byte identical to the original. 100K tokens compresses in under 2 seconds. Pass `query` to tell the model what matters for the next LLM call. Without it, the model auto-detects from the last user message. ## Native Format ```bash curl -X POST "https://api.morphllm.com/v1/compact" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "text to compress", "query": "what matters for the next LLM call", "compression_ratio": 0.5, "preserve_recent": 0 }' ``` Response includes `output` (compressed text) and `compacted_line_ranges` showing what was removed. ## OpenAI-Compatible Format Also works via `/v1/chat/completions` with `model: "morph-compactor"`: ```python from openai import OpenAI client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.morphllm.com/v1") response = client.chat.completions.create( model="morph-compactor", messages=[{"role": "user", "content": chat_history}], ) compressed = response.choices[0].message.content ``` ## TypeScript SDK ```typescript import { MorphClient } from '@morphllm/morphsdk'; const morph = new MorphClient({ apiKey: "YOUR_API_KEY" }); const result = await morph.compact({ input: chatHistory, query: "How do I validate JWT tokens?", compressionRatio: 0.5, preserveRecent: 3, }); // result.output is the compressed text ``` ## keepContext Tags Wrap sections you never want compressed: ``` // CRITICAL: Auth middleware function authenticate(req, res, next) { ... } ``` Tagged content survives compression verbatim regardless of the compression ratio. ## Compatible Endpoints | Endpoint | Format | Use with | |----------|--------|----------| | `POST /v1/compact` | Native Morph format | Direct HTTP, Morph SDK | | `POST /v1/responses` | OpenAI Responses API | Any OpenAI SDK | | `POST /v1/chat/completions` | OpenAI Chat Completions | Any OpenAI-compatible client | --- # WarpGrep POST /v1/chat/completions Semantic code search subagent. Explores repositories in ~6 seconds using a multi-turn tool-calling loop. The model has tools built in (grep_search, read, list_directory, glob, finish). You do NOT pass a `tools` array. ## Model `morph-warp-grep-v2.1` ## Message Format ```xml /home/user/myproject /home/user/myproject/README.md /home/user/myproject/package.json /home/user/myproject/src /home/user/myproject/src/auth /home/user/myproject/src/auth/login.py /home/user/myproject/src/db /home/user/myproject/src/utils /home/user/myproject/tests /home/user/myproject/config.py Find where user authentication is implemented ``` - ``: Flat list of absolute paths, repo root first, depth 2. No indentation, no tree characters. - ``: Natural language description of what to find. ## Multi-Turn Protocol 1. Send initial message. Response contains `tool_calls` (grep_search, list_directory, etc.) 2. Execute each tool call locally on your filesystem. 3. Return results as `{role: "tool", tool_call_id: "...", content: "..."}` messages. 4. Repeat until the model calls `finish` with code locations. Typically 3-6 turns. ## Example (TypeScript) ```typescript import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.morphllm.com/v1", }); const response = await openai.chat.completions.create({ model: "morph-warp-grep-v2.1", messages: [{ role: "user", content: `\n${repoStructure}\n\n\n\n${searchQuery}\n` }], temperature: 0.0, max_tokens: 2048, }); // Response has tool_calls - execute locally and continue the loop const toolCalls = response.choices[0].message.tool_calls; ``` ## Built-in Tools | Tool | Purpose | |------|---------| | `grep_search` | Search for regex patterns across files | | `read` | Read file contents with optional line ranges | | `list_directory` | Explore directory structure | | `glob` | Find files by name/extension pattern (sorted by mtime) | | `finish` | Submit final answer with code locations | ## Request Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `model` | string | Yes | Must be `morph-warp-grep-v2.1` | | `messages` | array | Yes | Conversation messages | | `temperature` | number | No | Recommended: `0.0` | | `max_tokens` | number | No | Recommended: `2048` | --- # Model Router Classifies a prompt in ~180ms and tells you how to route it. Trained on millions of coding prompts. $0.005 per request. Current endpoints: - `POST /v1/router/classify` — classify the prompt across difficulty / ambiguity / domain; you map labels to your own models. - `POST /v1/router/multimodel` — hand it your candidate models + a policy; it returns the single best model to call. ## /v1/router/classify ```bash curl -s -X POST "https://api.morphllm.com/v1/router/classify" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"input": "Add error handling to this function", "classes": ["difficulty", "ambiguity", "domain"]}' # Returns: { "classifications": { # "difficulty": { "label": "easy", "confidence": 0.93, "meets_threshold": true }, # "ambiguity": { "label": "low", "confidence": 0.88, "meets_threshold": true }, # "domain": { "label": "coding", "confidence": 0.91, "meets_threshold": true } } } ``` - `classes` is optional (defaults to all three). - difficulty: `easy` | `medium` | `hard` (treat as `needs_info` when `meets_threshold` is false) - ambiguity: `low` | `med` | `high` - domain: `general` | `summary` | `coding` | `design` | `data` ## /v1/router/multimodel ```bash curl -s -X POST "https://api.morphllm.com/v1/router/multimodel" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"input": "Add error handling to this function", "allowed_providers": ["anthropic"], "policy": "balanced", "default_model": "claude-sonnet-4-6"}' # Returns: { "model": "claude-haiku-4-5-20251001", "provider": "anthropic", "difficulty": "easy", "confidence": 0.93, ... } ``` - `allowed_models` / `allowed_providers`: union filter (both empty = whole catalog). - `policy`: `balanced` (default) | `cost_efficient`. - `default_model`: returned as-is when the prompt resolves to `needs_info`. - `model` is the model to call next; the classifier signals are echoed back. ## Legacy endpoints (still supported, backward compatible) `POST /v1/router/raw` — returns a difficulty label only: ```bash curl -s -X POST "https://api.morphllm.com/v1/router/raw" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"input": "Add a TODO comment", "mode": "balanced"}' # Returns: { "difficulty": "easy", "confidence": 0.93 } # Values: "easy" | "medium" | "hard" | "needs_info" | modes: "balanced" (default) | "aggressive" ``` `POST /v1/router/{provider}` (`openai`, `anthropic`, `gemini`) — **deprecated**, use `/v1/router/multimodel`. Returns a provider-specific model name: ```bash curl -s -X POST "https://api.morphllm.com/v1/router/anthropic" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"input": "Add error handling to this function", "mode": "balanced"}' # Returns: { "model": "claude-haiku-4-5-20251001", "confidence": 0.93 } ``` SDK (`@morphllm/morphsdk`) still exposes `morph.routers.raw.classify()` and `morph.routers.{provider}.selectModel()` for backward compatibility. --- # Fast Models Open-weight general models on Morph's custom inference stack. OpenAI-compatible. Same API key as Apply and Compact. | Model | ID | Speed | Context | In / Out per 1M | |-------|----|-------|---------|-----------------| | Kimi K3.1 Pro | `morph-kimik31` | ~100 tok/s | 1M | $2.50 / $14.00 | | GLM-5.3 744B | `morph-glm53-744b` | ~80 tok/s | 1M | $1.19 / $6.00 | | GLM-5.2 744B | `morph-glm52-744b` | — | 1M | $1.19 / $6.00 | | GLM-5.3-Flash | `morph-glm53flash` | — | 1M | $0.20 / $0.70 | | DeepSeek V4.1 Flash | `morph-dsv41flash` | — | 1M | $0.12 / $0.80 | | DeepSeek V4.1 Flash 1017 | `morph-dsv41flash-1017` | — | 1M | $0.12 / $0.80 | All models support `tools`, `response_format` (JSON mode + JSON schema), structured outputs, logprobs, and reasoning. `kimi-latest` always points to our newest Kimi model (today `morph-kimik31`) and `deepseek-flash-latest` to our newest DeepSeek Flash model (today `morph-dsv41flash-1017`). Responses report the model that answered, and usage bills at that model's rates. Use a dated ID to stay pinned. DeepSeek V4.1 Flash (`morph-dsv41flash`) and its October 17 snapshot (`morph-dsv41flash-1017`) share a serving pool and list prices, with separate usage and customer pricing records. Both accept text and images, not video. Reasoning is enabled by default. `reasoning_effort` accepts `low`, `high`, `xhigh`, `max`, an integer from 1 to 100, or `none` to disable it. `medium` maps to `high`; `minimal` maps to `low`. JSON mode and JSON schema disable reasoning. [Example and API controls](https://docs.morphllm.com/sdk/components/fast-models#deepseek-v41-flash). ## Kimi K3.1 dynamic tool loading Kimi K3.1 (`morph-kimik31`) can add tool definitions at any point in an OpenAI Chat Completions conversation. Put a non-empty array of standard function definitions in a `system` message and omit `content` entirely: ```json { "model": "morph-kimik31", "messages": [ {"role": "user", "content": "Use Calculator to compute 23 * 47."}, {"role": "system", "tools": [{ "type": "function", "function": { "name": "Calculator", "description": "Evaluate one arithmetic expression", "parameters": { "type": "object", "properties": {"expr": {"type": "string"}}, "required": ["expr"] } } }]} ], "tool_choice": "required" } ``` Calls return in the standard `choices[0].message.tool_calls` field. A dynamic declaration with `content`, including `content: null`, returns HTTP 400. This message shape is K3.1-only and supported through `/v1/chat/completions`; other models use top-level `tools`. Use a small top-level `search_tools` function to discover relevant schemas, then append those schemas in a dynamic system message. Full guide: https://docs.morphllm.com/sdk/components/dynamic-tool-loading Every model bills cached input at a lower rate: Kimi K3.1 $0.29, GLM-5.3 and GLM-5.2 $0.1955, GLM-5.3-Flash $0.04, DeepSeek V4.1 Flash $0.008 per 1M. For machine-readable models, limits and these list prices, fetch https://www.morphllm.com/api/models/json?prices=list. Without `?prices=list`, the same URL serves the OpenRouter provider feed, which carries OpenRouter's per-channel prices. GLM-5.3, GLM-5.2, GLM-5.3-Flash, DeepSeek V4 Flash (`morph-dsv4flash`) and Kimi K3.1 (`morph-kimik31`) support the OpenAI `service_tier` parameter: `"default"`/`"auto"`/omitted is standard processing; `"standby"` is best-effort capacity with no latency target or SLA. A standby request runs only while the fleet is under roughly a quarter of its serving capacity; otherwise it returns `429` with `error.code: "resource_unavailable"` and a `Retry-After` header (nothing generated, nothing billed). Retry with backoff, or resend with `service_tier: "default"`. The response echoes the tier that served it. Standby bills at 50% of the standard per-token rates. Use it for evals, batch labeling, and data generation; keep interactive traffic on `default`. ## Example ```python from openai import OpenAI client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.morphllm.com/v1") response = client.chat.completions.create( model="morph-glm53-744b", messages=[ {"role": "system", "content": "You are a senior backend engineer."}, {"role": "user", "content": "Refactor this Express handler to use async/await: ..."}, ], temperature=0.2, ) ``` Enable reasoning with `reasoning_effort` (or `reasoning: { effort: ... }`). Accepted values per model: DeepSeek and GLM models take `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; Kimi K3.1 takes `none`, `low`, `medium`, `high`, `xhigh`, `max`; Kimi K3.1 Fast takes `none`, `low`, `medium`, `high`. Unsupported values return 400. Reasoning tokens bill as output. --- # Anthropic API POST /v1/messages POST /v1/messages/count_tokens Every Fast Model also serves Anthropic's Messages wire format. Same API key, same models, same per-token billing. Auth accepts `x-api-key: KEY` or `Authorization: Bearer KEY`. Specialized APIs (Apply, Compact, WarpGrep, Router) are OpenAI-format only. Streaming, `tool_use` / `tool_result` blocks, multi-turn history, system prompts, and `cache_control` work as Anthropic documents them. Reasoning arrives as `thinking` content blocks before the `text` block — read `content[-1]`, not `content[0]`. ```bash curl -X POST "https://api.morphllm.com/v1/messages" \ -H "x-api-key: YOUR_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "morph-kimik31", "max_tokens": 1024, "messages": [{"role": "user", "content": "Write a tiny rate limiter in TS."}] }' ``` ```python import anthropic client = anthropic.Anthropic(api_key="YOUR_API_KEY", base_url="https://api.morphllm.com") message = client.messages.create( model="morph-kimik31", max_tokens=1024, messages=[{"role": "user", "content": "Write a tiny rate limiter in TS."}], ) print(message.content[-1].text) ``` ## Claude Code Claude Code speaks the Messages API, so it runs on Morph models with four env vars. `ANTHROPIC_MODEL` remaps sonnet/opus; `ANTHROPIC_SMALL_FAST_MODEL` remaps haiku (titles, summaries, background tasks). ```bash export ANTHROPIC_BASE_URL="https://api.morphllm.com" export ANTHROPIC_AUTH_TOKEN="YOUR_MORPH_API_KEY" export ANTHROPIC_MODEL="morph-kimik31" export ANTHROPIC_SMALL_FAST_MODEL="morph-glm53flash" claude ``` File edits, Bash, Grep, and the rest of Claude Code's tools run through the normal `tool_use` loop. Full guide: https://docs.morphllm.com/guides/coding-agents --- # Agent Tools Tool definitions for building AI agents that use Morph. These are the JSON schemas you pass to your LLM's `tools` parameter. ## edit_file The core tool for code editing. Sends an update snippet to Morph Apply, which returns the fully merged file. ```json { "name": "edit_file", "description": "Edit a file by specifying the changes. The tool will merge your changes with the original file. Use // ... existing code ... to represent unchanged sections.", "parameters": { "properties": { "target_file": { "type": "string", "description": "The path of the file to edit" }, "code_edit": { "type": "string", "description": "The code changes to apply. Use // ... existing code ... for unchanged sections." }, "instructions": { "type": "string", "description": "A brief description of what the edit does" } }, "required": ["target_file", "code_edit", "instructions"] } } ``` Workflow: read the file, construct the `code_edit` with `// ... existing code ...` markers for unchanged parts, send to Morph Apply, write the result back. ## codebase_search Semantic code search powered by WarpGrep. ```json { "name": "codebase_search", "description": "Find snippets of code from the codebase most relevant to the search query", "parameters": { "properties": { "query": { "type": "string", "description": "The search query to find relevant code" }, "target_directories": { "type": "array", "items": {"type": "string"}, "description": "Optional: limit search scope to specific directories" } }, "required": ["query"] } } ``` ## Agent Workflow 1. **Search**: Find relevant code with `codebase_search` or `grep_search` 2. **Read**: Get full file context with `read_file` 3. **Edit**: Make changes with `edit_file` (sends to Morph Apply) 4. **Verify**: Read again to confirm --- # morph CLI + skills (agent integration) One binary; skills tell Claude Code, Codex, Cursor and OpenCode when to call it. Docs: https://docs.morphllm.com/cli and https://docs.morphllm.com/skills ```bash curl -fsSL https://www.morphllm.com/install.sh | bash morph token set --api-key YOUR_API_KEY morph install # skills into detected agents morph search "where is auth validated" [--github owner/repo] [--json] morph apply -i "instruction" -u edit.txt # Fast Apply, // ... existing code ... markers ``` Skills index: https://www.morphllm.com/.well-known/agent-skills/index.json # MCP Server (legacy) For hosts that cannot run commands. `morph install --mcp` registers `morph mcp`; or run the package directly. Set `MORPH_API_KEY`; gate tools with `ENABLED_TOOLS` (allow-list) or `DISABLED_TOOLS` (deny-list). ```bash npx @morphllm/morphmcp@latest ``` Provides `edit_file`, `codebase_search`, and `github_codebase_search` as MCP tools. ### Claude Code ```bash claude mcp add morph -e MORPH_API_KEY=YOUR_API_KEY -e ENABLED_TOOLS=codebase_search,github_codebase_search -- npx -y @morphllm/morphmcp@latest ``` ### Cursor / Windsurf Add to MCP settings: ```json { "mcpServers": { "morph": { "command": "npx", "args": ["-y", "@morphllm/morphmcp@latest"], "env": { "MORPH_API_KEY": "YOUR_API_KEY" } } } } ``` --- # Authentication All endpoints use Bearer token auth: ``` Authorization: Bearer YOUR_API_KEY ``` Get your API key at https://morphllm.com/dashboard/api-keys All products (Apply, Compact, WarpGrep, Router, Fast Models) use the same API key. ## Reflex POST https://api.morphllm.com/v1/systemone with a Morph Bearer key. Body: {"model":"reflex","state":"context","questions":{"urgent":{"type":"noul","instructions":"Is this urgent?"}}}. `state` accepts text or JSON. Optional `images`: base64 data URLs (PNG, JPEG, WebP; at most 16, 8 MB each). Remote image URLs, audio and video are not accepted. Questions: choice (criteria map), noul (yes/no), score (2–10 ordered criteria). Answers contain per-option probabilities and confidence; output_tokens is 0. Input usage sums state plus question across questions, including expanded image tokens. $0.042/M input; $0.002/M cached input; 65,536-token context. Image and automatic caching examples: https://docs.morphllm.com/models/reflex. Repeat the same image, state and question; inspect usage.input_tokens_details.cached_tokens. Full schema: https://docs.morphllm.com/api-reference/endpoint/systemone.