File size: 2,520 Bytes
77d6c99 525af94 a67595f 525af94 a32c4b6 525af94 a32c4b6 525af94 a67595f a32c4b6 a67595f a32c4b6 a67595f a32c4b6 a67595f a32c4b6 a67595f a32c4b6 a65b0ad a32c4b6 a67595f a32c4b6 a67595f a32c4b6 a65b0ad a67595f a32c4b6 a67595f a32c4b6 a67595f 525af94 a32c4b6 525af94 a67595f 525af94 af9057d 525af94 a67595f a32c4b6 af9057d |
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
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() |