I have a feature where the user can log what they’ve eaten for meal and the food data would get passed into to a fine-tuned model I created and the model would feedback to the user the impact it would have on their sugar levels and well-being. After having trained the model using the jsonl file which successfully completed and tested it in the playground. When I include the code in my views.py and test it, i get a 200 response in the terminal, but on the UI its saying “Sorry, I couldn’t provide a response. Please try again.”. Any help here would be much appreciated to help me fix this issue.
On the frontend, the user enters what they had for breakfast for example, fish and chips, and the model would produce an output like shown on the second image.
#views.py
from openai import OpenAI
client = OpenAI(api_key=os.getenv(“OPENAI_API_KEY”))
@csrf_exempt
def get_dietary_advice(request):
if request.method == “POST”:
data = json.loads(request.body)
user_input = data.get(“user_input”)
try:
response = client.chat.completions.create(
model="ft:gpt-3.5-turbo-0125:personal:dietary-advice-bot:9CUENrwC",
messages=[
{
"role": "system",
"content": "This chatbot provides dietary advice for people with type 2 diabetes."
},
{
"role": "user",
"content": user_input
}
],
max_tokens=150,
temperature=0.7,
frequency_penalty=0,
presence_penalty=0,
)
# Extract the advice from the response assuming the last message is the bot's response
if 'choices' in response and response['choices']:
advice = response['choices'][0]['message']['content']
else:
advice = "Sorry, I couldn't provide a response. Please try again."
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
# Save the user input and AI advice to the database (assuming this model exists in your Django app)
entry = UserMealEntry.objects.create(
user_input=user_input,
ai_advice=advice
)
return JsonResponse({'advice': advice})
return JsonResponse({'error': 'Invalid request'}, status=400)
eenshot 2024-04-11 at 13.08.30.png…]()
The React component:
import React, { useState } from ‘react’;
import ‘…/…/sass/PatientDashboard.scss’;
import { Typography, Grid, IconButton, Button } from ‘@mui/material’;
import ArrowBackIosIcon from ‘@mui/icons-material/ArrowBackIos’;
import ArrowForwardIosIcon from ‘@mui/icons-material/ArrowForwardIos’;
import AddIcon from ‘@mui/icons-material/Add’;
import axios from ‘axios’;
import { Dialog, DialogTitle, DialogContent, TextField, DialogActions } from ‘@mui/material’;
const DietaryHabits = () => {
const [selectedDate, setSelectedDate] = useState(new Date());
const [open, setOpen] = useState(false);
const [currentMeal, setCurrentMeal] = useState(‘’);
const [foodEntry, setFoodEntry] = useState(‘’);
const [entries, setEntries] = useState({ Breakfast: ‘’, Lunch: ‘’, Dinner: ‘’, Snacks: ‘’ });
const [dietaryAdvice, setDietaryAdvice] = useState(‘’);
const handleClickOpen = (meal) => {
setCurrentMeal(meal);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const changeDate = (offset) => {
setSelectedDate(prevDate => {
const newDate = new Date(prevDate);
newDate.setDate(newDate.getDate() + offset);
return newDate;
});
};
const formatDate = (date) => {
return date.toLocaleDateString('en-UK', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
// Function to submit the food entry to the backend
const handleAddFood = async () => {
try {
const token = localStorage.getItem('token');
const response = await axios.post('/api/dietary-advice/', { user_input: foodEntry }, {
headers: {
Authorization: `Token ${token}`
}
});
setDietaryAdvice(response.data.advice);
handleClose(); // Close the dialog
// TODO: You might want to do something with the advice here, like displaying it to the user
} catch (error) {
console.error('There was an error getting the dietary advice:', error);
// Handle errors here, such as displaying a message to the user
}
};
// Update food entry state when typing in the text field
const handleFoodEntryChange = (event) => {
setFoodEntry(event.target.value);
};
return (
<div style={{ backgroundColor: '#eef0f9', padding: '16px' }}>
<Typography variant="h5" gutterBottom>
Dietary Habits
</Typography>
<Typography variant="subtitle1" gutterBottom>
Track and manage your daily food intake to better control your blood sugar levels.
</Typography>
<Grid container justifyContent="center" alignItems="center" sx={{ my: 2 }}>
<IconButton onClick={() => changeDate(-1)} aria-label="Previous day">
<ArrowBackIosIcon />
</IconButton>
<Grid item xs={12} sm={'auto'}>
<Typography variant="body1" align="center">
{formatDate(selectedDate)}
</Typography>
</Grid>
<IconButton onClick={() => changeDate(1)} aria-label="Next day">
<ArrowForwardIosIcon />
</IconButton>
</Grid>
{['Breakfast', 'Lunch', 'Dinner', 'Snacks'].map((meal) => (
<Grid container justifyContent="space-between" alignItems="center" sx={{ mt: 4 }}>
<Typography variant="h6" component="div">
{meal}
</Typography>
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={() => handleClickOpen(meal)}
sx={{
bgcolor: 'primary.main',
'&:hover': {
bgcolor: 'primary.dark',
},
}}
>
ADD FOOD
</Button>
<Dialog open={open && currentMeal === meal} onClose={handleClose}>
<DialogTitle>Add Food for {currentMeal}</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
id="food"
label="Food Name"
type="text"
fullWidth
variant="standard"
value={foodEntry}
onChange={handleFoodEntryChange}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleAddFood}>Add</Button>
</DialogActions>
</Dialog>
</Grid>
))}
{/* Possibly display the dietary advice here */}
{dietaryAdvice && <Typography>{dietaryAdvice}</Typography>}
</div>
);
};
export default DietaryHabits;