-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai-api.py
53 lines (45 loc) · 1.25 KB
/
openai-api.py
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
from dotenv import load_dotenv
from openai import OpenAI
import os
import base64
load_dotenv()
# Your Prompt
prompt = "What do you see on this image?"
# Image file path
image_path = "images/red-ballon-image.jpeg"
# Initialize Client
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY")
)
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Encode the image
base64_image = encode_image(image_path)
# Create chat completion
try:
chat_completion = client.chat.completions.create(
model="gpt-4o",
max_tokens=300,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
)
print(chat_completion.choices[0].message.content)
except Exception as e:
print(f"An error occured: {e}")