For years, building production AI agents meant writing Python—even if your entire stack ran on Node.js. In 2026, the TypeScript AI ecosystem has finally grown up. Three frameworks now dominate the landscape, each solving a fundamentally different problem. This guide breaks down Mastra, Vercel AI SDK, and LangGraph.js so you can pick the right one without wasting a sprint.
Building a chatbot or streaming UI? → Vercel AI SDK.
Building a full-stack agent product? → Mastra.
Building mission-critical, stateful workflows? → LangGraph.js.
These three frameworks are not interchangeable. They operate at different layers of the agentic stack. The diagram below shows exactly where each one sits:
Two years ago, if you wanted to build an AI agent, Python was the only serious option. LangChain, AutoGen, CrewAI — the entire tooling ecosystem was built for pip install. TypeScript developers were stuck with thin wrappers, incomplete ports, or writing raw OpenAI API calls by hand.
That era is over. Three forces converged to create a first-class TypeScript AI ecosystem:
The result? Three distinct frameworks, each purpose-built for a different slice of the AI agent problem space. Let's examine each one.
The Vercel AI SDK (now at v7.x) is the most widely installed TypeScript AI package. It is not an agent framework in the traditional sense — it's a model-agnostic interface layer that excels at connecting LLMs to user interfaces with minimal friction.
useChat and useCompletion hooks work across React, Vue, Svelte, and Angular.inputSchema / outputSchema via Zod. Tool input parameters stream automatically, allowing live UI updates as the model "thinks."maxSteps and stopWhen controls let you run multi-turn tool-calling loops without building your own orchestration layer.If your agent needs durable state, complex branching, or cross-session memory, the Vercel AI SDK alone won't cut it. It's a transport layer, not an orchestrator. Pair it with Mastra or LangGraph.js for those use cases.
Mastra, built by the team behind Gatsby, is the 2026 breakout star. It's an opinionated, "batteries-included" TypeScript framework that bundles agents, workflows, RAG, memory, evals, and an observability studio into a single cohesive package.
Critically, Mastra doesn't reinvent the LLM layer. It uses the Vercel AI SDK internally for all model interactions, which means you get the same model-agnostic, streaming-first interface — plus everything else on top.
Think of Mastra as "Next.js for AI agents." It gives you sensible defaults, a dev server, and a clear path from prototype to production — at the cost of some flexibility.
LangGraph.js is the TypeScript implementation of LangGraph, LangChain's low-level orchestration framework. It models agent workflows as directed state graphs — nodes represent logic, edges represent transitions, and a strongly typed state object flows through the entire graph.
In 2026, LangGraph.js has reached full feature parity with its Python counterpart, making it the go-to choice for teams that need surgical control over every decision point in their agent's execution.
PostgresSaver for production). Agents survive server restarts and resume exactly where they left off.interrupt() support allows agents to pause for human approval, then resume seamlessly.
Let's build the same simple agent in all three frameworks: an agent that has access to a getWeather tool and can answer questions about the weather.
import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";
const result = await generateText({
model: openai("gpt-4o"),
prompt: "What's the weather in Tokyo?",
tools: {
getWeather: tool({
description: "Get weather for a city",
parameters: z.object({
city: z.string().describe("City name"),
}),
execute: async ({ city }) => {
// Call your weather API here
return { city, temp: "22°C", condition: "Sunny" };
},
}),
},
maxSteps: 5, // Allow multi-turn tool-calling loop
});
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
const getWeather = createTool({
id: "getWeather",
description: "Get weather for a city",
inputSchema: z.object({
city: z.string().describe("City name"),
}),
outputSchema: z.object({
city: z.string(),
temp: z.string(),
condition: z.string(),
}),
execute: async ({ context }) => {
return { city: context.city, temp: "22°C", condition: "Sunny" };
},
});
const weatherAgent = new Agent({
name: "Weather Agent",
instructions: "You answer weather questions accurately.",
model: openai("gpt-4o"),
tools: { getWeather },
});
const response = await weatherAgent.generate(
"What's the weather in Tokyo?"
);
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";
// 1. Define your tool
const getWeather = tool(
async ({ city }) => {
return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
},
{ name: "getWeather", description: "Get weather for a city",
schema: z.object({ city: z.string() }) }
);
// 2. Define state schema
const AgentState = Annotation.Root({
messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});
// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
const response = await model.invoke(state.messages);
return { messages: [response] };
};
// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", new ToolNode([getWeather]))
.addEdge("__start__", "agent")
.addConditionalEdges("agent", (state) => {
const last = state.messages[state.messages.length - 1];
return last.tool_calls?.length ? "tools" : END;
})
.addEdge("tools", "agent")
.compile({ checkpointer: new MemorySaver() });
const result = await graph.invoke(
{ messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
{ configurable: { thread_id: "session-1" } }
);
Vercel AI SDK is the leanest — one function call, no classes, no ceremony.
Mastra introduces an Agent class with typed tools and output schemas.
LangGraph.js reveals its power: you explicitly define nodes, edges, and conditionalEdges — giving you surgical control over every state transition, with automatic checkpointing baked in.
| Feature | Vercel AI SDK | Mastra | LangGraph.js |
|---|---|---|---|
| Primary Use Case | Chat UIs & streaming | Full-stack agent apps | Stateful orchestration |
| Model Support | 20+ providers | 20+ (via AI SDK) | 10+ (via LangChain) |
| Tool Calling | ✅Zod schemas | ✅Zod schemas | |
| MCP Support | ✅Client | ✅Client + Server | ⚠️Via adapters |
| Persistent Memory | ❌ | ✅Built-in | ✅Checkpointing |
| RAG Pipeline | ❌ | ✅Built-in | ⚠️Via LangChain |
| Workflow Engine | ⚠️Basic | ✅Graph-based | ✅State graphs |
| Human-in-the-Loop | ❌ | ⚠️Manual | ✅interrupt() |
| Observability | ⚠️DIY (OTel) | ✅Mastra Studio | ✅LangSmith |
| Durable Execution | ❌ | ⚠️Early stage | ✅Battle-tested |
| Best Runtime | Serverless / Edge | Node.js Server | Containerized Node.js |
| License | Apache 2.0 | Elastic License v2 | MIT |
❓ Is your primary goal a chat UI or streaming interface?
❓ Do you need durable state that survives server restarts?
❓ Do you want agents, workflows, memory, and RAG in one framework?
Streaming, useChat hooks, model-agnostic tool calling, SSE transport
Agents, workflows, RAG, memory, evals, MCP server, observability — all bundled
Directed state graphs, durable checkpointing, HITL, time-travel debugging
Note: Mastra uses the Vercel AI SDK internally for LLM calls — they are complementary, not competing.
Many production teams use Vercel AI SDK for the frontend (streaming, hooks) and LangGraph.js or Mastra on the backend (orchestration, memory). The frameworks are designed to complement each other, not compete.
The TypeScript AI agent ecosystem in 2026 is no longer playing catch-up with Python. It's offering something Python can't: end-to-end type safety from your model calls to your React components, in a single runtime, a single monorepo, and a single deployment pipeline.
The right choice depends entirely on your architecture:
Whatever you choose, avoid tightly coupling your business logic to framework-specific APIs. Build your tools as pure functions with Zod schemas, and you'll be able to migrate between any of these frameworks with minimal friction.
Durante años, construir agentes de IA en producción significaba escribir en Python, incluso si todo tu stack corría en Node.js. En 2026, el ecosistema de IA en TypeScript finalmente ha madurado. Tres frameworks dominan ahora el panorama, cada uno resolviendo un problema fundamentalmente diferente. Esta guía desglosa Mastra, Vercel AI SDK y LangGraph.js para que puedas elegir el adecuado sin desperdiciar un sprint.
¿Construyendo un chatbot o una interfaz con streaming? → Vercel AI SDK.
¿Construyendo un producto de agentes full-stack? → Mastra.
¿Construyendo flujos de trabajo con estado de misión crítica? → LangGraph.js.
useChat y useCompletion funcionan en React, Vue, Svelte y Angular.inputSchema / outputSchema a través de Zod. Los parámetros de entrada de la herramienta se transmiten automáticamente, permitiendo actualizaciones de la UI en vivo mientras el modelo "piensa".maxSteps y stopWhen te permiten ejecutar bucles de llamadas a herramientas de múltiples turnos sin construir tu propia capa de orquestación.Si tu agente necesita estado duradero, ramificaciones complejas o memoria entre sesiones, el Vercel AI SDK por sí solo no será suficiente. Es una capa de transporte, no un orquestador. Combínalo con Mastra o LangGraph.js para esos casos de uso.
Piensa en Mastra como "Next.js para agentes de IA". Te da configuraciones predeterminadas sensatas, un servidor de desarrollo y un camino claro desde el prototipo a producción — a costa de cierta flexibilidad.
PostgresSaver para producción). Los agentes sobreviven a reinicios del servidor y se reanudan exactamente donde se quedaron.interrupt() que permite a los agentes pausar para obtener aprobación humana y luego reanudarse sin problemas.import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";
const result = await generateText({
model: openai("gpt-4o"),
prompt: "What's the weather in Tokyo?",
tools: {
getWeather: tool({
description: "Get weather for a city",
parameters: z.object({
city: z.string().describe("City name"),
}),
execute: async ({ city }) => {
// Call your weather API here
return { city, temp: "22°C", condition: "Sunny" };
},
}),
},
maxSteps: 5, // Allow multi-turn tool-calling loop
});
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
const getWeather = createTool({
id: "getWeather",
description: "Get weather for a city",
inputSchema: z.object({
city: z.string().describe("City name"),
}),
outputSchema: z.object({
city: z.string(),
temp: z.string(),
condition: z.string(),
}),
execute: async ({ context }) => {
return { city: context.city, temp: "22°C", condition: "Sunny" };
},
});
const weatherAgent = new Agent({
name: "Weather Agent",
instructions: "You answer weather questions accurately.",
model: openai("gpt-4o"),
tools: { getWeather },
});
const response = await weatherAgent.generate(
"What's the weather in Tokyo?"
);
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";
// 1. Define your tool
const getWeather = tool(
async ({ city }) => {
return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
},
{ name: "getWeather", description: "Get weather for a city",
schema: z.object({ city: z.string() }) }
);
// 2. Define state schema
const AgentState = Annotation.Root({
messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});
// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
const response = await model.invoke(state.messages);
return { messages: [response] };
};
// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", new ToolNode([getWeather]))
.addEdge("__start__", "agent")
.addConditionalEdges("agent", (state) => {
const last = state.messages[state.messages.length - 1];
return last.tool_calls?.length ? "tools" : END;
})
.addEdge("tools", "agent")
.compile({ checkpointer: new MemorySaver() });
const result = await graph.invoke(
{ messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
{ configurable: { thread_id: "session-1" } }
);
Vercel AI SDK es el más ligero — una llamada a función, sin clases, sin ceremonia.
Mastra introduce una clase Agent con herramientas tipadas y esquemas de salida.
LangGraph.js revela su poder: defines explícitamente nodes, edges, y conditionalEdges — dándote control quirúrgico sobre cada transición de estado, con creación de checkpoints automáticos integrada.
| Característica | Vercel AI SDK | Mastra | LangGraph.js |
|---|---|---|---|
| Caso de uso principal | UIs de chat y streaming | Apps de agentes full-stack | Orquestación con estado |
| Soporte de modelos | 20+ proveedores | 20+ (vía AI SDK) | 10+ (vía LangChain) |
| Llamado a herramientas | ✅Esquemas Zod | ✅Esquemas Zod | |
| Soporte MCP | ✅Cliente | ✅Cliente + Servidor | ⚠️Vía adaptadores |
| Memoria persistente | ❌ | ✅Integrada | ✅Checkpoints |
| Pipeline RAG | ❌ | ✅Integrada | ⚠️Vía LangChain |
| Motor de flujos de trabajo | ⚠️Básico | ✅Basado en grafos | ✅Grafos de estado |
| Humano en el bucle | ❌ | ⚠️Manual | ✅interrupt() |
| Observabilidad | ⚠️Hágalo usted mismo (OTel) | ✅Mastra Studio | ✅LangSmith |
| Ejecución duradera | ❌ | ⚠️Etapa temprana | ✅Probado en batalla |
| Mejor entorno de ejecución (Runtime) | Serverless / Edge | Servidor Node.js | Node.js en contenedores |
| Licencia | Apache 2.0 | Elastic License v2 | MIT |
❓ ¿Es tu objetivo principal una UI de chat o una interfaz con streaming?
❓ ¿Necesitas un estado duradero que sobreviva a los reinicios del servidor?
❓ ¿Quieres agentes, flujos de trabajo, memoria y RAG en un solo framework?
Streaming, hooks de useChat, llamadas a herramientas independientes del modelo, transporte SSE
Agentes, flujos de trabajo, RAG, memoria, evaluaciones, servidor MCP, observabilidad — todo integrado
Grafos de estado dirigidos, checkpoints duraderos, HITL, depuración con viaje en el tiempo
Nota: Mastra usa el Vercel AI SDK internamente para las llamadas a LLM — son complementarios, no compiten.
Muchos equipos en producción usan Vercel AI SDK para el frontend (streaming, hooks) y LangGraph.js o Mastra en el backend (orquestación, memoria). Los frameworks están diseñados para complementarse, no para competir.
Jahrelang bedeutete die Entwicklung produktionsreifer KI-Agenten, dass man Python schreiben musste – selbst wenn der gesamte Stack auf Node.js lief. Im Jahr 2026 ist das TypeScript-KI-Ökosystem endlich erwachsen geworden. Drei Frameworks dominieren nun die Landschaft, wobei jedes ein grundlegend anderes Problem löst. Dieser Leitfaden analysiert Mastra, Vercel AI SDK und LangGraph.js, damit Sie das richtige auswählen können, ohne einen Sprint zu verschwenden.
Einen Chatbot oder eine Streaming-UI bauen? → Vercel AI SDK.
Ein Full-Stack-Agenten-Produkt entwickeln? → Mastra.
Unternehmenskritische, zustandsbehaftete Workflows erstellen? → LangGraph.js.
useChat- und useCompletion-Hooks funktionieren über React, Vue, Svelte und Angular hinweg.inputSchema / outputSchema via Zod definiert. Tool-Eingabeparameter werden automatisch gestreamt, was Live-UI-Updates ermöglicht, während das Modell "denkt".maxSteps und stopWhen ermöglichen es Ihnen, Multi-Turn-Tool-Calling-Schleifen auszuführen, ohne Ihre eigene Orchestrierungsschicht aufbauen zu müssen.Wenn Ihr Agent einen dauerhaften Zustand (Durable State), komplexe Verzweigungen oder sitzungsübergreifendes Memory benötigt, reicht das Vercel AI SDK allein nicht aus. Es ist eine Transportschicht, kein Orchestrator. Kombinieren Sie es für diese Anwendungsfälle mit Mastra oder LangGraph.js.
Stellen Sie sich Mastra als "Next.js für KI-Agenten" vor. Es bietet Ihnen sinnvolle Standardeinstellungen, einen Dev-Server und einen klaren Weg vom Prototyp in die Produktion — auf Kosten von etwas Flexibilität.
PostgresSaver in der Produktion). Agenten überleben Serverneustarts und setzen genau dort an, wo sie aufgehört haben.interrupt()-Support ermöglicht es Agenten, auf menschliche Freigabe zu warten und dann nahtlos fortzufahren.import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";
const result = await generateText({
model: openai("gpt-4o"),
prompt: "What's the weather in Tokyo?",
tools: {
getWeather: tool({
description: "Get weather for a city",
parameters: z.object({
city: z.string().describe("City name"),
}),
execute: async ({ city }) => {
// Call your weather API here
return { city, temp: "22°C", condition: "Sunny" };
},
}),
},
maxSteps: 5, // Allow multi-turn tool-calling loop
});
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
const getWeather = createTool({
id: "getWeather",
description: "Get weather for a city",
inputSchema: z.object({
city: z.string().describe("City name"),
}),
outputSchema: z.object({
city: z.string(),
temp: z.string(),
condition: z.string(),
}),
execute: async ({ context }) => {
return { city: context.city, temp: "22°C", condition: "Sunny" };
},
});
const weatherAgent = new Agent({
name: "Weather Agent",
instructions: "You answer weather questions accurately.",
model: openai("gpt-4o"),
tools: { getWeather },
});
const response = await weatherAgent.generate(
"What's the weather in Tokyo?"
);
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";
// 1. Define your tool
const getWeather = tool(
async ({ city }) => {
return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
},
{ name: "getWeather", description: "Get weather for a city",
schema: z.object({ city: z.string() }) }
);
// 2. Define state schema
const AgentState = Annotation.Root({
messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});
// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
const response = await model.invoke(state.messages);
return { messages: [response] };
};
// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", new ToolNode([getWeather]))
.addEdge("__start__", "agent")
.addConditionalEdges("agent", (state) => {
const last = state.messages[state.messages.length - 1];
return last.tool_calls?.length ? "tools" : END;
})
.addEdge("tools", "agent")
.compile({ checkpointer: new MemorySaver() });
const result = await graph.invoke(
{ messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
{ configurable: { thread_id: "session-1" } }
);
Das Vercel AI SDK ist am schlanksten — ein Funktionsaufruf, keine Klassen, kein formeller Aufwand.
Mastra führt eine Agent-Klasse mit typisierten Tools und Output-Schemas ein.
LangGraph.js zeigt seine wahre Kraft: Sie definieren explizit nodes, edges und conditionalEdges — was Ihnen chirurgische Kontrolle über jeden Zustandsübergang gibt, inklusive automatischem Checkpointing.
| Feature | Vercel AI SDK | Mastra | LangGraph.js |
|---|---|---|---|
| Primärer Anwendungsfall | Chat-UIs & Streaming | Full-Stack-Agenten-Apps | Zustandsbehaftete Orchestrierung |
| Modell-Support | 20+ Anbieter | 20+ (via AI SDK) | 10+ (via LangChain) |
| Tool-Calling | ✅Zod-Schemas | ✅Zod-Schemas | |
| MCP-Support | ✅Client | ✅Client + Server | ⚠️Via Adapter |
| Persistentes Memory | ❌ | ✅Integriert | ✅Checkpointing |
| RAG-Pipeline | ❌ | ✅Integriert | ⚠️Via LangChain |
| Workflow-Engine | ⚠️Basis | ✅Graphenbasiert | ✅Zustandsgraphen |
| Human-in-the-Loop | ❌ | ⚠️Manuell | ✅interrupt() |
| Observability | ⚠️DIY (OTel) | ✅Mastra Studio | ✅LangSmith |
| Dauerhafte Ausführung | ❌ | ⚠️Frühe Phase | ✅Praxiserprobt |
| Beste Runtime | Serverless / Edge | Node.js Server | Containerisiertes Node.js |
| Lizenz | Apache 2.0 | Elastic License v2 | MIT |
❓ Ist Ihr Hauptziel eine Chat-UI oder eine Streaming-Schnittstelle?
❓ Benötigen Sie dauerhafte Zustände (Durable State), die Serverneustarts überstehen?
❓ Wollen Sie Agenten, Workflows, Memory und RAG in einem einzigen Framework?
Streaming, useChat-Hooks, modellunabhängiges Tool-Calling, SSE-Transport
Agenten, Workflows, RAG, Memory, Evals, MCP-Server, Observability — alles gebündelt
Gerichtete Zustandsgraphen, robustes Checkpointing, HITL, Time-Travel-Debugging
Hinweis: Mastra nutzt intern das Vercel AI SDK für LLM-Aufrufe — sie ergänzen sich, statt zu konkurrieren.
Viele Produktionsteams nutzen das Vercel AI SDK für das Frontend (Streaming, Hooks) und LangGraph.js oder Mastra im Backend (Orchestrierung, Memory). Die Frameworks sind darauf ausgelegt, sich zu ergänzen, nicht zu konkurrieren.
長年、本番用のAIエージェントを構築するとなると、スタック全体がNode.jsで動いていてもPythonを書く必要がありました。2026年、TypeScriptのAIエコシステムはようやく成熟しました。現在、3つのフレームワークが主流となっており、それぞれが根本的に異なる課題を解決しています。このガイドでは、無駄なスプリントを費やすことなく適切なものを選択できるように、Mastra、Vercel AI SDK、そしてLangGraph.jsについて詳しく解説します。
チャットボットやストリーミングUIを構築するなら? → Vercel AI SDK。
フルスタックのエージェントプロダクトを構築するなら? → Mastra。
ミッションクリティカルでステートフルなワークフローを構築するなら? → LangGraph.js。
useChatやuseCompletionフックは、React、Vue、Svelte、Angularで機能します。inputSchema / outputSchemaで定義されます。ツールの入力パラメータは自動的にストリーミングされ、モデルが「思考」している間にライブでUIを更新できます。maxStepsとstopWhenコントロールを使用すると、独自のオーケストレーションレイヤーを構築することなく、複数ターンのツール呼び出しループを実行できます。エージェントに永続的なステート、複雑な分岐、またはセッション間のメモリが必要な場合、Vercel AI SDKだけでは不十分です。これはトランスポートレイヤーであり、オーケストレータではありません。それらのユースケースには、MastraまたはLangGraph.jsと組み合わせて使用してください。
Mastraを「AIエージェント向けのNext.js」と考えてください。いくつかの柔軟性を犠牲にする代わりに、理にかなったデフォルト設定、開発サーバー、プロトタイプから本番環境への明確な道筋を提供します。
PostgresSaver)にチェックポイントとして保存されます。エージェントはサーバーの再起動を生き延び、中断した場所から正確に再開します。interrupt()サポートにより、エージェントは人間の承認を待って一時停止し、その後シームレスに再開できます。import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";
const result = await generateText({
model: openai("gpt-4o"),
prompt: "What's the weather in Tokyo?",
tools: {
getWeather: tool({
description: "Get weather for a city",
parameters: z.object({
city: z.string().describe("City name"),
}),
execute: async ({ city }) => {
// Call your weather API here
return { city, temp: "22°C", condition: "Sunny" };
},
}),
},
maxSteps: 5, // Allow multi-turn tool-calling loop
});
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
const getWeather = createTool({
id: "getWeather",
description: "Get weather for a city",
inputSchema: z.object({
city: z.string().describe("City name"),
}),
outputSchema: z.object({
city: z.string(),
temp: z.string(),
condition: z.string(),
}),
execute: async ({ context }) => {
return { city: context.city, temp: "22°C", condition: "Sunny" };
},
});
const weatherAgent = new Agent({
name: "Weather Agent",
instructions: "You answer weather questions accurately.",
model: openai("gpt-4o"),
tools: { getWeather },
});
const response = await weatherAgent.generate(
"What's the weather in Tokyo?"
);
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";
// 1. Define your tool
const getWeather = tool(
async ({ city }) => {
return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
},
{ name: "getWeather", description: "Get weather for a city",
schema: z.object({ city: z.string() }) }
);
// 2. Define state schema
const AgentState = Annotation.Root({
messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});
// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
const response = await model.invoke(state.messages);
return { messages: [response] };
};
// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", new ToolNode([getWeather]))
.addEdge("__start__", "agent")
.addConditionalEdges("agent", (state) => {
const last = state.messages[state.messages.length - 1];
return last.tool_calls?.length ? "tools" : END;
})
.addEdge("tools", "agent")
.compile({ checkpointer: new MemorySaver() });
const result = await graph.invoke(
{ messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
{ configurable: { thread_id: "session-1" } }
);
Vercel AI SDKは最もシンプルです。単一の関数呼び出しで、クラスや面倒な手続きはありません。
Mastraは、型付けされたツールと出力スキーマを持つAgentクラスを導入しています。
LangGraph.jsはその威力を発揮します。nodes、edges、そしてconditionalEdgesを明示的に定義することで、すべてのステート遷移を外科手術のように制御でき、自動チェックポイント機能も組み込まれています。
| 機能 | Vercel AI SDK | Mastra | LangGraph.js |
|---|---|---|---|
| 主なユースケース | チャットUI & ストリーミング | フルスタックのエージェントアプリ | ステートフルなオーケストレーション |
| モデルサポート | 20以上のプロバイダー | 20以上 (AI SDK経由) | 10以上 (LangChain経由) |
| ツール呼び出し | ✅Zodスキーマ | ✅Zodスキーマ | |
| MCPサポート | ✅クライアント | ✅クライアント + サーバー | ⚠️アダプタ経由 |
| 永続的メモリ | ❌ | ✅組み込み | ✅チェックポイント |
| RAGパイプライン | ❌ | ✅組み込み | ⚠️LangChain経由 |
| ワークフローエンジン | ⚠️基本的 | ✅グラフベース | ✅ステートグラフ |
| ヒューマン・イン・ザ・ループ | ❌ | ⚠️手動 | ✅interrupt() |
| オブザーバビリティ | ⚠️DIY (OTel) | ✅Mastra Studio | ✅LangSmith |
| 永続的な実行 | ❌ | ⚠️初期段階 | ✅実戦テスト済み |
| 最適なランタイム | サーバーレス / エッジ | Node.js サーバー | コンテナ化されたNode.js |
| ライセンス | Apache 2.0 | Elastic License v2 | MIT |
❓ 主な目的はチャットUIやストリーミングインターフェースですか?
❓ サーバーの再起動を生き延びる永続的なステートが必要ですか?
❓ エージェント、ワークフロー、メモリ、RAGを1つのフレームワークでまとめたいですか?
ストリーミング、useChatフック、モデル非依存のツール呼び出し、SSEトランスポート
エージェント、ワークフロー、RAG、メモリ、評価、MCPサーバー、オブザーバビリティ — すべてをバンドル
有向ステートグラフ、永続的なチェックポイント、HITL、タイムトラベルデバッグ
注: MastraはLLM呼び出しにおいて内部的にVercel AI SDKを使用します。両者は競合するものではなく、補完関係にあります。
多くのプロダクションチームは、フロントエンドにはVercel AI SDK(ストリーミング、フック)を、バックエンドにはLangGraph.jsまたはMastra(オーケストレーション、メモリ)を使用しています。これらのフレームワークは互いに競合するのではなく、補完し合うように設計されています。