Week10 / app.py
bparekh99's picture
Update app.py
af2927a verified
import gradio as gr
import os
import openai
# Assuming customer_order_management and order_response are defined elsewhere
# For demonstration purposes, let's create dummy data
import json
file_path = "customer_order_management.json"
# Open and read the JSON file
with open(file_path, "r", encoding="utf-8") as file:
data = json.load(file) # Load JSON into a Python dictionary
customer_order_management = data
# customer_order_management = {
# "ORD123": {"item": "Laptop", "status": "Shipped", "date": "2023-10-27"},
# "ORD456": {"item": "Keyboard", "status": "Processing", "date": "2023-10-28"},
# }
# Hardcoded base URL for the OpenAI API
openai.api_base = "https://aibe.mygreatlearning.com/openai/v1" # Replace with your actual API base URL
# Define the system message for the order management assistant
order_system_message = "You are an order management assistant. Provide details about the order based on the provided data and user query."
def get_openai_response(system_message, user_data, user_query, api_key):
"""
Gets a response from the OpenAI API.
"""
openai.api_key = "gl-U2FsdGVkX19IRkV5/9AArju4hogc+YLYdh9yQ9pjfph8ou0ZHfSCcUOov5cKAw0r" # Set the API key for the current request
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": f"Order Data:\n{user_data}\nUser Query: {user_query}"}
]
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Or your preferred model
messages=messages
)
return response.choices[0].message['content']
except Exception as e:
return f"Error communicating with OpenAI API: {e}"
def Chatbot(user_query, order_no, api_key):
"""
Chatbot function adapted for Gradio interface, interacting with OpenAI API.
"""
order_no = order_no.strip().upper()
if order_no in customer_order_management:
order_details = customer_order_management.get(order_no)
user_data = "\n".join([f"{key}: {value}" for key, value in order_details.items()])
# Get response from OpenAI API
response = get_openai_response(order_system_message, user_data, user_query, api_key)
return response
else:
return "Invalid order number. Please try again."
# Create the Gradio interface
interface = gr.Interface(
fn=Chatbot,
inputs=[
gr.Textbox(label="Enter your query"),
gr.Textbox(label="Enter your order number"),
# gr.Textbox(label="Enter your OpenAI API Key", type="password") # Input for API key
],
outputs=gr.Textbox(label="Chatbot Response"),
title="Order Management Chatbot with OpenAI",
description="Enter your query, order number, and OpenAI API key to get order details."
)
# Launch the interface
interface.launch()