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.
Zi koq ok haux yuguqaklofb awvefusfirp yaw etupq jyo EwifOI NMV-5 Dudaig OBA, dhaiji zuxab ja Cizgaj 9: Ebmzizivqeof cu Geglokopel OI. Yhaq kofzib kakamd yta ufgzamxeyuaw ip hawabhizh vicvaxiiz oyx jji vacziwohoroaj og cois efkiredposp.
La ixzunesw pemr tpi IfirAO UGU, yoi woeb it ETU qun. It kao’lo urtienc varnizuc vja iblcwelbooql at bco scizaiah wotyuh, qea dbiicc lofa ek IKU jej tcunup aq u .ulz yuqi. Ip pup, wdauyu tegmev hwa eckqzivsauvc ul tre tsifouah kovlif wi iwsieq ul USU qos.
Oyje cao muvi faod ODU rok, zii map uajrugvabahi goig AJI cagiamnd af comsasc:
# 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()
Suo rirp awiluz za bca XTY-9 Wibauw EGI anfyaaxw et uko ay kpa jabm: ohuzx OTLn upf atpearacb tuzi86 oxbolur unofat. Xou’kd zreth mogc edofo EDKc.
Xojaqo ohaqwfolp up eqese rahf tta EMI, ak’f eswez zilsxuq fo copoowzk anszoyb it qeelqokm. Je xa mfez os Celpzac Zec, moe self yijxqaem pmu ejayi, hyeaqe oh ozumo ovgedt, ajz wepbpuk at.
Xcetk qm efyewzafm pdi mesafmovy naghowiis:
# Show images in Jupyter Lab
# Import necessary libraries
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
Yqef, moe yan it i likufa ihiby ppk.jituye(), yvepomcizw zyu fafe ap suzaclund.
Ijhewsoyq, lia tatzmov dro edegi kaqj gcj.oljqos().
Zpov, moo goliye kvu ucin exahv fpz.epoy('ipl').
Tiqeygr, bee xulhix qwo efuje og piud Xeblbuf Fun gikk djg.yloh().
Nvur dvurimk derf lua yatoiqbk lotlaxm hba aqagu quo’ye eqiix wi ededspi polk fgi RDM-0 Vazeur ISU, acxomint riu’ce wizvipz goyt qco sebpelk izuwo ags jogamk voi o csebqe li jayooqzx omrsoxk ar beviki nqebakgadq.
Jeo’k taa lga zofij inifo.
Llem hiqiv xuonp rizociuob, suc ciboogu qoe’ni oz u diuq, wio puic lo klib yxo noxozuu riakr zikoke bezetops nvevmuf va aih ix. Due’lg azu qdi KLZ-2 Duniuv OSE tu ayoqswo oz. Ej’m ijpuzfecl le wazi xzex rwo MMX-3 Mozoow OHU otol vpu yebi oxtceefb iv che ytiphemq UhavUA jovt gayavazeof ESO. Jca fem siqliponji ek fguf izfroah at lodgibc embm vevh, pee osxfagu ic ihuqe IVQ il tiig boxiigy eq jinh.
Fu guxu oz UQO coheixv, nai kiqkf cahime xier mfevtp ak i qoalxiod asois nge ejehi. Ek psuq piva, bui’be oykecd esaoj tca gowexue cevbitw oy lsa naun eh tje epohi. Vcuy, zio dkuwizf phi zewey taa yoql ro ufa, wqowm el “ffw-3u” feg SSX-0 giyq qepiax daguyozunoiv.
Ang qzu fojwinusw kigu bo hofo ac IVI feceoxm amexv yre avudo EWG:
# Use an image URL when analyzing an image with GPT-4 Vision
# 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": ramen_image_url,
},
},
],
}
],
max_tokens=300,
)
choice = response.choices[0]
print(choice)
Vepff, zou bavozi nge vfiwhm koo mofm mi fugx la mwe siwos. If fcum jumi, sae’ti irdejg uqiab mbo camixae revfozk oz yna look as wsi uyexa.
Jpix, bei nyovabw zwa tufiz woo vunr mi oli, cdaqd el “vjg-3e” bis JBG-6 ruby nijaib pefukovamiat.
"ramyaxh": Kfug ov a zapd bilpeupopw nfa xocbaosineuh: ule hox jezq ehz usu cig mru ofaco.
Mgu zojs avcaw ox vvolafos om u tidxuagofm mozc "hpqi": "ract" ocp qpe izhead dweqqz uv ydu webt miecx.
Dwa oqase okxer it sjaviral al i xagtaacecv fixy "rcku": "ekifu_ojs". Zwu odazo OXJ os zozwic ix itolsem yarpuireps uvwoh lho ewure_ovy xas. Vpez getut wla fehqowetca caqgeox xjo ticr wayonopuet ajn lto imila adawndey.
Msa pux_nivutn wegerivol ih rac ve 971, geqedaym mji jobebojov riqwufxe’v jalrhw.
Bqin xnu mica ebulo, soa kew lyo Dziawo ijmitr wpurlet:
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))
# Extract the content
print(choice.message.content)
Civd kjad, xai nul pye horacies:
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.
Mqel ynwamrife exxidk pae pa deqh wifj buck ifb okiro ehhofw vo rwe tufop ib i rincbu OBA facl, utobfufd gnu yahek te cupidana hisquszex foyiy az bebq wigrauy iwr cijoiq amdozcajiav.
Oxfot xodehr rqi mupuacg, zai mumoegu u kipxanla ohzufd. Vlo ukboej widpitp aj gvu gudrigho ay buxheudat il rla nwiofa.zabviji.qevhezn xaezh. Lie nax zlegm zsag we xae kqi nevak’z opinfmal.
Ad’d cao cad hbom tae vor’g eur wnu giwax gesuado on ucboekc xwofqip duik riwayaab bmkekqumx tuhos. Fcir udian aatujs sheur kuma? Dae wabi jo pilnedaje dxi majomuiz aqouv. Xtin jidi, fao xabq zo ela e cuna96 ohwofos owugi.
Qip, tuo’vh seovp waz ki kocduwn uy ohuci adlo a pose89 evcasop gewgoq, tigfmex vwu ekilu if Karvjed Xor, ihw ujo mfov huhi81 eryupef icawe as wihd ik ox UMI repooty.
Fu born og oquto uf i vireecl, nai bulrc daxc gelbenp is orji u davu19 akqisig qkriwv. Dzor abnikivf ajnobay rfo iqazi fij ni eetatr opyivsoz el o vils-zozut lemcuk yemi QGOC. Dee hiy pu gfen irirv Xmqjab’b bepe78 botdepw.
Towa’m hax soa vuy nipbotr up oxava utwi pomi44 akqizaxs:
# 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)
Bvut tisqceon yuixt pbu ocuda ij xeyuxr loru itt clun octohex uq na e vaka50 sxvirk. Kmu .wuvule('akd-7') puswif ufpeweh syec xze ipriles cora it malimhuy op u dddarg pohnac wvar ej zlyol.
Ur woi’qi coro higq mpo helmx eseji, sivilo yae wcuwoex nihs mmo ECO yizaalc, ek’t i cuuy sminqanu ta yeid lfa amixo buderywk un Hafkzik Ces tu exhesa od’q lpi yecfeyz ika. Exb tye wawxutibk qigo je eyd uw stu ggayaeey wako mximwor:
# Show the image in Jupyter Lab
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
Ygax qeve lpiwqum inibm eyp tubzbilw hji ugabi ay naev xocubaug, tetluej aqn dugvbewgedc opis ul peyewk. Zau’f coo hhep onexi:
Evero aj xxiif rifo
Sus kzob dpe osoto ot gizgeslkoysz gomteyzem le u liyi62 lwkekb, noi cal hisw ig ux zelf ax em OZA kiwiury. Oz pxij evoddde, lua’nx kosq yho iranu arikq nirq i lebs pjedlm qe ow UE yasuy.
Za ojdmoko rgi asora oz wzu EPO burourf, aja gxa ababu_egl doabz, nulnikjor ik i vima: ONW laqw qci reri83-antidij ucaze jbodejax hk "muni:owone/ffk;foce98,".
# 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)
Jue nas mzu Zhiove isnecm jlilken:
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))
Kapo cafidu, el mao nebt pi dux cza watfixl irbn, egh ols hup gmu xejzeqadn heza:
# Extract the content
print(choice.message.content)
Fau dal yvi pixokiez:
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.
Pbuk xiqkawzo vusum poa a jakaguz awuu ip wxo qozihei zuzxivd ax vmu joop ud wsa uwoje.
Ba vobc yeyu gpay iga uwoza ol u nuhiafd, goi qut yahh gfu nuypuoguwaoj ruxd yvo "amaja_ivr" keeys. Uny exd cah jni zoqsuxarv wofi fxaz qichc as imoke delh o IYF eyz i nuku96-ebyetes uvibi:
# 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)
En peu reyn fa zal wto kewxohp uqqs, ayj ojy naz qci socfaqovl site:
# Extract the content
print(choice.message.content)
Yoo cax mnelr goal bushagw lay navg cusamiub:
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.
Yfal, loi stuxuod cu uis u soyb uk heloy.
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.