-
Notifications
You must be signed in to change notification settings - Fork 0
/
AGiXTService.ts
1182 lines (1037 loc) · 39.8 KB
/
AGiXTService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import axios from 'axios';
interface ActivitySummaryRecord {
activityType: string;
duration: number;
}
export interface UserProfile {
name: string;
age: string;
gender: string;
feet: string;
inches: string;
weight: string;
goal: string;
fitnessLevel: string;
daysPerWeek: string;
bio: string;
interests: string;
profileImage: string | null;
level: number;
experiencePoints: number;
currentStreak: number;
longestStreak: number;
lastWorkoutDate: string;
coins: number;
unlockedAchievements: string[];
friends: string[];
}
export interface Exercise {
name: string;
sets: number;
reps: string;
rest: string;
text?: string;
}
export interface DayPlan {
day: string;
focus: string;
exercises: Exercise[];
}
export interface WorkoutPlan {
weeklyPlan: DayPlan[];
nutritionAdvice: string;
}
export interface WorkoutPlanResponse {
conversationName: string;
workoutPlan: WorkoutPlan;
completed: boolean;
difficulty: number;
}
export interface Challenge {
id: number;
name: string;
description: string;
duration: string;
difficulty: string;
completed: boolean;
}
export interface Supplement {
id: number;
name: string;
dosage: string;
benefit: string;
}
export interface MealPlan {
breakfast: string;
lunch: string;
dinner: string;
snacks: string[];
}
export interface CustomExercise {
id: number;
name: string;
description: string;
}
export interface WorkoutFeedback {
workoutId: string;
difficulty: 'easy' | 'just right' | 'hard';
completedExercises: string[];
}
export interface FeedbackAnalysis {
sentiment: string;
commonIssues: string[];
}
export interface AdaptiveWorkoutPlan extends WorkoutPlan {
adaptationLevel: number;
recommendedDifficulty: number;
}
export interface AnomalyDetectionResult {
isAnomaly: boolean;
details: string;
}
export interface PersonalizedRecommendation {
workoutPlan: WorkoutPlan;
focusAreas: string[];
recommendedExercises: string[];
nutritionTips: string[];
}
export interface FitnessForecast {
date: string;
predictedMetrics: {
weight: number;
bodyFat: number;
muscleGain: number;
};
}
export interface WorkoutPreferences {
location: string;
space: string;
equipment: string[];
}
export interface SocialChallenge {
id: string;
creatorId: string;
participantIds: string[];
challengeName: string;
description: string;
startDate: string;
endDate: string;
goal: number;
unit: string;
}
export interface ProgressReport {
summary: string;
workoutProgress: {
totalWorkouts: number;
averageDifficulty: number;
mostImprovedExercises: string[];
};
bodyCompositionChanges: {
weightChange: number;
bodyFatPercentageChange: number;
};
recommendations: string[];
}
export interface BodyMeasurements {
date: string;
weight: number;
bodyFatPercentage: number;
measurements: {
[key: string]: number;
};
}
interface WorkoutAnalysis {
recommendation: string;
warning: boolean;
}
class AGiXTService {
public baseUri: string;
public headers: { [key: string]: string };
public agentName: string = 'WorkoutAgent';
private isDemoMode: boolean;
constructor(isDemoMode: boolean) {
this.baseUri = '';
this.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
this.isDemoMode = isDemoMode;
}
public updateSettings(newUri: string, newApiKey: string) {
this.baseUri = newUri;
this.headers = {
...this.headers,
'Authorization': `Bearer ${newApiKey}`,
};
}
private async request(method: string, endpoint: string, data?: any) {
try {
const response = await axios({
method,
url: `${this.baseUri}${endpoint}`,
headers: this.headers,
data,
});
return response.data;
} catch (error) {
console.error(`Error in ${method} request to ${endpoint}:`, error);
throw error;
}
}
public async getAgents(): Promise<any> {
if (this.isDemoMode) {
return { agents: [{ name: 'DemoAgent' }] }; // Dummy data
}
return this.request('get', '/api/agent');
}
public async addAgent(agentName: string, settings: any = {}): Promise<any> {
if (this.isDemoMode) {
console.log('Demo Mode: Agent added -', agentName, settings);
return { success: true }; // Dummy response
}
return this.request('post', '/api/agent', { agent_name: agentName, settings });
}
public async newConversation(agentName: string, conversationName: string, conversationContent: any[] = []): Promise<any> {
if (this.isDemoMode) {
console.log('Demo Mode: New conversation created -', agentName, conversationName, conversationContent);
return { success: true }; // Dummy response
}
return this.request('post', '/api/conversation', {
conversation_name: conversationName,
agent_name: agentName,
conversation_content: conversationContent,
});
}
public async chat(agentName: string, userInput: string, conversationName: string, contextResults = 4): Promise<any> {
if (this.isDemoMode) {
console.log('Demo Mode: Chat simulated -', agentName, userInput, conversationName, contextResults);
return { response: '{ "demo": "response" }' }; // Dummy response
}
return this.request('post', `/api/agent/${agentName}/prompt`, {
prompt_name: 'Chat',
prompt_args: {
user_input: userInput,
context_results: contextResults,
conversation_name: conversationName,
disable_memory: true,
},
});
}
public async newConversationMessage(role: string, message: string, conversationName: string): Promise<any> {
if (this.isDemoMode) {
console.log('Demo Mode: New conversation message added -', role, message, conversationName);
return { success: true }; // Dummy response
}
return this.request('post', '/api/conversation/message', {
role,
message,
conversation_name: conversationName,
});
}
public async initializeWorkoutAgent(): Promise<void> {
if (this.isDemoMode) {
console.log('Demo Mode: Workout agent initialization skipped.');
return;
}
try {
const agentsResponse = await this.getAgents();
const agents = agentsResponse.agents || [];
if (!agents.some((agent: any) => agent.name === this.agentName)) {
await this.createWorkoutAgent();
}
} catch (error) {
console.error('Error initializing WorkoutAgent:', error);
throw error;
}
}
private async createWorkoutAgent(): Promise<void> {
if (this.isDemoMode) {
console.log('Demo Mode: Workout agent creation skipped.');
return;
}
const settings = {
provider: 'gpt4free',
AI_MODEL: 'gpt-3.5-turbo',
AI_TEMPERATURE: 0.7,
MAX_TOKENS: 4000,
embedder: 'default',
};
try {
await this.addAgent(this.agentName, settings);
console.log('WorkoutAgent created successfully');
} catch (error) {
console.error('Error creating WorkoutAgent:', error);
throw error;
}
}
public extractJson(response: any): any {
let jsonResponse: any;
if (typeof response === 'string') {
try {
jsonResponse = JSON.parse(response);
} catch (error) {
console.error("Failed to parse response as JSON:", error);
const match = response.match(/\{[\s\S]*\}/);
if (match) {
try {
jsonResponse = JSON.parse(match[0]);
} catch (innerError) {
console.error("Failed to parse extracted JSON:", innerError);
try {
const truncatedResponse = response.substring(0, response.lastIndexOf('}') + 1);
jsonResponse = JSON.parse(truncatedResponse);
} catch (finalError) {
console.error("Failed to parse truncated response as JSON:", finalError);
throw new Error("Failed to extract valid JSON from response");
}
}
} else {
throw new Error("No valid JSON found in the response");
}
}
} else if (typeof response === 'object' && response !== null) {
if (response.response) {
try {
jsonResponse = JSON.parse(response.response);
} catch (error) {
console.error("Failed to parse response.response as JSON:", error);
try {
const truncatedResponse = response.response.substring(0, response.response.lastIndexOf('}') + 1);
jsonResponse = JSON.parse(truncatedResponse);
} catch (finalError) {
console.error("Failed to parse truncated response.response as JSON:", finalError);
throw new Error("Failed to parse response.response as JSON");
}
}
} else {
jsonResponse = response;
}
} else {
throw new Error("Response is neither a string nor an object");
}
return jsonResponse;
}
public async generateMultipleWorkouts(preferences: WorkoutPreferences, userProfile: UserProfile, count: number = 3, bodyPart: string | null = null): Promise<WorkoutPlanResponse[]> {
if (this.isDemoMode) {
// Return dummy workout data
return [
{
conversationName: 'DemoWorkout_1',
workoutPlan: {
weeklyPlan: [
{
day: 'Day 1 - Chest & Triceps',
focus: 'Strength',
exercises: [
{ name: 'Bench Press', sets: 3, reps: '8-12', rest: '60 seconds' },
{ name: 'Incline Dumbbell Press', sets: 3, reps: '8-12', rest: '60 seconds' },
{ name: 'Dumbbell Flyes', sets: 3, reps: '10-15', rest: '60 seconds' },
{ name: 'Close-Grip Bench Press', sets: 3, reps: '8-12', rest: '60 seconds' },
{ name: 'Triceps Pushdowns', sets: 3, reps: '12-15', rest: '60 seconds' },
],
},
{
day: 'Day 2 - Back & Biceps',
focus: 'Strength',
exercises: [
{ name: 'Pull-ups', sets: 3, reps: 'As many as possible', rest: '60 seconds' },
{ name: 'Barbell Rows', sets: 3, reps: '8-12', rest: '60 seconds' },
{ name: 'Lat Pulldowns', sets: 3, reps: '10-15', rest: '60 seconds' },
{ name: 'Dumbbell Curls', sets: 3, reps: '10-12', rest: '60 seconds' },
{ name: 'Hammer Curls', sets: 3, reps: '12-15', rest: '60 seconds' },
],
},
],
nutritionAdvice: 'Eat plenty of protein and complex carbohydrates.',
},
completed: false,
difficulty: 3,
},
];
} else {
// Real workout generation logic (remove initializeWorkoutAgent call)
const conversationName = `MultipleWorkouts_${Date.now()}`;
const generatedWorkouts: any[] = [];
const workoutNames = new Set();
try {
await this.newConversation(this.agentName, conversationName);
const chunkSize = Math.ceil(count / 3);
for (let i = 0; i < count; i += chunkSize) {
const numToGenerate = Math.min(chunkSize, count - i);
const prompt = `Generate ${numToGenerate} unique workout plans for a ${userProfile.gender} aged ${userProfile.age} with a fitness level of ${userProfile.fitnessLevel} and the following preferences:
Location: ${preferences.location}
Available space: ${preferences.space}
Equipment: ${preferences.equipment.join(', ')}
Fitness goal: ${userProfile.goal}
${bodyPart ? `Focus on: ${bodyPart}` : ''}
Each workout plan should be suitable for the given preferences and include:
1. A unique name for the workout
2. 5-7 exercises
3. For each exercise: name, sets, reps, rest time, and any additional instructions
4. A difficulty rating (1-5) based on the user's fitness level
5. A focus area for the workout (e.g., Strength, Endurance, Flexibility)
Please format the response as a JSON object with the following structure:
{
"workouts": [
{
"name": "Workout Name",
"difficulty": 3,
"focus": "Strength", // Include focus here
"exercises": [
{
"name": "Exercise Name",
"sets": 3,
"reps": "10-12",
"rest": "60 seconds",
"text": "Additional details about the exercise"
}
]
}
]
}`;
console.log("Sending prompt to AGiXT:", prompt);
const response = await this.chat(this.agentName, prompt, conversationName);
console.log("Received response from AGiXT:", response);
const newWorkouts = this.extractJson(response).workouts;
newWorkouts.forEach((workout: any) => {
if (!workoutNames.has(workout.name)) {
workoutNames.add(workout.name);
generatedWorkouts.push(workout);
}
});
}
const workoutPlans: WorkoutPlanResponse[] = generatedWorkouts.map((workout, index) => ({
conversationName: `${conversationName}_${index}`,
workoutPlan: {
weeklyPlan: [{
day: workout.name,
focus: workout.focus || 'General', // Provide a default if focus is missing
exercises: workout.exercises
}],
nutritionAdvice: "Personalized nutrition advice will be generated separately."
},
completed: false,
difficulty: workout.difficulty
}));
await this.newConversationMessage('assistant', JSON.stringify(workoutPlans, null, 2), conversationName);
return workoutPlans;
} catch (error) {
console.error('Error generating multiple workouts:', error);
throw error;
}
}
}
public async getChallenges(userProfile: UserProfile): Promise<Challenge[]> {
if (this.isDemoMode) {
return [
{
id: 1,
name: 'Demo Challenge 1',
description: 'Complete 3 demo workouts this week.',
duration: '1 week',
difficulty: 'Easy',
completed: false,
},
{
id: 2,
name: 'Demo Challenge 2',
description: 'Run 5 miles.',
duration: '1 week',
difficulty: 'Medium',
completed: false,
},
// Add more demo challenges as needed
];
} else {
// Real challenge generation logic (remove initializeWorkoutAgent call)
const conversationName = `Challenges_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Generate a series of fitness challenges for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal}. Each challenge should have an id, name, description, duration,
difficulty level, and a completion status.
Please format the response as a JSON object with the following structure:
{
"challenges": [
{
"id": 1,
"name": "Challenge Name",
"description": "Detailed description of the challenge",
"duration": "Duration of the challenge",
"difficulty": "Difficulty level",
"completed": false
}
]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const challenges = this.extractJson(response).challenges;
await this.newConversationMessage('assistant', JSON.stringify({ challenges }, null, 2), conversationName);
return challenges;
} catch (error) {
console.error('Error generating challenges:', error);
throw error;
}
}
}
public async analyzeFeedback(feedback: string): Promise<FeedbackAnalysis> {
if (this.isDemoMode) {
return {
sentiment: 'positive',
commonIssues: [],
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `FeedbackAnalysis_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Analyze the following user feedback and provide sentiment analysis and identify common issues:
User Feedback: "${feedback}"
Please format the response as a JSON object with the following structure:
{
"sentiment": "positive/negative/neutral",
"commonIssues": ["issue1", "issue2", "issue3"]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
return this.extractJson(response);
} catch (error) {
console.error('Error analyzing feedback:', error);
throw error;
}
}
}
public async getAdaptiveWorkout(userProfile: UserProfile, previousPerformance: WorkoutFeedback[]): Promise<AdaptiveWorkoutPlan> {
if (this.isDemoMode) {
return {
weeklyPlan: [
{
day: 'Demo Adaptive Workout',
focus: 'Strength', // Add focus here
exercises: [
{ name: 'Push-ups', sets: 3, reps: '10-12', rest: '60 seconds' },
{ name: 'Squats', sets: 3, reps: '12-15', rest: '60 seconds' },
],
},
],
nutritionAdvice: 'Demo Nutrition Advice: Stay hydrated and eat a balanced diet.',
adaptationLevel: 0.8,
recommendedDifficulty: 2.7,
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `AdaptiveWorkout_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const averageDifficulty = previousPerformance.reduce((sum, feedback) => {
return sum + (feedback.difficulty === 'easy' ? 1 : feedback.difficulty === 'just right' ? 2 : 3);
}, 0) / previousPerformance.length;
const prompt = `Create an adaptive workout plan for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal} and fitness level ${userProfile.fitnessLevel}.
The average difficulty of previous workouts was ${averageDifficulty.toFixed(2)} (1=easy, 2=just right, 3=hard).
Adjust the workout difficulty and complexity based on this information.
Please format the response as a JSON object with the following structure:
{
"weeklyPlan": [
{
"day": "Day 1",
"focus": "Strength", // Ensure AGiXT includes focus
"exercises": [
{
"name": "Exercise Name",
"sets": 3,
"reps": "10-12",
"rest": "60 seconds",
"text": "Additional details about the exercise"
}
]
}
],
"nutritionAdvice": "Detailed nutrition advice here",
"adaptationLevel": 0.75,
"recommendedDifficulty": 2.5
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const adaptiveWorkoutPlan = this.extractJson(response);
adaptiveWorkoutPlan.weeklyPlan.forEach((dayPlan: DayPlan) => {
dayPlan.focus = dayPlan.focus || 'General';
});
return adaptiveWorkoutPlan;
} catch (error) {
console.error('Error generating adaptive workout:', error);
throw error;
}
}
}
public async detectAnomalies(userMetrics: number[]): Promise<AnomalyDetectionResult> {
if (this.isDemoMode) {
return {
isAnomaly: false,
details: 'No anomalies detected in demo mode.',
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `AnomalyDetection_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Analyze the following user metrics for anomalies: ${userMetrics.join(', ')}
Please format the response as a JSON object with the following structure:
{
"isAnomaly": true/false,
"details": "Explanation of any detected anomalies"
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
return this.extractJson(response);
} catch (error) {
console.error('Error detecting anomalies:', error);
throw error;
}
}
}
public async getPersonalizedRecommendations(userProfile: UserProfile, workoutHistory: WorkoutFeedback[], preferences: WorkoutPreferences): Promise<PersonalizedRecommendation> {
if (this.isDemoMode) {
return {
workoutPlan: {
weeklyPlan: [
{
day: 'Demo Personalized Workout',
focus: 'Strength',
exercises: [
{ name: 'Bench Press', sets: 3, reps: '8-12', rest: '60 seconds' },
{ name: 'Squats', sets: 3, reps: '10-15', rest: '60 seconds' },
],
},
],
nutritionAdvice: 'Demo Nutrition Advice: Focus on protein intake and hydration.',
},
focusAreas: ['Strength', 'Endurance'],
recommendedExercises: ['Deadlifts', 'Pull-ups'],
nutritionTips: ['Eat a balanced diet.', 'Get enough sleep.'],
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `PersonalizedRecommendations_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Generate personalized workout and nutrition recommendations for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal} and fitness level ${userProfile.fitnessLevel}.
User preferences: ${JSON.stringify(preferences)}
Workout history: ${JSON.stringify(workoutHistory)}
Please format the response as a JSON object with the following structure:
{
"workoutPlan": {
"weeklyPlan": [
{
"day": "Day 1",
"focus": "Strength", // Ensure AGiXT includes focus
"exercises": [
{
"name": "Exercise Name",
"sets": 3,
"reps": "10-12",
"rest": "60 seconds",
"text": "Additional details about the exercise"
}
]
}
],
"nutritionAdvice": "Detailed nutrition advice here"
},
"focusAreas": ["Strength", "Flexibility"],
"recommendedExercises": ["Recommended Exercise 1", "Recommended Exercise 2"],
"nutritionTips": [
"Increase protein intake",
"Add more leafy greens to your diet"
]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
return this.extractJson(response);
} catch (error) {
console.error('Error generating personalized recommendations:', error);
throw error;
}
}
}
public async getFitnessForecast(userProfile: UserProfile, historicalData: number[][]): Promise<FitnessForecast[]> {
if (this.isDemoMode) {
return [
{
date: '2024-01-01',
predictedMetrics: {
weight: 175,
bodyFat: 18,
muscleGain: 0.5,
},
},
// Add more demo forecast data as needed
];
} else {
await this.initializeWorkoutAgent();
const conversationName = `FitnessForecast_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Generate a fitness forecast for the next 4 weeks based on the following historical data:
${JSON.stringify(historicalData)}. Consider the user's goal of ${userProfile.goal}.
Please format the response as a JSON object with the following structure:
{
"forecast": [
{
"date": "YYYY-MM-DD",
"predictedMetrics": {
"weight": 70.5,
"bodyFat": 15.2,
"muscleGain": 0.3
}
}
]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
return this.extractJson(response).forecast;
} catch (error) {
console.error('Error generating fitness forecast:', error);
throw error;
}
}
}
public async getSupplements(userProfile: UserProfile): Promise<Supplement[]> {
if (this.isDemoMode) {
return [
{
id: 1,
name: 'Demo Supplement 1',
dosage: '1 capsule daily',
benefit: 'Improved muscle recovery',
},
// Add more demo supplements as needed
];
} else {
await this.initializeWorkoutAgent();
const conversationName = `Supplements_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Recommend dietary supplements for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal}. Each supplement should have an id, name, dosage, and benefit.
Please format the response as a JSON object with the following structure:
{
"supplements": [
{
"id": 1,
"name": "Supplement Name",
"dosage": "Dosage information",
"benefit": "Health benefit of the supplement"
}
]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const supplements = this.extractJson(response).supplements;
await this.newConversationMessage('assistant', JSON.stringify({ supplements }, null, 2), conversationName);
return supplements;
} catch (error) {
console.error('Error recommending supplements:', error);
throw error;
}
}
}
public async getMealPlan(userProfile: UserProfile): Promise<MealPlan> {
if (this.isDemoMode) {
return {
breakfast: 'Demo Breakfast: Oatmeal with berries and nuts',
lunch: 'Demo Lunch: Chicken salad sandwich on whole-wheat bread',
dinner: 'Demo Dinner: Salmon with roasted vegetables',
snacks: ['Demo Snack 1: Greek yogurt with fruit', 'Demo Snack 2: Almonds'],
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `MealPlan_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Generate a detailed meal plan for a ${userProfile.gender} aged ${userProfile.age}, height ${userProfile.feet}'${userProfile.inches}",
weight ${userProfile.weight} lbs, with a fitness goal of ${userProfile.goal}.
Please format the response as a JSON object with the following structure:
{
"breakfast": "Detailed breakfast plan",
"lunch": "Detailed lunch plan",
"dinner": "Detailed dinner plan",
"snacks": ["Snack 1", "Snack 2", "Snack 3"]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const mealPlan = this.extractJson(response);
await this.newConversationMessage('assistant', JSON.stringify(mealPlan, null, 2), conversationName);
return mealPlan;
} catch (error) {
console.error('Error generating meal plan:', error);
throw error;
}
}
}
public async addCustomExercise(userProfile: UserProfile, exercise: { name: string; description: string }): Promise<CustomExercise[]> {
if (this.isDemoMode) {
return [
{
id: 1,
name: 'Demo Custom Exercise',
description: 'This is a demo custom exercise.',
},
];
} else {
await this.initializeWorkoutAgent();
const conversationName = `CustomExercise_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Add a custom exercise for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal}. The exercise name is "${exercise.name}" and the description is "${exercise.description}".
Please generate a list of custom exercises including this new one and any previously added exercises.
Please format the response as a JSON object with the following structure:
{
"customExercises": [
{
"id": 1,
"name": "Exercise Name",
"description": "Detailed description of the exercise"
}
]
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const customExercises = this.extractJson(response).customExercises;
await this.newConversationMessage('assistant', JSON.stringify(customExercises, null, 2), conversationName);
return customExercises;
} catch (error) {
console.error('Error adding custom exercise:', error);
throw error;
}
}
}
public async logWorkoutCompletion(userProfile: UserProfile, workoutPlan: WorkoutPlan, feedback: WorkoutFeedback): Promise<void> {
if (this.isDemoMode) {
console.log('Demo Workout Completion Logged:', { userProfile, workoutPlan, feedback });
} else {
await this.initializeWorkoutAgent();
const conversationName = `WorkoutCompletion_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Log the completion of a workout for a ${userProfile.gender} aged ${userProfile.age},
with a fitness goal of ${userProfile.goal}. The workout plan was: ${JSON.stringify(workoutPlan)}.
The user's feedback is: ${JSON.stringify(feedback)}.
Please provide a brief analysis of the workout completion and any recommendations for future workouts.
Please format the response as a JSON object with the following structure:
{
"analysis": "Brief analysis of the workout completion",
"recommendations": "Recommendations for future workouts"
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const completionAnalysis = this.extractJson(response);
await this.newConversationMessage('assistant', JSON.stringify(completionAnalysis, null, 2), conversationName);
console.log("Workout completion logged and analyzed:", completionAnalysis);
} catch (error) {
console.error('Error logging workout completion:', error);
throw error;
}
}
}
public async getMotivationalQuote(): Promise<string> {
if (this.isDemoMode) {
return 'Demo Quote: "The only bad workout is the one that didn\'t happen."';
} else {
await this.initializeWorkoutAgent();
const conversationName = `MotivationalQuote_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Provide a motivational quote for fitness enthusiasts.
Please format the response as a JSON object with the following structure:
{
"quote": "Motivational quote here"
}`;
const response = await this.chat(this.agentName, prompt, conversationName);
const quoteResponse = this.extractJson(response);
await this.newConversationMessage('assistant', JSON.stringify(quoteResponse, null, 2), conversationName);
return quoteResponse.quote;
} catch (error) {
console.error('Error getting motivational quote:', error);
throw error;
}
}
}
public async getProgressReport(userProfile: UserProfile, workoutHistory: WorkoutFeedback[], measurementHistory: BodyMeasurements[]): Promise<ProgressReport> {
if (this.isDemoMode) {
return {
summary: 'Demo Report: You\'re making great progress! Keep up the good work.',
workoutProgress: {
totalWorkouts: 10,
averageDifficulty: 2.5,
mostImprovedExercises: ['Push-ups', 'Squats'],
},
bodyCompositionChanges: {
weightChange: -5,
bodyFatPercentageChange: -2,
},
recommendations: ['Stay consistent with your workouts.', 'Focus on proper form.'],
};
} else {
await this.initializeWorkoutAgent();
const conversationName = `ProgressReport_${userProfile.name}_${Date.now()}`;
try {
await this.newConversation(this.agentName, conversationName);
const prompt = `Generate a comprehensive progress report for ${userProfile.name}.
Consider their fitness goal of ${userProfile.goal} and current fitness level of ${userProfile.fitnessLevel}.
Workout history: ${JSON.stringify(workoutHistory)}
Measurement history: ${JSON.stringify(measurementHistory)}