import { Callout, Steps, Tabs } from "nextra/components";

## Introduction

Mastra is an opinionated Typescript framework that helps you build AI applications and features quickly. It gives you the set of primitives you need: workflows, agents, RAG, integrations, syncs and evals. You can run Mastra on your local machine, or deploy to a serverless cloud.

The main Mastra features are:

| Features                                                       | Description                                                                                                                                                                                                                                                                              |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [LLM Models](../guide/how-to/00-llm-models.mdx)                | Mastra supports a variety of LLM providers, including OpenAI, Anthropic, Google Gemini. You can choose the specific model and provider, choose system and user prompts, and decide whether to stream the response.                                                                       |
| [Agents](../guide/how-to/01-creating-agents)                   | Agents are systems where the language model chooses a sequence of actions. In Mastra, agents provide LLM models with tools, workflows, and synced data. Agents can call your own functions or APIs of third-party integrations and access knowledge bases you build.                     |
| [Tools](../guide/how-to/02-adding-tools)                       | Tools are typed functions that can be executed by agents or workflows, with built-in integration access and parameter validation. Each tool has a schema that defines its inputs, an executor function that implements its logic, and access to configured integrations.                 |
| [Workflows](../guide/how-to/03-building-workflows)             | Workflows are durable graph-based state machines. They have loops, branching, wait for human input, embed other workflows, do error handling, retries, parsing and so on. They can be built in code or with a visual editor. Each step in a workflow has built-in OpenTelemetry tracing. |
| [RAG](../guide/how-to/04-knowledge-sources)                    | Retrieval-augemented generation (RAG) lets you construct a knowledge base for agents. RAG is an ETL pipeline with specific querying techniques, including chunking, embedding, and vector search.                                                                                        |
| [Integrations & Syncs](../guide/how-to/06-adding-integrations) | In Mastra, syncs are async functions that can be deployed as background tasks across different execution environments. Integrations are auto-generated, type-safe API clients for third-party services that can be used as tools for agents or steps in workflows.                       |
| [Evals](../guide/how-to/08-running-evals)                      | Evals are automated tests that evaluate LLM outputs using model-graded, rule-based, and statistical methods. Each eval returns a normalized score between 0-1 that can be logged and compared. Evals can be customized with your own prompts and scoring functions.                      |

## Quick Start

### Prerequisites

- [Node.js v20.0+](https://nodejs.org/)

<Steps>

### Get an LLM provider API key

If you don't have an API key for an LLM provider, you can get one from the following services:

- [OpenAI](https://platform.openai.com/)
- [Anthropic](https://console.anthropic.com/settings/keys)
- [Google Gemini](https://ai.google.dev/gemini-api/docs)

If you don't have an account with these providers, you can sign up and get an API key. OpenAI and Anthropic require a credit card to get an API key. Gemini does not and has a generous free tier for its API.

### Create a new project

Create a project directory and navigate into it:

```bash copy
mkdir hello-mastra
cd hello-mastra
```

Next, initialize a TypeScript project using npm:

```bash copy npm2yarn
npm init -y
npm install zod typescript tsx @types/node --save-dev
npx tsc --init
```

Add an index file in a `src` directory

```bash copy
mkdir src
touch src/index.ts
```

### Install Mastra dependencies

Install the `cli`, `mastra` core and initialize starter files.
The core package provides the `agents` and `workflows` classess we'll be using.

```bash npm2yarn copy
npm i -g mastra
npm install @mastra/core@alpha
```

### Initialize agents

```bash copy
mastra init
```

This `init` command creates two sample agents and wires them
up to the Mastra `class`

```ts copy filename="src/mastra/index.ts" {3,6} showLineNumbers
import { Mastra, createLogger } from "@mastra/core";

import { agentOne, agentTwo } from "./agents/agent";

export const mastra = new Mastra({
  agents: [agentOne, agentTwo],
  logger: createLogger({
    type: "CONSOLE",
    level: "INFO",
  }),
});
```

Update agent one to the following code below:

```ts copy filename="src/mastra/agents/agent.ts" {2-6} showLineNumbers
export const agentOne = new Agent({
  name: "cat-one",
  instructions:
    "You are a feline expert with comprehensive knowledge of all cat species, from domestic breeds to wild big cats. As a lifelong cat specialist, you understand their behavior, biology, social structures, and evolutionary history in great depth.",
  model: {
    provider: "OPEN_AI",
    name: "gpt-4o",
    toolChoice: "auto",
  },
});
// rest of code
```

### Execute the agent

Now, we will import and run the Mastra agent:

```ts filename="src/index.ts" showLineNumbers copy {1,4,20-21}
import { mastra } from "./mastra";

const main = async () => {
  const agentCat = mastra.getAgent("cat-one");

  try {
    const result = await agentCat.textObject({
      messages: ["What is the most popular cat species?"],
      structuredOutput: {
        catSpecies: {
          type: "object",
          items: {
            species: {
              type: "string",
            },
          },
        },
      },
    });
    const {
      catSpecies: { species },
    } = (await result.toJsonResponse().json()) as {
      catSpecies: { species: string };
    };
    console.log(species);
  } catch (err) {
    console.error(err);
  }
};
main();
```

In your terminal, run:

```bash copy filename="terminal"
OPENAI_API_KEY=<your-openai-api-key> npx tsx src/index.ts
```

</Steps>

With this, you have created your very first agent with Mastra. We've extended agent one to use Mastra's `workflows`. You can check out the example [here](https://github.com/mastra-ai/mastra/tree/main/examples/quick-start)

### Using REST endpoints

Mastra provides you with api endpoints to communicate with your agent. Let's see how below:

<Steps>
### Add your API key

Create a `.env` file and add your provider api key

```bash filename=".env"
OPENAI_API_KEY=<your-openai-api-key>
```

If you're using Anthropic, set the `ANTHROPIC_API_KEY`. If you're using Gemini, set the `GOOGLE_GENERATIVE_AI_API_KEY`.

### Run mastra serve

```bash copy
mastra serve
```

Mastra serve creates the following POST endpoints:

1. `localhost:4111/agent/cat-one/text` for the agent

`agentId` is the name of the agent.

### Test out the endpoint

**Agent**

<Tabs items={['curl', 'fetch']}>
  <Tabs.Tab>
```bash copy
curl -X POST http://localhost:4111/agent/cat-one/text \
-H "Content-Type: application/json" \
-d '{"messages": ["What is the most popular cat by adoption rate?"]}'
```
  </Tabs.Tab>
  <Tabs.Tab>
```js copy
fetch(`http://localhost:4111/agent/cat-one/text`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    messages: ["What is the most popular cat by adoption rate?"],
  }),
})
.then((data) => {
  console.log("Response:", data);
})
.catch((error) => {
  console.error("Error:", error);
});
```
  </Tabs.Tab>
</Tabs>
</Steps>

### That's it 🎉

You have just setup Mastra. Mastra also provides you with an instance that can be used in your `node` based project.
You aren't limited to just using the `REST` endpoints to communicate with your agents.
