Spaces:
Sleeping
Sleeping
Upload groq_api.py
Browse files- groq_api.py +47 -0
groq_api.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
# Get the Groq API key from environment variables
|
| 9 |
+
groq_api_key = os.environ.get("GROQ_API_KEY")
|
| 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 |
+
# Set the headers for the API request
|
| 20 |
+
headers = {
|
| 21 |
+
"Authorization": f"Bearer {groq_api_key}"
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Define the body for the API request
|
| 25 |
+
body = {
|
| 26 |
+
"model": "llama-3.1-8b-instant",
|
| 27 |
+
"messages": [
|
| 28 |
+
{
|
| 29 |
+
"role": "user",
|
| 30 |
+
"content": "Tell me a very funny joke"
|
| 31 |
+
}
|
| 32 |
+
]
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Send a POST request to the Groq API
|
| 36 |
+
response = requests.post(url, headers=headers, json=body)
|
| 37 |
+
|
| 38 |
+
# Check if the request was successful
|
| 39 |
+
if response.status_code == 200:
|
| 40 |
+
# Print the full response from Groq
|
| 41 |
+
# print("Response from Groq:", response.json())
|
| 42 |
+
# print('\n')
|
| 43 |
+
# Print the content of the first message choice
|
| 44 |
+
print(response.json()['choices'][0]['message']['content'])
|
| 45 |
+
else:
|
| 46 |
+
# Print the error message if the request failed
|
| 47 |
+
print("Error:", response.status_code, response.text)
|