Skip to content

Commit 83648ef

Browse files
committed
Updated readme and index.js
1 parent ff17943 commit 83648ef

File tree

4 files changed

+75
-199
lines changed

4 files changed

+75
-199
lines changed

mastra-agents/.env.example

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# OpenAI API key for the agent functionality
2+
OPENAI_API_KEY=<your-openai-api-key>
3+
4+
# Trigger.dev environment variables
5+
TRIGGER_API_URL=https://api.trigger.dev
6+
TRIGGER_SECRET_KEY=<your-secret-key>

mastra-agents/README.md

Lines changed: 50 additions & 194 deletions
Original file line numberDiff line numberDiff line change
@@ -1,140 +1,27 @@
1-
# What Should I Wear Today? - Mastra Agents
1+
# Mastra agents + Trigger.dev real-world example project:
22

3-
A weather-aware clothing advisor powered by Mastra agents and Trigger.dev. This system provides personalized clothing recommendations based on real-time weather conditions.
3+
> **ℹ️ Note:** This is a v4 project. If you are using v3 and want to upgrade, please refer to our [v4 upgrade guide](https://trigger.dev/docs/v4-upgrade-guide).
44
5-
## 🌟 Features
5+
Enter a city and activity, and get a clothing recommendation generated based on the weather.
66

7-
- **Weather-Aware Clothing Advice**: Get clothing recommendations based on current temperature, rain chance, and wind speed
8-
- **Intelligent Memory System**: Uses Mastra's working memory to efficiently share weather data between agents
9-
- **Activity-Specific Recommendations**: Tailored advice for different activities (walking, running, etc.)
10-
- **Fast Response**: Optimized for quick responses (~3 seconds)
11-
- **Simple Input**: Just provide a city and optional activity
12-
- **Natural Language Output**: Returns human-readable clothing advice paragraph
7+
By combining Mastra's persistent memory system and agent orchestration with Trigger.dev's durable task execution, retries and observability, you get production-ready AI workflows that survive failures, scale automatically, and maintain context across long-running operations.
138

14-
## 🏗️ Architecture
9+
## Tech stack
1510

16-
### Agents
11+
- [Node.js](https://nodejs.org) runtime environment
12+
- [Mastra](https://mastra.ai) for AI agent orchestration and memory management
13+
- [Trigger.dev](https://trigger.dev) for task orchestration, batching, and observability
14+
- [OpenAI GPT-4](https://openai.com) for natural language processing
15+
- [Open-Meteo API](https://open-meteo.com) for weather data (no API key required)
16+
- [Zod](https://zod.dev) for schema validation and type safety
1717

18-
- **Weather Analyst** (`weather-analyst.ts`) - Gets weather data and stores essentials in memory
19-
- **Clothing Advisor** (`clothing-advisor.ts`) - Reads weather data from memory and provides clothing recommendations
18+
## Featured patterns
2019

21-
### Tasks
22-
23-
- **`weather-data`** - Gets weather data and stores temperature, rain chance, and wind speed in memory
24-
- **`clothing-advice`** - Reads weather data from memory and generates clothing recommendations
25-
- **`what-should-i-wear-today`** - Main task that orchestrates both subtasks with shared memory
26-
27-
### Memory System
28-
29-
- **Simplified Schema** (`weather-data.ts`) - Lightweight weather data structure (4 fields only)
30-
- **Working Memory** - Stores essential weather data between task executions
31-
- **Thread-Scoped** - Data shared within same execution thread
32-
33-
## 🚀 Getting Started
34-
35-
### Prerequisites
36-
37-
- Node.js 18+
38-
- OpenAI API key
39-
- Trigger.dev account
40-
41-
### Installation
42-
43-
1. **Clone and install dependencies:**
44-
45-
```bash
46-
git clone <repo-url>
47-
cd mastra-agents
48-
npm install
49-
```
50-
51-
2. **Set up environment variables:**
52-
53-
```bash
54-
cp .env.example .env
55-
# Add your OpenAI API key to .env
56-
OPENAI_API_KEY=your_openai_api_key_here
57-
```
58-
59-
3. **Install Trigger.dev CLI:**
60-
61-
```bash
62-
npm install -g @trigger.dev/cli@v4-beta
63-
```
64-
65-
4. **Start the development server:**
66-
67-
```bash
68-
npx trigger.dev@v4-beta dev
69-
```
70-
71-
## 🎯 Usage
72-
73-
### Main Task: What Should I Wear Today?
74-
75-
Get clothing recommendations based on weather:
76-
77-
```bash
78-
npx trigger.dev@latest dev --trigger what-should-i-wear-today --payload '{"city": "London", "activity": "walking"}'
79-
```
80-
81-
**Payload:**
82-
83-
- `city` (required): City name (e.g., "London", "New York", "Tokyo")
84-
- `activity` (optional): Activity type (defaults to "walking")
85-
86-
**How it works:**
87-
88-
1. Weather analyst fetches current weather data and stores temperature, rain chance, and wind speed in memory
89-
2. Clothing advisor reads from memory and generates clothing recommendations
90-
3. No duplicate API calls - efficient memory-based task chaining
91-
92-
### Individual Tasks
93-
94-
**Weather Data Only:**
95-
96-
```bash
97-
npx trigger.dev@latest dev --trigger weather-data --payload '{"city": "Paris"}'
98-
```
99-
100-
**Clothing Advice Only:**
101-
102-
```bash
103-
npx trigger.dev@latest dev --trigger clothing-advice --payload '{"city": "Tokyo", "activity": "running", "threadId": "run_abc123"}'
104-
```
105-
106-
### Sample Output
107-
108-
The main task returns a simple paragraph with clothing advice:
109-
110-
```
111-
"For walking in London you should wear a light t-shirt or short-sleeved shirt with comfortable pants or shorts, as the temperature is warm at 25°C. With only a 3% chance of rain, you won't need any rain protection, and the light wind at 8 km/h means you can stick to breathable, comfortable clothing for your walk."
112-
```
113-
114-
## 🧠 Memory System
115-
116-
The system uses Mastra's working memory to share simplified weather data between agents:
117-
118-
```typescript
119-
// Weather data stored in memory
120-
{
121-
location: "London",
122-
temperature: 24.8, // Current temperature in Celsius
123-
rainChance: 3, // Rain chance percentage (0-100)
124-
windSpeed: 8.3 // Wind speed in km/h
125-
}
126-
```
127-
128-
This simplified schema focuses on the essential data needed for clothing decisions, making the system faster and more efficient.
129-
130-
## 🛠️ Technical Stack
131-
132-
- **Mastra**: Agent orchestration and memory management
133-
- **Trigger.dev v4**: Task execution and monitoring
134-
- **OpenAI GPT-4**: Natural language processing
135-
- **Open-Meteo API**: Weather data (no API key required)
136-
- **LibSQL**: Local database for memory storage
137-
- **Zod**: Type-safe schema validation
20+
- **[Agent Memory Sharing](src/trigger/weather-task.ts)**: Efficient data sharing between agents using Mastra's working memory system
21+
- **[Task Orchestration](src/trigger/weather-task.ts)**: Multi-step workflows with `triggerAndWait` for sequential agent execution
22+
- **[Custom Tools](src/mastra/tools/weather-tool.ts)**: External API integration with structured output validation
23+
- **[Agent Specialization](src/mastra/agents/)**: Purpose-built agents with specific roles and instructions
24+
- **[Schema Optimization](src/mastra/schemas/weather-data.ts)**: Lightweight data structures for performance
13825

13926
## 📁 Project Structure
14027

@@ -144,92 +31,61 @@ src/
14431
│ ├── agents/
14532
│ │ ├── weather-analyst.ts # Weather data collection
14633
│ │ ├── clothing-advisor.ts # Clothing recommendations
147-
│ │ └── day-planner.ts # (Legacy) Activity planning
14834
│ ├── tools/
14935
│ │ └── weather-tool.ts # Enhanced weather API tool
15036
│ ├── schemas/
151-
│ │ └── weather-data.ts # Simplified weather schema
37+
│ │ └── weather-data.ts # Weather schema
15238
│ └── index.ts # Mastra configuration
15339
├── trigger/
15440
│ └── weather-task.ts # Trigger.dev tasks
15541
└── test-weather-agent.ts # Local testing
15642
```
15743

158-
## 🎨 Customization
44+
## Relevant code
15945

160-
### Adding New Agents
46+
- [src/trigger/weather-task.ts](src/trigger/weather-task.ts) - Multi-step task orchestration with `triggerAndWait` for sequential agent execution and shared memory context
47+
- [src/mastra/agents/weather-analyst.ts](src/mastra/agents/weather-analyst.ts) - Specialized agent for weather data collection with external API integration and memory storage
48+
- [src/mastra/agents/clothing-advisor.ts](src/mastra/agents/clothing-advisor.ts) - Purpose-built agent that reads from working memory and generates natural language responses
49+
- [src/mastra/tools/weather-tool.ts](src/mastra/tools/weather-tool.ts) - Custom Mastra tool with Zod validation for external API calls and error handling
50+
- [src/mastra/schemas/weather-data.ts](src/mastra/schemas/weather-data.ts) - Optimized Zod schema for efficient memory storage and type safety
51+
- [src/mastra/index.ts](src/mastra/index.ts) - Mastra configuration with LibSQL storage and agent registration
16152

162-
1. Create agent file in `src/mastra/agents/`
163-
2. Add memory configuration if needed
164-
3. Register in `src/mastra/index.ts`
53+
## Getting started
16554

166-
### Modifying Weather Schema
55+
1. After cloning the repo, run `npm install` to install the dependencies.
56+
2. Set up your environment variables (see `.env.example`)
57+
3. If you haven't already, sign up for a free Trigger.dev account [here](https://cloud.trigger.dev/login) and create a new project.
58+
4. Copy the project ref from the Trigger.dev dashboard and add it to the `trigger.config.ts` file.
59+
5. In your terminal, run the Trigger.dev dev CLI command with `npx trigger.dev@latest dev`.
16760

168-
Update `src/mastra/schemas/weather-data.ts` to change the weather data structure. The current schema is optimized for speed with just 4 fields.
61+
Now you should be able to visit your Trigger.dev dashboard and test any of the agent tasks with the example payloads provided in each task file.
16962

170-
### Adding New Activities
63+
## Testing locally
17164

172-
The system supports different activities. You can extend the clothing advisor agent to provide more specific recommendations for activities like:
65+
Use the Trigger.dev dashboard to test each task:
17366

174-
- Running
175-
- Cycling
176-
- Hiking
177-
- Formal events
178-
- Outdoor work
67+
### Example payload
17968

180-
### Adding New Tasks
181-
182-
Create new tasks in `src/trigger/weather-task.ts` using the existing agents.
183-
184-
## 📊 Features Comparison
185-
186-
| Feature | Before (Day Planner) | After (Clothing Advisor) |
187-
| -------------------- | ---------------------- | ------------------------ |
188-
| Weather API Calls | 2+ per execution | 1 per execution |
189-
| Data Schema | 40+ fields complex | 4 fields simplified |
190-
| Response Time | 20+ seconds | ~3 seconds |
191-
| Output Format | Complex JSON structure | Simple text paragraph |
192-
| Memory Usage | Full weather data | Essential data only |
193-
| Agent Specialization | Generic agents | Purpose-built agents |
194-
195-
## 🔄 Task Flow
196-
197-
```mermaid
198-
graph TD
199-
A[What Should I Wear Today] --> B[Weather Data Task]
200-
B --> C[Weather Analyst Agent]
201-
C --> D[Weather Tool - API Call]
202-
D --> E[Store in Memory:<br/>temp, rain, wind]
203-
E --> F[Clothing Advice Task]
204-
F --> G[Clothing Advisor Agent]
205-
G --> H[Read from Memory]
206-
H --> I[Generate Clothing Advice]
207-
I --> J[Return Advice Paragraph]
69+
```json
70+
{ "city": "New York", "activity": "walking" }
20871
```
20972

210-
## 📈 Performance Benefits
211-
212-
- **Single API call** - Memory system eliminates duplicate weather requests
213-
- **~3 second responses** - Optimized for speed with simplified data schema
214-
- **Efficient memory usage** - Only 4 essential fields stored (vs 40+ in full schema)
215-
- **Better reliability** - Memory persistence across task failures
216-
- **Cleaner architecture** - Specialized agents with clear responsibilities
73+
## Deployment
21774

218-
## 🤝 Contributing
75+
This project uses LibSQL as a local database for development, but **LibSQL doesn't work in serverless environments**. For production deployment, you'll need to switch to a serverless-compatible storage option:
21976

220-
1. Fork the repository
221-
2. Create a feature branch
222-
3. Make your changes
223-
4. Add tests if applicable
224-
5. Submit a pull request
77+
- **Turso** (LibSQL-compatible): Set `TURSO_DATABASE_URL` and `TURSO_AUTH_TOKEN` in your environment variables. Create an account and database [here](https://turso.tech/signup).
78+
- **PostgreSQL** (Supabase): Set `DATABASE_URL` in your environment variables. Create an account and database [here](https://supabase.com/dashboard/sign-in).
79+
- **No persistence**: Remove storage from mastra config entirely.
22580

226-
## 📄 License
81+
Update `src/mastra/index.ts` with your chosen storage provider before deploying.
22782

228-
MIT License - see LICENSE file for details
83+
## Learn More
22984

230-
## 🙏 Acknowledgments
85+
To learn more about the technologies used in this project, check out the following resources:
23186

232-
- [Mastra](https://mastra.ai) for the agent framework
233-
- [Trigger.dev](https://trigger.dev) for task orchestration
234-
- [Open-Meteo](https://open-meteo.com) for weather data
235-
- [OpenAI](https://openai.com) for language models
87+
- [Mastra docs](https://docs.mastra.ai) - learn about AI agent orchestration and memory management
88+
- [Mastra working memory](https://docs.mastra.ai/memory/working-memory) - learn about efficient data sharing between agents
89+
- [Trigger.dev docs](https://trigger.dev/docs) - learn about Trigger.dev and its features
90+
- [Trigger.dev task orchestration](https://trigger.dev/docs/triggering#triggering-from-a-task) - learn about sequential task execution with `triggerAndWait`
91+
- [Multi-agent workflow patterns](https://docs.mastra.ai/agents/multi-agent-workflows) - advanced agent collaboration examples

mastra-agents/src/mastra/index.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,27 @@ import { LibSQLStore } from "@mastra/libsql";
33
import { weatherAnalyst } from "./agents/weather-analyst";
44
import { clothingAdvisorAgent } from "./agents/clothing-advisor";
55

6-
export const mastra: Mastra = new Mastra({
7-
storage: new LibSQLStore({
6+
// Storage configuration - for production, switch to serverless-compatible storage
7+
// See README.md deployment section for options (Turso, PostgreSQL, etc.)
8+
function createStorage() {
9+
// Turso (serverless LibSQL)
10+
if (process.env.TURSO_DATABASE_URL) {
11+
return new LibSQLStore({
12+
url: process.env.TURSO_DATABASE_URL,
13+
authToken: process.env.TURSO_AUTH_TOKEN,
14+
});
15+
}
16+
17+
// Local development (won't work in serverless)
18+
return new LibSQLStore({
819
url: "file:./mastra.db",
9-
}),
20+
});
21+
}
22+
23+
export const mastra: Mastra = new Mastra({
24+
storage: createStorage(),
1025
agents: {
1126
weatherAnalyst,
12-
1327
clothingAdvisorAgent,
1428
},
1529
});

mastra-agents/trigger.config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { defineConfig } from "@trigger.dev/sdk/v3";
22

33
export default defineConfig({
4-
project: "proj_xjminyoyogxbrfipkrkt",
4+
project: "proj_xjminyoyogxbrfipkrkt", // replace with your project ref
55
runtime: "node",
66
logLevel: "log",
77
// The max compute seconds a task is allowed to run. If the task run exceeds this duration, it will be stopped.

0 commit comments

Comments
 (0)