create-mastra 0.0.0-storage-20250225005900

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ import { Step, Workflow } from '@mastra/core';
2
+ import { z } from 'zod';
3
+
4
+ const fetchWeather = new Step({
5
+ id: 'fetch-weather',
6
+ description: 'Fetches weather forecast for a given city',
7
+ inputSchema: z.object({
8
+ city: z.string().describe('The city to get the weather for'),
9
+ }),
10
+ execute: async ({ context }) => {
11
+ const triggerData = context.machineContext?.getStepPayload<{ city: string }>('trigger');
12
+
13
+ if (!triggerData) {
14
+ throw new Error('Trigger data not found');
15
+ }
16
+
17
+ const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(triggerData.city)}&count=1`;
18
+ const geocodingResponse = await fetch(geocodingUrl);
19
+ const geocodingData = (await geocodingResponse.json()) as {
20
+ results: { latitude: number; longitude: number; name: string }[];
21
+ };
22
+
23
+ if (!geocodingData.results?.[0]) {
24
+ throw new Error(`Location '${triggerData.city}' not found`);
25
+ }
26
+
27
+ const { latitude, longitude, name } = geocodingData.results[0];
28
+
29
+ const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_mean,weathercode&timezone=auto`;
30
+ const response = await fetch(weatherUrl);
31
+ const data = (await response.json()) as {
32
+ daily: {
33
+ time: string[];
34
+ temperature_2m_max: number[];
35
+ temperature_2m_min: number[];
36
+ precipitation_probability_mean: number[];
37
+ weathercode: number[];
38
+ };
39
+ };
40
+
41
+ const forecast = data.daily.time.map((date: string, index: number) => ({
42
+ date,
43
+ maxTemp: data.daily.temperature_2m_max[index],
44
+ minTemp: data.daily.temperature_2m_min[index],
45
+ precipitationChance: data.daily.precipitation_probability_mean[index],
46
+ condition: getWeatherCondition(data.daily.weathercode[index]!),
47
+ location: name,
48
+ }));
49
+
50
+ return forecast;
51
+ },
52
+ });
53
+
54
+ const forecastSchema = z.array(
55
+ z.object({
56
+ date: z.string(),
57
+ maxTemp: z.number(),
58
+ minTemp: z.number(),
59
+ precipitationChance: z.number(),
60
+ condition: z.string(),
61
+ location: z.string(),
62
+ }),
63
+ );
64
+
65
+ const planActivities = new Step({
66
+ id: 'plan-activities',
67
+ description: 'Suggests activities based on weather conditions',
68
+ inputSchema: forecastSchema,
69
+ execute: async ({ context, mastra }) => {
70
+ const forecast = context.machineContext?.getStepPayload<z.infer<typeof forecastSchema>>('fetch-weather');
71
+
72
+ if (!forecast) {
73
+ throw new Error('Forecast data not found');
74
+ }
75
+
76
+ const prompt = `Based on the following weather forecast for ${forecast[0].location}, suggest appropriate activities:
77
+ ${JSON.stringify(forecast, null, 2)}
78
+ `;
79
+
80
+ if (!mastra?.llm) {
81
+ throw new Error('Mastra not found');
82
+ }
83
+
84
+ const llm = mastra.llm({
85
+ provider: 'OPEN_AI',
86
+ name: 'gpt-4o',
87
+ });
88
+
89
+ const response = await llm.stream([
90
+ {
91
+ role: 'system',
92
+ content: `You are a local activities and travel expert who excels at weather-based planning. Analyze the weather data and provide practical activity recommendations.
93
+
94
+ For each day in the forecast, structure your response exactly as follows:
95
+
96
+ 📅 [Day, Month Date, Year]
97
+ ═══════════════════════════
98
+
99
+ 🌡️ WEATHER SUMMARY
100
+ • Conditions: [brief description]
101
+ • Temperature: [X°C/Y°F to A°C/B°F]
102
+ • Precipitation: [X% chance]
103
+
104
+ 🌅 MORNING ACTIVITIES
105
+ Outdoor:
106
+ • [Activity Name] - [Brief description including specific location/route]
107
+ Best timing: [specific time range]
108
+ Note: [relevant weather consideration]
109
+
110
+ 🌞 AFTERNOON ACTIVITIES
111
+ Outdoor:
112
+ • [Activity Name] - [Brief description including specific location/route]
113
+ Best timing: [specific time range]
114
+ Note: [relevant weather consideration]
115
+
116
+ 🏠 INDOOR ALTERNATIVES
117
+ • [Activity Name] - [Brief description including specific venue]
118
+ Ideal for: [weather condition that would trigger this alternative]
119
+
120
+ ⚠️ SPECIAL CONSIDERATIONS
121
+ • [Any relevant weather warnings, UV index, wind conditions, etc.]
122
+
123
+ Guidelines:
124
+ - Suggest 2-3 time-specific outdoor activities per day
125
+ - Include 1-2 indoor backup options
126
+ - For precipitation >50%, lead with indoor activities
127
+ - All activities must be specific to the location
128
+ - Include specific venues, trails, or locations
129
+ - Consider activity intensity based on temperature
130
+ - Keep descriptions concise but informative
131
+
132
+ Maintain this exact formatting for consistency, using the emoji and section headers as shown.`,
133
+ },
134
+ {
135
+ role: 'user',
136
+ content: prompt,
137
+ },
138
+ ]);
139
+
140
+ for await (const chunk of response.textStream) {
141
+ process.stdout.write(chunk);
142
+ }
143
+
144
+ return {
145
+ activities: response.text,
146
+ };
147
+ },
148
+ });
149
+
150
+ function getWeatherCondition(code: number): string {
151
+ const conditions: Record<number, string> = {
152
+ 0: 'Clear sky',
153
+ 1: 'Mainly clear',
154
+ 2: 'Partly cloudy',
155
+ 3: 'Overcast',
156
+ 45: 'Foggy',
157
+ 48: 'Depositing rime fog',
158
+ 51: 'Light drizzle',
159
+ 53: 'Moderate drizzle',
160
+ 55: 'Dense drizzle',
161
+ 61: 'Slight rain',
162
+ 63: 'Moderate rain',
163
+ 65: 'Heavy rain',
164
+ 71: 'Slight snow fall',
165
+ 73: 'Moderate snow fall',
166
+ 75: 'Heavy snow fall',
167
+ 95: 'Thunderstorm',
168
+ };
169
+ return conditions[code] || 'Unknown';
170
+ }
171
+
172
+ const weatherWorkflow = new Workflow({
173
+ name: 'weather-workflow',
174
+ triggerSchema: z.object({
175
+ city: z.string().describe('The city to get the weather for'),
176
+ }),
177
+ })
178
+ .step(fetchWeather)
179
+ .then(planActivities);
180
+
181
+ weatherWorkflow.commit();
182
+
183
+ export { weatherWorkflow };