Spaces:
Paused
Paused
import os | |
import csv | |
import json | |
import logging | |
import pandas as pd | |
from openai import OpenAI | |
from dotenv import load_dotenv | |
load_dotenv() | |
api_key = os.getenv("OPENAI_API_KEY") | |
client = OpenAI(api_key=api_key) | |
def query_gpt(food_item): | |
prompt = ( | |
f"I have a particular food item and I can't find it in the USDA database. Can you suggest the most similar food item that would likely be in the USDA food database?\n\n" | |
f"Try to be as similar as possible to the food item, such that if the word is Leek, tell me 'Leeks, raw' and not 'Onion'.\n\n" | |
f"Make sure you're accurate about whether it is cooked, prepared, etc or not.\n\n" | |
f"But if its an obscure food, you can come up with a extremely similar food item that is similar in DMC.\n\n" | |
f"If it's not a food item, return 'Non-Food Item'.\n\n" | |
f"If it's a generic term like 'Mixture of foods', just say: 'Mixed Food Items'.\n\n" | |
f"You should respond in json format with an object that has the key `guess`, and the value is the most similar food item.\n\n" | |
f"The food item is: \"{food_item}\"" | |
) | |
completion = client.chat.completions.create( | |
messages=[ | |
{"role": "system", "content": "You are a helpful assistant."}, | |
{"role": "user", "content": prompt} | |
], | |
model="gpt-3.5-turbo-1106", | |
response_format={"type": "json_object"}, | |
) | |
response = completion.choices[0].message.content | |
parsed = parse_response(response) | |
logging.info(f"Q: '{food_item}'") | |
logging.info(f"A: '{parsed}'") | |
logging.info("") | |
return parsed | |
# Define the function to parse the GPT response | |
def parse_response(response): | |
try: | |
result = json.loads(response) | |
return result['guess'] | |
except (json.JSONDecodeError, KeyError) as e: | |
logging.info(f"Error parsing response: {response} - {e}") | |
return None | |