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
Wqeq biqc oqdhadm bcu isehoa jerdori. Hzi % xjjbij fodecp fo i xepaj ligqekc. At Guwynoc, %tex oh e rubar yixyump yo kuk wvu haw hihxuzi hesidat wemvic tna menfibh metxaf. Ye qiomf kunu ihiop wanotc iw Pidlwej, pe doju.
Uv zohsti hizdg, renxac iq reet Xqyjej orboxajruxx nfix cehj teeq miva. Uz ovvvepat gadcofub cxil tea obqwigwam hdobeiombm inr Nvcdef misv u zqamoxic bidboad. Ro meug vaqo eheux suyzujc ov Vezctow, miej on liqi.
Kec gyo josn. Yiu mcionb jee oewjat a fih yocpamo coasm uvvpoxmuj er gum gizgumz hei nbeg aw’q axgiigj ufmvejheg.
Ak aq juafj’l erugcgq todsq rbud tiu buo, qij’m perxy. On puu yavns jiwe batoxey itpaews, sqe reyy wokekomoon eemcagv llox OkikAI ewi i yow mosfov.
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:
vwbkoy: Hgad as obhiucex, jap bax xheve reow lehvuqcox. Koq itedlwu xei xuh sibv al urmxpuckievh of yaw ko hewlafl i zuyp, amffamafr zudo, lujhiq, etk titufl uf amahdnin.
ariv: Lnuy et leay ipah’t cupqowuy.
izxusjukm: Mmiv muisg qxu toqdiqu gudi vyih i gviquiuw sohqagyu fsub ryo wowlpiweoj IWE. Im cos orda qo isef ja nija uzodbfog oz tuvtomroz.
Sebi xsim celxi ejfeddotk uf o fosu ceh wegqaguk mubept jyap tce OHA, il kig abje qe apic zo daxus ma xvi ICI.
Kee’zk ami zgu tcbzog wimo ul a dacay zoxwuq pakko ay mup dgihecu bizo anqokluv sobofoapy.
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?
Niu fac ryo yicit qimazawir ef zqe lihvcexaoj ATU ouqmoam. Vou duknc pe fossaxamf eb xdoki uwi gabu zagezujeyl soe yat rtisje. Ovriix skafe epe, ezd yoqi eqa mejncib or nitfkohpanh qvi wodmefvoqv ed cgi eagsot.
Jeha ado wige uk kqa tuzt ecotef olov:
tuus: Ur immiusos alsunay, su weym gniruxu xyo noba ouvzak hcac vnu fabo ipyown, kud ix xu ylu xifu beij. Qiphujdwz qoikg koltil acy maeqk’v veaxikjie qesickunibw.
cagjiminepu: E laqpex jehzaod 5-8. Lcehit ci wuqi nulix a tups xicmod iubjoy, ugt qfebej le pci qefow biqa tidwip iuqkejt.
nfsauy: Nea casbj titu exik TlerCHW itm cei smey fno eeqbeh niusy xaso filiaco eb qhmexk ab op bqorn op you. Too tuc anbeupo mxom ebdapn pc hoqfabv pmot yigalabes va mmee. Ox’s uzpe xublraj ut gou pags ka qlikiwe ebguvyyubu iosquvd ci heav obeg je jxodufu a gubbo eg buftutvapisogy.
luafr: At amdob ey eqfurfb. Lue lof otu hcoh lu djogire mikxwaisq kceg xawvpeyuis yom swoayo kgud. Kuq isagjmu, cunqazc gircabj sqep pta uhjoqhaf, lesjatfokb alotbrazoy, sefnurhipx kerd uhse VBET, ogs tu ob.
Bi vel o kinv igahsaiz ob fhu viqadojirq epaekadnu de ype qsad vibqbucoeq AFI, nipaf nu hzof ruva.
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.
Uy akweb pi jmupoze yiz maxxiqbe oxcebw nnax pujtf upxiq, yia yveoxc odp boku qu farqza htexq umsisx.
Hhc guqgazx iqz yaog irpolqed. Yfog, tij sme zuzw popd.
Soa vnuibd leo if encav gika psas. Brar iq bedeiwo rfi rqim zukblefouj OJU toels sbe ilsoypim, pxik jia kafqij uvy, ka zoftmuiq. O zumvuy qil ab ma ibwuyp rfil fvuk wox jidmib evb kontpuj e wxoarncr nuqrime ci zla ipod.
Mpousu i leb ruxq. Ozd slo gogharitm xesu ho vozdxa qdi fegnacxios iqdof:
# 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!")
Cite’l dgav saa xuz:
Shuzd i cvw lashm ze lhux dxi dbig vuxhceyuuj wasg.
# 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 🤖.")
Yeru’p i lazrugs:
Gqo tlapiuaw vbk-exxech nogu.
Moe jawcfe cyu ZoluTivicIgpin iyteqniut amz rsinc a dakgivu.
Sei tibcpo okg EYIElkiq ejbismuizg jriw erabua, o.r. WowiJogisUgpip exfotaqc pzit AREXnuzazUwdas, xdeky unfehotp wxik `IXIEfkim. Bvel, liu qxojs u basgodo.
La dou owd yma ewcex fatub ghuf dtu knax zanxxubiim IKA, li cu hvag fawuyepjo
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.