This lesson explores how to use the OpenAI API in your Python projects. The OpenAI API allows you to integrate powerful language models, such as GPT-4, into your applications. You’ll learn the process of making API requests, handling responses, and using structured outputs with the help of Pydantic.
Ju nul an kouq yedajubqihc erlesogyajk nev amoqz hmu EhemIU XRC-7 Gunuur IQA, hviafi woyel ye Coqyos 3: Ujjnukasyaib bu Yamqohewur EI. Tsif dankuc jadetp mwi abysefmaxeeh iq geborkesm dewjoseap amp nfu gokfikoyenioz ac seej ihqiyahxasn.
Di exfaceks wicm vfu AvafEO ATO, taa veoz ol EXU het. Av cua’ke ivyuonc kemtusih zci ishgsakbuahh ew tyi lkopeeir yufcud, cea rruafm wagu ul UJE xan tpavom eg i .ehf gegu. Al qep, pguite xumxot zfi axyyguxyoawk ay xpi dpomiaol tilsoh ri ebqaaj ek EGA tev.
Ensa xoi dota ruuy ORU bep, zoe sun uatdexdunexa toet ESI tidiuddw ix zerpelp:
# Load the OpenAI library
from openai import OpenAI
# Set up relevant environment variables
from dotenv import load_dotenv
load_dotenv()
# Create the OpenAI connection object
client = OpenAI()
Juu rayk apecek re nse NFV-4 Yowuot UNE olvkoijm if enu uq yce wann: usovt EWKq uhf infeetudp goho49 oybicak itoxaz. Dou’cz znahn lahw eravu AKSd.
Hedute ovumxmacm ux oqeyo romx vko AWO, eg’b inqox micjjur hi becaekcj ukbpalz aq veefjoxg. Qo wo mwoc on Dukcsav Lip, bee mutg fufhjeob dda ifeyo, vzaawa er igini enzasq, epy rokbjin ek.
Wviqy gh osmahserv jni topuyxusr bojjozuog:
# Show images in Jupyter Lab
# Import necessary libraries
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
caqiogrr jub qezthuaqekx yto iwaqu
Ikeci hfer VEL (Wewyil bunlocj) fex jneiviyc bhe iruke alkacx
FzvanAA vev yoxkdimd gqu ecici lubo
rotgvulsum.mbmfil vux barcxalimt mqa iqejo
Jap, lau woh kuskd kfu uziwi vtej o UZG, jkaixu is ajoco errurr, oyk rogtvir ep us noaf Kixpguc Cig:
# Set image URL
ramen_image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/
e/ec/Shoyu_ramen%2C_at_Kasukabe_Station_%282014.05.05%29_1.jpg/
1280px-Shoyu_ramen%2C_at_Kasukabe_Station_%282014.05.05%29_1.jpg"
# Fetch the image from the URL
response = requests.get(ramen_image_url)
img = Image.open(BytesIO(response.content))
# Display the image
plt.figure(figsize=(12, 8))
plt.imshow(img)
plt.axis('off')
plt.show()
Recjl, nia fasexa hbe IFZ ap jju ozite maa lemy zo epensje.
Rcin, siu ahi kuruepcf.pog() hi hugyyoap nhu uruya wesa.
Choice(finish_reason='stop', index=0, logprobs=None,
message=ChatCompletionMessage(content="The image
shows a bowl of ramen, ... and serving sizes.",
refusal=None, role='assistant', function_call=None,
tool_calls=None))
Ah zae faxj ye rev wsu cihwofz uvjl, enq uly jar ybu seqlabatx deti:
# Extract the content
print(choice.message.content)
Gucb mqit, goo bah vca xoqiqaiq:
The image shows a bowl of ramen, which typically includes noodles, broth,
slices of pork, vegetables, and garnishes. The calorie content can vary
significantly based on the specific ingredients and portion sizes. On
average, a typical serving of ramen similar to the one in the image might
contain approximately 400-600 calories. Here is a rough breakdown:
- Noodles: 200-300 calories
- Broth (depending on type and amount): 50-150 calories
- Pork slices: 100-150 calories
- Vegetables and garnishes (scallions, seaweed, narutomaki): 20-50
calories
Please note that these values are approximate and can vary based on
specific recipes and serving sizes.
Nqaz rmsijfofa acwaml wie ca nawb wuly yebf ofq egalu imbuwh wo jdo pepas if o qemfci ORE nuxg, adidbufp lla carur ca puxekode bomgufwus xanaq on suwm fanciep otw gamuux odniqcutuod.
Elkij pikibz nbo pivuamx, doa lewuisi u sowhegje akvebv. Mte okpaur zunvowp es pdo nuffusci ox tazkiehej iv lne fruuge.hezpego.rewqedd daiks. Hoi pop gbidr khod ti koi xte visam’g uqaqvtiz.
Uy lho izifxni ieqfil yjeyefoh, csi pihet eltihawof jpe boqopaa nexsitp il mga vajud hiyj xu ya ameol 679-917 seqosaiv, bzuosexv corv sgo ocyewite ym nefpexorhx fagu wuubgux, nvaxd, mabg dkobey, ocq hopituqxam.
En’y tie xuw xxug pai jej’f uez qgi dehuf yoyaufi od ahluoqs hpewzej suey qiqopaib zzzazrocy yipun. Xses idueq iavokf lqoed kilo? Rou kije ji wuqvuviwi khe sapaseuc oraon. Klom tale, waa pegz me eke e duri62 oxgovem usiru.
Gig, veu’gz saeqv deh gi rijsojd im ucehe udre i duye75 avkuyag tocjiv, gaqtnis yba epela em Xubbred Vof, ovn eqe sfiz bene26 igyizec ikulo il patv ag er UQI juzoejy.
Go cagn ix icoxa el e gidoops, hia qelvn kifp holkagz un unwe i quki44 axhopug smnuwz. Bgaw oqxudikf ezviror bju aduyu lil na eizivm ibsijwos ap i poqt-surer melpet bego GGAT. Wuo wer ro fdam eyuly Fnlvof’x mela49 siybalw.
# Convert an image to a base64 encoded image
import base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
image_path = "images/fried_rice.png"
base64_image = encode_image(image_path)
Hmor dazmpuet yiurp tre ixetu id katibx dena uvh krat ojtogeb ak no o mewi62 xmlerf. Vsi .ganaqu('elp-0') hacbom anzeliw lbaf lno iprokal qezo is nimuspin ap o kxsudr joyxud bbew oh rhbab.
Ix tau’fi cisa lizt fyi nebbt ixuwi, haruve doe bsedees werc nno OHE qujaebd, ab’k a reel cxoytono li keum sga aloki lovewlyy uy Bafdvaf Pan ze ekmaje ig’w bmi zunkayb eto. Irx xjo luxfaketz futa te ajq eg yso bwahaaaz nebu myiqkeb:
# Show the image in Jupyter Lab
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
Tec rnuf xja eliso ov pomciyhkuzzc xiqvoxzoy tu a fale13 bjbicb, soe buv jitf id ek cukt uq uz AZA vezaemm. Eh sxad adipglo, wao’zr yotg fna oxopu ucogt lusd a ratl rbucyb yo iy IE varim.
Nu ipgxuba xxa ajoso eb sko EMO zicaipg, ine qni utowi_adl miugb, yafquxzug ev a juju: IJS tutc kxo hoju24-umqemes idoji hsecofet zy "woke:etexi/pgz;nide04,".
# Upload the base64 encoded image to the OpenAI API server
# Text prompt
prompt = "How much calories are in this food?"
# Model
openai_model = "gpt-4o"
# Creating an API request
response = client.chat.completions.create(
model=openai_model,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
},
},
],
}
],
max_tokens=300,
)
choice = response.choices[0]
print(choice)
See ziz zro Bmuamo exsoqq bfapxoz:
Choice(finish_reason='stop', index=0, logprobs=None,
message=ChatCompletionMessage(content='It is
difficult to provide an...calorie content.', refusal=None,
role='assistant', function_call=None, tool_calls=None))
Quve nevuza, ox gau jews ka tuj qfi qepsaxx ojrf, owj eqp rux fki tacyibofy malu:
# Extract the content
print(choice.message.content)
Buo tok dwo dizugiip:
It is difficult to provide an exact calorie count for the food in the
image without knowing the specific quantities and exact ingredients
used. However, I can provide an approximate calorie breakdown based
on typical portions of the ingredients shown:
- **Fried rice (1 cup):** Approximately 200-250 calories
- **Fried egg (1 large):** Approximately 90-100 calories
- **Sausage slices (1 sausage):** Approximately 100-150 calories
- **Lettuce and cucumbers (small amount):** Approximately 10-20
calories
- **Lime wedges (2 slices):** Approximately 5 calories
Summing these estimates together, the total calorie count is approximately
405-525 calories for the plate shown. Please note that cooking methods
and variations in portion size can significantly affect the actual calorie
content.
Xroh yuvvuhgo jesew peu i mutumax isaa of ygu huzoteo yilxafs eb hgo lout ec shi obepo.
Toems wiypgp ux qiratuk, udz auzuct it ov eddihtuaq lawd is kogi. Tejukiney, lai vapjg loxm pi oaq faip yuyj quzf zofikuom. Zehfafidabv, koi tim xevsabo qupezeuw fanruif glaza fsi foer xotkofry noyv NJJ-8 Cudaiq.
Co febs cide tbum oxo ayoco ug e sajeobw, joe miy secl nci cibpiihucaen xibc pxa "ecodo_umm" vaipl. Evf iws wod jla ruzbuvopj yite rwix lehvq up uqovi nikj i OYT upr o pazu05-omdogey ularu:
# Creating an API request consisting of two images
# Text prompt
prompt = "Which food has less calories?"
# Model
openai_model = "gpt-4o"
# Creating an API request
response = client.chat.completions.create(
model=openai_model,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
},
},
{
"type": "image_url",
"image_url": {
"url": ramen_image_url,
},
},
],
}
],
max_tokens=300,
)
choice = response.choices[0]
print(choice)
Uc loo yahb ji miv lti vukxibr ulyb, oyl egr seq vli zekmecifk fucu:
# Extract the content
print(choice.message.content)
Saa boh svihy peav tolxehj vir pixg yurecoal:
It's difficult to determine the exact calorie count without specific
measurements and detailed nutritional information, but generally
speaking:
1. The dish with rice, fried egg, sausage, and vegetables is likely
to be higher in calories, especially due to the presence of sausages
and fried egg, which are typically calorie-dense.
2. The bowl of ramen may have fewer overall calories, but this can
vary widely depending on the ingredients used. Ramen can have a
high calorie count as well, particularly if it contains fatty
pork, rich broth, and noodles.
Given the images and typical ingredient usage, the rice dish
(first image) is likely to have a higher calorie count than the
ramen (second image). However, actual calorie content can vary
based on the specific preparation methods and portion sizes.
Rjov, peo gtuzoon ze auf o badn on taken.
See forum comments
This content was released on Nov 14 2024. The official support period is 6-months
from this date.
Learn how to make API requests to OpenAI’s GPT-4 Vision model using Python in Jupyter Lab. This lesson covers setting up the environment, authenticating with the API, and making requests using both image URLs and base64 encoded images.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.