Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,47 +1,58 @@
|
|
1 |
-
import os
|
2 |
-
import requests
|
3 |
-
|
4 |
-
from dotenv import load_dotenv
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
# Check if the Groq API key is set
|
13 |
-
if groq_api_key is None:
|
14 |
-
raise ValueError("Groq API key is not set in environment variables.")
|
15 |
-
|
16 |
-
# Define the URL for the Groq API endpoint
|
17 |
-
url = "https://api.groq.com/openai/v1/chat/completions"
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import gradio as gr
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
|
6 |
+
# Load environment variables from .env file
|
7 |
+
load_dotenv()
|
8 |
+
|
9 |
+
# Get the Groq API key from environment variables
|
10 |
+
groq_api_key = os.environ.get("GROQ_API_KEY")
|
11 |
+
|
12 |
+
# Check if the Groq API key is set
|
13 |
+
if groq_api_key is None:
|
14 |
+
raise ValueError("Groq API key is not set in environment variables.")
|
15 |
+
|
16 |
+
# Define the URL for the Groq API endpoint
|
17 |
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
18 |
+
|
19 |
+
# Function to interact with the Groq API
|
20 |
+
def groq_chat(prompt):
|
21 |
+
headers = {
|
22 |
+
"Authorization": f"Bearer {groq_api_key}"
|
23 |
+
}
|
24 |
+
body = {
|
25 |
+
"model": "llama-3.1-8b-instant",
|
26 |
+
"messages": [
|
27 |
+
{
|
28 |
+
"role": "user",
|
29 |
+
"content": prompt
|
30 |
+
}
|
31 |
+
]
|
32 |
+
}
|
33 |
+
|
34 |
+
# Send a POST request to the Groq API
|
35 |
+
response = requests.post(url, headers=headers, json=body)
|
36 |
+
|
37 |
+
if response.status_code == 200:
|
38 |
+
# Extract and return the content of the first message choice
|
39 |
+
return response.json().get('choices', [{}])[0].get('message', {}).get('content', "No response found.")
|
40 |
+
else:
|
41 |
+
# Return the error details
|
42 |
+
return f"Error {response.status_code}: {response.text}"
|
43 |
+
|
44 |
+
# Define the Gradio interface
|
45 |
+
with gr.Blocks() as interface:
|
46 |
+
gr.Markdown("# Chat with Groq API")
|
47 |
+
with gr.Row():
|
48 |
+
user_input = gr.Textbox(label="Enter your prompt", placeholder="Type something funny or interesting...")
|
49 |
+
with gr.Row():
|
50 |
+
output = gr.Textbox(label="Response from Groq API")
|
51 |
+
with gr.Row():
|
52 |
+
submit_button = gr.Button("Get Response")
|
53 |
+
|
54 |
+
submit_button.click(fn=groq_chat, inputs=user_input, outputs=output)
|
55 |
+
|
56 |
+
# Launch the interface
|
57 |
+
if __name__ == "__main__":
|
58 |
+
interface.launch()
|