Salta ai contenuti

Mastra - Cheatsheet del Framework di Agente AI TypeScript

Mastra - Cheatsheet del Framework di Agente AI TypeScript

Mastra è un framework open-source TypeScript per agenti AI e workflow, costruito dal team dietro Gatsby. Mentre la maggior parte dei framework di agenti sono Python-first, Mastra punta all”ecosistema JavaScript/TypeScript con piena type safety: agenti tipizzati con strumenti e memoria, workflow durevoli espressi come grafi con branching e suspend/resume, primitive RAG, valutazioni integrate e un playground di sviluppo locale per iterare gli agenti nel browser.

Installation

MethodCommand
Create a projectnpm create mastra@latest
Add to existingnpm install @mastra/core
Dev servernpm run dev (playground at localhost:4111)
Model providernpm install @ai-sdk/openai (uses Vercel AI SDK)
Verifyopen the playground

Defining an Agent

import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";

export const supportAgent = new Agent({
  name: "support",
  instructions: "You are a concise support agent. Cite docs when possible.",
  model: openai("gpt-4o"),
  tools: { searchDocs },
});

const result = await supportAgent.generate("How do I rotate my API key?");
console.log(result.text);
MethodDoes
.generate(input)Esegui una volta e restituisci il risultato
.stream(input)Trasmetti token/step
toolsStrumenti tipizzati che l”agente può chiamare
memoryMemoria conversazionale persistente

Tools

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

export const searchDocs = createTool({
  id: "search-docs",
  description: "Search the product documentation",
  inputSchema: z.object({ query: z.string() }),
  outputSchema: z.object({ results: z.array(z.string()) }),
  execute: async ({ context }) => {
    return { results: await search(context.query) };
  },
});

Gli schemi Zod forniscono type safety end-to-end — le chiamate di strumenti dell”agente sono validate e tipizzate su entrambi i lati.

Workflows (Durable Graphs)

import { createWorkflow, createStep } from "@mastra/core/workflows";

const fetchData = createStep({ id: "fetch", execute: async () => ({ ... }) });
const analyze   = createStep({ id: "analyze", execute: async ({ inputData }) => ({ ... }) });

export const pipeline = createWorkflow({ id: "pipeline" })
  .then(fetchData)
  .then(analyze)
  .commit();
FeaturePurpose
.then()Step sequenziali
.branch()Percorsi condizionali
.parallel()Step concorrenti
.dowhile() / .foreach()Loop sui dati
Suspend/resumePausa per input umano, riprendi dopo
Durable executionSopravvive ai riavvii

Memory

TypeUse
Conversation historyTurni recenti in contesto
Semantic recallRicerca vettoriale su messaggi passati
Working memoryFatti persistenti sull”utente
Storage adaptersLibSQL, Postgres, Upstash

RAG Primitives

PieceProvides
Document chunkingDividi i documenti con strategie configurabili
EmbeddingsVia i provider dell”AI SDK
Vector storespgvector, Pinecone, Qdrant, Chroma
Retrieval toolCollega il recupero in un agente come strumento

Evals & Observability

CapabilityNote
Built-in evalsRilevanza della risposta, fedeltà, tossicità, bias
Custom scorersDefinisci le tue metriche
TracingTrace compatibili con OpenTelemetry
PlaygroundIspeziona esecuzioni dell”agente, strumenti e memoria localmente

Deployment

TargetNote
Node servermastra build produce un server distribuibile
Vercel / Cloudflare / NetlifyDistribuitori ufficiali
ServerlessWorkflow progettati per host stateless

Mastra vs Other Agent Frameworks

AspectMastraLangGraphCrewAI
LanguageTypeScriptPythonPython
WorkflowsGrafo durevole + suspend/resumeGrafo con statoCrew basati su ruoli
Type safetyForte (Zod end-to-end)Tipizzazione PythonTipizzazione Python
Best forTeam TS/JS, app webAgenti con stato complessiRoleplay multi-agente

L”omologo TypeScript di LangGraph; confronta con CrewAI e AutoGen per Python.

Resources