import openai import os from dotenv import load_dotenv from datetime import datetime import logging import traceback import json with open('available_slots.json', 'r') as file: available_slots = str(json.load(file)) now = datetime.now() date_strng = now.strftime("%d-%m-%Y_%H-%M-%S") if not os.path.exists('logs'): os.makedirs('logs') logging.basicConfig(filename='logs/{}.log'.format(date_strng), level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') logging.info('Starting the application') load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") context = f"""\ You will act as a booking agent, who will book appointments for customers for home repair. \ The customer needs to provide a day and time slot for the appointment. If the conversation \ strays from booking system, tactfully steer it back. Keep your responses succinct and engaging. \ When you determine the customer's preferences. The time slots available from the company are \ provided under the "Available Slots" section. The customer can choose from these slots. \ Available Slots: {available_slots} When you think the customer has provided a day and time slot, you can end the conversation by \ returning your final response in the JSON format below. JSON Format: {{ "day": "customer's preferred day goes here", "time": "customer's preferred time goes here }} """ messages = [] messages.append({"role": "system", "content": context}) def json_format(response): dict_start = response.find('{') dict_end = response.rfind('}') + 1 json_string = response[dict_start:dict_end] products_dict = json.loads(json_string) return products_dict["productCategory"] def chatbot(user_message, history): messages.append({"role": "user", "content": user_message}) logging.info("Getting response from gpt-3.5-turbo") response = openai.ChatCompletion.create( model="gpt-3.5-turbo-16k", messages=messages, temperature=0, ) messages.append({"role": "assistant", "content": response.choices[0].message.content}) # try: # product_category = json_format(response.choices[0].message.content) # # image_url = get_product_details(product_category) # # if image_url: # # return (image_url, product_category) # except: # pass logging.info("Messages list: {}".format(messages)) return response.choices[0].message.content