File size: 2,048 Bytes
9189e38
 
 
b72dd6f
9189e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d93f20c
71df5fb
9189e38
 
 
 
 
 
 
 
 
 
 
 
 
 
b72dd6f
 
 
9189e38
 
 
 
 
 
 
 
b72dd6f
9189e38
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
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', or 'grocery items' just say: 'Heterogeneous Mixture'.\n\n"
        f"If it's not a food item, but a broad category like 'Various Produce', just say: 'Broad Category'.\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