lifestyle development
This commit is contained in:
@@ -1,41 +1,49 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import OpenAI from 'openai';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import PersonalCode from '~/lib/utils';
|
||||
import { ILifeStyleResponse, PROMPT_NAME } from '../../_components/ai/types';
|
||||
import { updateLifeStyle } from './ai-actions';
|
||||
|
||||
const failedResponse = {
|
||||
lifeStyle: null,
|
||||
lifestyle: [],
|
||||
summary: null,
|
||||
};
|
||||
|
||||
async function lifeStyleLoader(account: AccountWithParams) {
|
||||
async function lifeStyleLoader(
|
||||
account: AccountWithParams,
|
||||
): Promise<ILifeStyleResponse> {
|
||||
if (!account?.personal_code) {
|
||||
return failedResponse;
|
||||
}
|
||||
|
||||
const openAIClient = new OpenAI();
|
||||
const { gender, age } = PersonalCode.parsePersonalCode(account.personal_code);
|
||||
try {
|
||||
const response = await openAIClient.responses.create({
|
||||
store: false,
|
||||
prompt: {
|
||||
id: analysesRecommendationsPromptId,
|
||||
variables: {
|
||||
analyses: JSON.stringify(formattedAnalyses),
|
||||
results: JSON.stringify(formattedAnalysisResponses),
|
||||
gender: gender.value,
|
||||
age: age.toString(),
|
||||
weight: weight.toString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
const lifeStylePromptId = process.env.PROMPT_ID_LIFE_STYLE;
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Error calling OpenAI: ', error);
|
||||
if (!lifeStylePromptId) {
|
||||
return failedResponse;
|
||||
}
|
||||
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
const { data, error } = await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.select('response')
|
||||
.eq('account_id', account.id)
|
||||
.eq('prompt_name', PROMPT_NAME.LIFE_STYLE)
|
||||
.order('latest_data_change', { ascending: false, nullsFirst: false })
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching AI response from DB: ', error);
|
||||
return failedResponse;
|
||||
}
|
||||
|
||||
if (data?.response) {
|
||||
return JSON.parse(data.response as string);
|
||||
} else {
|
||||
return await updateLifeStyle({ account });
|
||||
}
|
||||
}
|
||||
export const loadLifeStyle = cache(lifeStyleLoader);
|
||||
|
||||
Reference in New Issue
Block a user