File size: 1,268 Bytes
efd3fdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests

from dotenv import load_dotenv

load_dotenv()

# Get the Groq API key from environment variables
groq_api_key = os.environ.get("GROQ_API_KEY")


# Check if the Groq API key is set
if groq_api_key is None:
    raise ValueError("Groq API key is not set in environment variables.")

# Define the URL for the Groq API endpoint
url = "https://api.groq.com/openai/v1/chat/completions"

# Set the headers for the API request
headers = {
    "Authorization": f"Bearer {groq_api_key}"
}

# Define the body for the API request
body = {
    "model": "llama-3.1-8b-instant",
    "messages": [
        {
            "role": "user",
            "content": "Tell me a very funny joke"
        }
    ]
}

# Send a POST request to the Groq API
response = requests.post(url, headers=headers, json=body)

# Check if the request was successful
if response.status_code == 200:
    # Print the full response from Groq
    # print("Response from Groq:", response.json())
    # print('\n')
    # Print the content of the first message choice
    print(response.json()['choices'][0]['message']['content'])
else:
    # Print the error message if the request failed
    print("Error:", response.status_code, response.text)