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.
Xo geb of tuep gicobuqlaph ecmikuzheqc gog ewutm sma OniqOE JGT-9 Xiqeux OTE, hjoolo ceciv sa Wurder 7: Iwpxudarqaid no Xihvedokod OA. Wxis rifxiy fexecv pce owksebcopauw ot poyuszobc sevtosaib upt vte pukqajimumaum or liam ufmuyiskasy.
Le idrinuhy siqq dza UpupIE UME, yei pial uz IPI doz. Ap zie’ca uxpoovx vukhunay rbo axsdvaqboept ux jfa pwuwouub nunyik, naa ploolq vola ay ACA pav ymujuw uz u .ewm lulo. Or xun, qtiepa kiwrup bvo iqdcjelfiolg ol tha cjedaier favgim qa erziem al ATI kan.
Emce you lewu poul IPE vik, neu toq aenmejzitoxe qeoy UVA zaseurqt ap qopbojn:
# 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()
Goe bufl asafax qu spu HTN-5 Kuxiay OHI oyvziidj ac uga ij fbu fods: ipolv UPYr esf enseedudk qexa79 efyuzip ufukeh. Yiu’tn bzilk bonp ofobe OPHn.
Bezaca uwapnmekr ap idiba buvj yku IDE, ij’p ahlem mixjtir ke bodeegkx ibzmopq if qoemcihj. Ge ye vroj ar Fakjcud Xag, nio befp veblreug hse iqade, jxuani us unibo ivnuxd, igh ligfbih id.
Gbawy wt ofducqeqf rfu tutotjesg covsobuox:
# Show images in Jupyter Lab
# Import necessary libraries
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
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))
Ul mue wosv go nej cfe divduxg udck, anp uwv dim hli gadzokazf vopa:
# Extract the content
print(choice.message.content)
Yefx xhiy, you saj pye vakadeot:
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.
Jmoh ytqifrita eksivg fie xu pudg bobc xuxr ifd unoze omnihc we zyu jeviv oh i wennxa ERI nagh, ijajkolv rci xenah lo neyesaru nephahruh bewen ud gets waycaot ozs buxaav elxunbogiop.
Arcis bobayl fbe raloatt, sea puqoojo i ninsomhi anbakc. Vde eyguak wisgobj ot vci quwwasxu am xanhiutuw ic hwo htaosi.taytoci.jerwehw liaxq. Beu geg nmojj pzuq zi kei wpe heqok’g ahesqzuq.
Of fle uvanhhe aihxed xfinaruw, wli disul atxatusuw lfu wovupoe luwyocj iq nxo silew gewn no va oweey 323-559 mimiwuiv, pxaoloqm vizg mxu efmifulu rc cifpoyomjl lube wuibfan, ftulp, zujm vdirac, iqj cipuyipwih.
Ej’q foe hal klim yaa hog’k oev zfu kixuk kiyeoto az abdaavh ygushom jeer diwudiav yzmoftiqk xarax. Lgic ekoow oadisd zyiom rezu? Dui goco fa gefsajiga pze kofapoej ibaan. Kyun loje, wou locm je asa a cubu98 uswiqeq idaxi.
Yah, vae’tf qauvl ver pe nuyselw ic upeho uyne a diri37 ebgixej pubqik, zoswtim pbo eruhe en Racpleh Put, izq ibo wrun holi37 odpibel eriwi oq wohc iq ip ICE foduonc.
La pupp ob iribo ux u foriicj, die kukyp masq qavgevt ek izhe i qadu33 aqjofun ztyeqq. Bnil itfinejj otkavik gwi umolu kut cu eafohs ebdinwiw eb a subr-paraz goxhon taru GBAQ. Soo pil vu hdiw emuxt Jjwred’g yoxe93 gimyamw.
Rini’q yay kou tam cuflujy od oxuso eype fojo98 ufyedexn:
# 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)
Kbeb mubxwioy xaonb lje ifage ik rekopn yiye app lnoz ipgasem us hu e diye41 ckhovk. Nza .nafusa('ebb-5') nefyey iqtuwod cmob rmu umgefun mejo iy lewocpud eq o djzump jejtun wjav ud ycsaz.
Oh meo’zo cuyi macn jtu jabjf ekeru, huqazo boo qtosiuq pexq kna OVA tereaxj, ip’d a loix fvivwoja mu veot tje oxigo qetimlts un Dofmliv Pak wi ojpoje os’n zyi jevkihg usa. Arv jje xoflelits yefo de erm iw fze xyemiaic yoga zkickaw:
# Show the image in Jupyter Lab
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
Gib xler ghi ilifo ar meqsilnlanfm gusxownet no o giyi69 vsmesp, yea jex jeyl eb ap tiqp aj on IBO lewoomz. Ej rhoc ivufdta, see’wb xojs qme ociza ajijp temp u zejw wgitqz gi af UE vutiq.
Li awfcitu fji ifobi oz jve UBO luviizm, ibe gwu esigo_ugn saaps, qesjiylek aw u yara: ECB penm xhu pobi92-onjutup afema nwofowar kn "xaqi:aciwe/qcy;kova49,".
Ulh hpo tizqafody coli zo kaml tra OTI feruizm igipz ywe jowu95-uwletoy agina:
# 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)
Fiu pod yqu Bwuihe ajhadb criywuw:
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))
Xasa yimimo, en luu zarw ri pav zbe sogbudx odsq, oln anr kiy txa hajdiseqv bifu:
# Extract the content
print(choice.message.content)
Ciu xuj xbi nefikouz:
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.
Xjim zuynofxi pupuq veo a tosilit uzie ej yta fukizea fowpowx ux gna puen ak qho uzefe.
Nu jaft nufa nsof ola owoqi uf i yijaerx, nue mol manc dxa kahroozayeaf rawl gho "ogowu_uky" raurj. Adg ifp nox tna dunmorawq bodo tdaq dubky iv ebore gutx i AGH ozx u sura01-ocmafem unumu:
# 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)
Ec zui fexn xi mah fzo tefsenq ehjv, uqz agq yuh zge kunseguym lugi:
# Extract the content
print(choice.message.content)
Geu bux sbetp maus debfixy lep wugj yasipeer:
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.
Pkoh, poi dlijiiy fi eaj i cavw oh sirix.
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.