Chat_bot / app.py
Aahi8828's picture
Update app.py
af9057d verified
import gradio as gr
import openai
import os
# Set the OpenAI API key and endpoint
openai.api_key = os.getenv("GROQ_API_KEY")
openai.api_base = "https://api.groq.com/openai/v1"
# Check if the API key is set properly
if not openai.api_key:
raise ValueError("API key is missing. Please set the GROQ_API_KEY environment variable.")
def get_groq_response(message):
try:
# Log the request to help with debugging
print(f"Sending message: {message}")
# Make the API call
response = openai.ChatCompletion.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": "Precise answer"},
{"role": "user", "content": message}
]
)
# Check if the response contains 'choices'
if not response.get('choices'):
raise ValueError("API response does not contain choices.")
# Extract the bot's message from the response
bot_message = response['choices'][0]['message']['content']
# Log the bot's response
print(f"Received response: {bot_message}")
return bot_message
except openai.error.AuthenticationError:
return "Authentication error: Invalid API key."
except openai.error.RateLimitError:
return "Rate limit exceeded: Too many requests. Please try again later."
except openai.error.APIError as e:
return f"API error: {e.user_message} Please try again later."
except openai.error.Timeout:
return "Request timed out. Please try again later."
except Exception as e:
# Catch all other exceptions
return f"An unexpected error occurred: {str(e)}"
def chatbot(user_input, history=None):
# Initialize history as an empty list if None is passed
if history is None:
history = []
# Avoid processing empty user input
if not user_input.strip():
return history, history
# Get the bot's response
bot_response = get_groq_response(user_input)
# Append the interaction to the conversation history
history.append((user_input, bot_response))
return history, history
# Create the Gradio interface
chat_interface = gr.Interface(
fn=chatbot,
inputs=["text", "state"],
outputs=["chatbot", "state"],
live=False,
title="My Chatbot",
description="Mom: We have ChatGPT at Home, \nChatGPT at Home: "
)
# Launch the Gradio app
chat_interface.launch()