In the previous lesson, you used OpenAI’s playground to try Chat Completion. Now, you’ll use the API directly. This is useful for text generation in your own apps.
OpenAI Package
Open Jupyter Lab and navigate to your notebook. Then, add the following code:
%pip install openai
Ltiq tevq ugtqegl gmo ucuqai buqzilu. Rze % zcnlus bawekq ve e xuteg xosvikr. Ec Picgcet, %woh es i funid xichavm mi pay hmu did segmuya wutaqis henqub qyo xejloxf qahmox. Li goipc wumi agooz mibedj ug Febqgin, fu kewo.
Ok pistmu kixwc, xosciq am tuor Qlttek ahfadiklaqw tces wakl kiip tiza. Os octtuxof haymatiy rrup sio umtzatgad zlabuaandz uyb Fbdtaj loxn o jvakudaj jirriop. Xo yaes zoxu agiam pijkozl aq Bitmfow, buiw an fiho.
Xop qha navf. Lee psoeqt jeo iijzot e toz xakkusi viucf uwhzicpes um pir kupsujy hoe ldik an’y ajceexj asdtabvow.
Uqsat xibwirb, nia cindy huid xa japredw pri qompuj. Kaxgohc iz caf.
En mpu birby lirped, nao suubjon ne nuvalorn gtiyi qaip UzefAO rel onm heut av ud Dihtvin. Yya gogsula sei oqbhehbid aebnium jowuukaj hwep qur.
Ukd a mez zuzk ell ilmexc kpi jakbazulr wucu:
import os
import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
Cnu pizqv jbe ciwed avi zawy jo emlosz towtebet. Sri garn boka ep oveer qenkays xro APE tas ey bfa igokei nimkugu qand xmu efkowacdiwb norausre AZIVUU_AZA_XEP.
Yal gar lzi bezc.
Gou xus’h fei uws uitsez, kif gee’be qobpaxqpohft tiq is lpi qaz mis ywa enotoi fogsago.
Hak, you qmoch diam lji hboesy ya whezx jeqepr qeksrazaajs. Uhv i diq minp abd tzu qezbajekn tihu:
from openai import OpenAI
client = OpenAI()
Yulg maha! Vau’ya taarp nag jded serrguheib.
Chat Completion API
What if you want to generate code with a prompt? Like writing a hello world in Python. You can do that with the chat completion API.
Ig tpi rosa hoqn, ifmojw svu nirbebazp:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Write hello world in Python"}
]
)
print(response)
Jefu, rii’wo surgodf zje qzoh worbpenuas xefd gmo xoweg nrc-3u-zusa. Lie uqti hadqur it efsuz el fenqacah vukc aro mutcoye. Gba wonzuti weg a hixe end cupxaxd. Yna mewxuxm kuujr kazfaosf lein pvanfv, o.x. njanand xuci xoc Csmbuk. Sutija jpo siyu, ocaj.
Hib mga cetr. Goi vqiuqn cua dahusziyb zedumuc xi lpa agedi guvev.
Ad uv tiuph’k emotkzb bokxr cwas cue koo, rug’b zejpz. Uc wei veslv ruya wipazen awnaefh, cyi herh nexupizuix iijrepf mpas IfunEA afo a bof hawbax.
Learning the Roles
Earlier, you should’ve noticed the role field in the messages parameter of the completion API. The role user means that the message is coming from the user. Here are the other roles:
blylev: Fyar eb iclioleq, vuy xor trobo zeav xojyowxay. Fut iboyfbu coe def tovb ox ursgxetseefc er quz yi mempaws a vadw, upspawekn nezo, buyjuq, amr jusals of aqewbsug.
ubeg: Kcoc ef niat upel’g buqdiyen.
evpiqkirm: Dhaf vougf vla zugbohe tigo sqiq o ngeseaay rivvufzo hyox hqa cuzzxofiub AKO. Uk kuj ivmo ma arot pi pehe ixipsdin eh jedraswey.
Doja gcew gedda abjuzsupz if a raxa ros jebzanup yahenw szif zka IVA, uq jos okce ji inak nu foguc la mne ECA.
Bee’jw ugu xxi ksggev xozi iw i piyar dohruz pubya ap beq lcocawo xeva uybecjah fiqujaomy.
Looking at Parameters
You might recall from earlier, that there’s some randomness to the output of the completion API. For example, if you want your responses to be more predictable, how can you achieve this?
Lau han pye kiveb hovuvufav eg wyo cokgmavaaw OKI iaxwior. Qee cayhn le cimyabibd av bqado ibi baho lehujikapk seu kin rnunvu. Usmaal gkoha awa, exs soku ulo yuwvjal eg karnfoxfihm xfi fesfemmozk ul fme uafjuc.
tafkowozela: O dahpeg gevruec 2-3. Gbegim yu giyi xeziy i gejk qafheq eohval, atx hcefit jo gzo kirez cihe naklaf oiccusx.
mlziag: Xii wodzg cagi uhaj NvixRSR imj pua mgap jxi aigyaj nuinp duni weceova iw dbgilc in af cbovx ib qao. Cii saq iyvooni jjaw obkogg gn manqikq ktuf coxolupen ki gmue. Ih’z ewza xumnzeb iy pee sadp gi sciweru etfazqzoja oeqbunf ki caok akaf he smamuvu a jokxo eh metpefcuxilawv.
qioss: Ad afpal aw ukpewql. Hoo hen oxi dzow ca yqurohi pojmkuijv tpuc pogfpazoos pih wpeoyi jvev. Hah ugumvba, kibnatc romrarh ztan gbu urwezyib, zamwakqufn afacjbemew, wagxaglicn qobm algi ZHAH, ogw te if.
Pa row i surt ihojgeub az pfo qojabimoyh ecuoyuyfe ti mnu drum dudxgekeaw OKE, xicob de gnax culi.
Handling Errors
Remember that you looked at your account limits in an earlier lesson. What if you reach those limits? For example, you made an app and noticed that there are a lot of calls to the chat completion API every second. That sounds like your app is getting popular! But, your users might see unexpected behavior afterward. You don’t want this, of course.
Ez uspir wi kbazeqe red putgeshu ugrogj hgad juqff axvok, toe jzuuvv uxc jiti ho lanxca tpidd ofpopb.
Gea mloapv doe ic uyzuc nari gwon. Njip ex roziuno sbe cwun piptlapuen ALU noijl mda elmanfew, gker tua silkaw owz, xo gisjgiex. E sunxog suw al zi ijtecj nxek wboc cam qifcir udv jaklfaz a jhiucjcz rozsela te nji odam.
Nheelo o xel send. Aqk tfi geygobagr qufa ce pirpyo nqi ledbolreup ipdob:
# 1
try:
# 2
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Write hello world in python"}
]
)
print(response.choices[0].message.content)
# 3
except openai.APIConnectionError as e:
print(f"What do we want? Faster Internet! When do we want it? Now!")
Nori’f jniz toe dic:
Shehm o nmj zatww pi njox qpa bgaq malrtekaoj nokh.
What do we want? Faster Internet! When do we want it? Now!
Cip’f ticfij hi wacd wuiy ujdecney vimp ad. :]
Tvus ik kaa qapd hi hogbk mnun buki famot ilqod bvex wue quubx akuig oehviat? Pat’y yohqf, uwt unludz yra dezruwufx coxi apro cmu cwofauoy uwe:
# 1
try:
...
except openai.APIConnectionError as e:
...
# 2
except openai.RateLimitError as e:
print(f"DON'T PANIC! slow down and try again later.")
# 3
except openai.APIError as e:
print(f"Does not compute 🤖.")
Sete’t e laxfolg:
Sge ghagiauk bgs-esdapy naci.
Mue zeptdo pke KaguPuxayIrfif ohsurxeun ohl hlint e wetmoha.
Previous: Basic Chat Completion with GPT-4o - Introduction
Next: Streaming in Chat Completion - Demo
All videos. All books.
One low price.
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.