Build your first Mastra agent in TypeScript. Write instructions, pick a model, register the agent, and get replies with generate() and stream().
In this lesson, you will configure an AI agent using the Mastra Agent class, register it on your Mastra server, and run text generation and streaming responses in TypeScript.
Previous lesson: Setting Up Your First Mastra Project | Next lesson: Mastra Tools: Giving Your Agent Tools
An agent is an autonomous system powered by a large language model. You give it an identity, behavioral rules, and a specific model backend. It receives user prompts and generates relevant replies.
Mastra provides the Agent class inside @mastra/core/agent. When you construct an agent, you define four core properties:
id: A unique string identifier used internally by Mastra systems and routes.name: A human-readable display label for the agent in user interfaces and logs.instructions: The system prompt. This text sets boundaries, tone, and operational guidelines for the model.model: A provider-qualified model string that tells Mastra which LLM to invoke.Think of an agent like a newly hired support representative who has read the employee handbook but has not yet received access to internal database tools.
Model strings in Mastra always use the format provider/model with a forward slash. Mastra routes requests through its unified provider layer, so you do not need separate provider client libraries. For this course, you will use openai/gpt-5-mini.
Common Mistake: Writing model strings with colons such as openai:gpt-5-mini or using raw SDK wrappers directly. Always pass the string 'openai/gpt-5-mini'.
Open your code editor in the project created in the previous lesson. Create a new file at src/mastra/agents/support-agent.ts.
Add the following TypeScript code:
tsCopy
The instructions property serves as the persistent system prompt. Every time Mastra sends a user prompt to the provider API, it prepends these instructions to guide the model.
Quick Insight: Keeping instructions concise and prescriptive helps smaller, fast models like openai/gpt-5-mini follow output rules reliably without getting confused.
Creating an agent instance does not automatically make it accessible to your application server or the Mastra Studio interface. You must register it inside your main entry point file.
Open src/mastra/index.ts and import your new supportAgent:
tsCopy
The key you provide in the agents object becomes the reference handle for retrieving the agent programmatically.
You can retrieve registered agents anywhere in your backend using two methods:
mastra.getAgent('supportAgent') retrieves the agent by the key used in the registration object.mastra.getAgentById('support-agent') retrieves the agent by its internal id property.Pro Tip: Use mastra.getAgent('supportAgent') throughout your application code so TypeScript can offer autocomplete based on your export names.
To get a complete response from the agent at once, use the generate() method. This method waits until the model finishes generating the full text and then returns an execution result object.
Create a test script at src/test-generate.ts to execute a prompt from the command line:
tsCopy
Run this file with tsx:
bashCopy
The --env-file=.env flag loads your API key, as covered in the previous lesson.
The response object contains metadata about the call along with response.text, which holds the raw string generated by the model.
What happens if the model encounters an invalid API key? The generate() promise rejects with an authentication error from the provider. Ensure your OPENAI_API_KEY is present in your .env file before executing scripts.
Waiting for the complete text can create noticeable delay for end users. The stream() method sends text chunks back as the model outputs them, allowing you to display replies in real time.
Create another test script at src/test-stream.ts:
tsCopy
The property streamResponse.textStream is an asynchronous iterable. Each iteration yields an incoming token slice as a string.
| Method | Return Type | Primary Use Case |
|---|---|---|
| generate | Promise resolving to response object | Background batch jobs, classification, structured data |
| stream | Promise resolving to stream object | Live chat interfaces, real-time UI text rendering |
Quick Challenge: Open Mastra Studio by running npm run dev and navigate to http://localhost:4111. Select Support Agent in the left sidebar and verify that it responds to customer greetings directly in the browser interface.
Modify src/mastra/agents/support-agent.ts to switch the underlying model to Anthropic or Google:
tsCopy
Add your ANTHROPIC_API_KEY to .env and rerun npx tsx --env-file=.env src/test-stream.ts. Notice that the code does not require changes to your method calls or handling logic. Mastra normalizes the streaming interface across all supported model providers. Switch it back to 'openai/gpt-5-mini' when you finish testing.
In the next lesson, Mastra Tools: Giving Your Agent Tools, you will build an order status lookup tool using Zod schemas and attach it to your support agent.
Was this lesson helpful?