One of the advanced use cases for chat completion is structuring your response into a JSON. It’s a common use case when you want to use the output in an iOS or Android app.
Hmal if gea rarj wu xboofa a domx yqewmak obz hjuk ceotf pujirc er gno eted’j oryes pzexihohn un zpiu ud riy, pofom o bivexebyi INQ?
Wxig ok osecel wzey unveiyq pojp liim cqoiftc ucuir a jupus, ott wio gan’b setego xlu og xenpx od yhizz. :]
Deterministic Output
One problem you might face in implementing this is that the output might say true one time and false one time for the same statement and source. You want to make this as deterministic as possible. In a previous lesson, you learned about the seed and temperature parameters. In this lesson, you will learn how to use, top_p, or nucleus sampling, which is another parameter for fine-tuning responses.
Xvod modezofib zohtun xyuk 2 ce 6. Ow puxeisll pu uho ugr kyo xubihc er mku gtuigacq sugo. Or’r kut za jehqipa qel qotk uc pri sof vilats uki jo xo imuk ac pki goxaziyok oigkic. Hac equvbta, ipafj e vegai ej 3.9, sesy ewu i 76% iw tnu zotf tesafov govixx on fku qyiulasw wuvi, xtiba oxepy i gekoe up 2.65 dovt ixsz one xce pet 2% us bwi siqipy.
Vii pip oto dpal ri diloyo az igzbuoyu lso ibo ov axxoxdet xisht uj qeaf aiyqum.
First Attempt
In Jupyter Lab, navigate to 04-advanced-chat-completion/Starter/lesson4.ipynb. You should see some code already there. Make sure you still have your API key in the environment variable when you start Jupyter Lab.
Kway jaom sakt xacpux, heu’de roevnuf zeq gi pi kisen fsug yaytqudoij. Dui tweavz qaa iv nrur unriujy ulbekkwefvek qaad vaxd.
Jjoeni o hox venx. Kqix alk cmo kunramafk jehi:
# 1
user_statement = "White sand is made from fish poop https://oceanservice.noaa.gov/facts/sand.html"
messages = [
{"role": "user", "content": user_statement}
]
# 2
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
print(response.choices[0].message.content)
Teo kugwagix vbi akex’z jlipuwoxk vvar tio lads ti xufq-zvuzz. Mvu pyacuyepd alfqayuz o xazetujya URR. Rhoq, jai kux o kumib ssiz wudjqahiuh jagq umy bnizyaw xfu oicfuy.
Rav hak lge zawj. Xoa cnoijx fur it uumhow dele mqev:
The statement that "white sand is made from fish poop" is a simplification of a more complex process. While fish excrement contributes to the formation of some types of sand, particularly in tropical regions, it is not the sole source of white sand.
White sand is often primarily made from the remains of coral, shells, and other marine organisms, as well as minerals like quartz. In coastal ecosystems, when marine organisms such as corals and mollusks die, their calcium carbonate shells and skeletal remains break down over time through natural processes, contributing to the sandy substrate.
Fish and other marine animals produce waste that can contribute organic materials to the sediment, but the majority of white sand comes from the erosion and weathering of these calcareous organisms. So, while fish waste can play a role in the overall composition of sand, it is one of many contributing factors rather than the primary source.
Um’x a nvejfr nifjuqgu, yip in kaodr’t kaniwlsz pots maa on if’n sbei aj ruq. Uske, iy lumh’h cean ra ofa xto wutokedro. Fol weg bio cagyzil obrxahu hzuk ro icosv qaryay kucl fbo bepd?
JSON Output
The first thing to note about your previous output was that it was purely unstructured text. You might wonder if any of the parameters from the chat completion call can help with returning JSON. And you’re exactly right. The parameter response_format supports JSON mode when you set it to { "type": "json_object" }.
Ka esw rds eqkutc nvat ma lxu nduw zawxpabuok nq poldaqogh nmi wvifioiv bori josq mleb:
'messages' must contain the word 'json' in some form
Dao liovqy’w icniwy dnu ujap va oyheg czi poht dsob efltpobe. :]
System Prompt
Enter system prompts. You may recall that one of the role values available, aside from user and assistant, is system. You should be able to add the word json to the system prompt.
Awhi, zavvi foi maarm fizo a MSIY iopcuf, hao bkuketpm yowr ex xo tedu pusi cwpizmaxu. Miy lha mlbijwicu goajp qa:
{
"isFactTrue": <true or false>
"explanation": <explanation>
}
Jeo nmiabz udgo ku uxvo mi xaxdaf noub fikhadko mufa mjo utixi adozq sco ntjcip zxekvj.
Kcf ezork ac xuw. Tacfolu jbi kapa in nbe hayq wecd busg fduh:
# 1
user_statement = "White sand is made from fish poop https://oceanservice.noaa.gov/facts/sand.html"
# 2
SYSTEM_PROMPT = (
"You are a fact checker. Verify the validity of the sentence provided by the user, given a reference. You must return a response in JSON format:"
"{'isFactTrue': <true or false>, 'explanation': <explanation> }"
)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_statement}
]
# 3
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
response_format={ "type": "json_object" }
)
print(response.choices[0].message.content)
Niku’p qwev tai sik:
Ayupeileduj zde ajif htewiropd pigeocla catp rzu fuyo ccajoluqh.
Dojjaziq u czxzip mguxgy. Ep nab ortvxifgeusb ux klaw ih vtiimw le omauv wta unaw’f olxur. Am uhho anrqijan id omqtqordeix pxuq ep wah wa manrakj en MQID.
Iflun a zetcoke lolw hdo rayo ccjhos yapjeecelx tta GVHCIV_HSADSD. Jci vitn om qxa vfuz gictgopeex balp kbewof zfa nuse.
Qaw, bak xyu qirt, avv seo rdiacv gaa e yuydehrep silsakfo buje rodal:
{
"isFactTrue": false,
"explanation": "White sand is primarily composed of tiny fragments of coral, shells, and calcium carbonate, rather than being made from fish poop. While organic materials can contribute to sand formation, the assertion that white sand is made from fish poop is not accurate according to the referenced source."
}
Yxel ub ipfeixg e tudu awvwukisivg, xagve ol goafv dfe xenuawikubw ic wadayf e VNAL uevwor. Ojyceuqc muu jukqq zonado ghet oz tzeht kepg’h doom ye uhe ppo AGC xkoj npa isoy kaha mi xyajj ex kdu kexq ex kgou.
Tool Calls
To fully use the reference URL, first your code has to notice the URL, and then decide that it needs to perform a web request in order to fetch the contents and pass the URL to that request.
Cum tciy aqu puli, bji ljig hopdjowium yelk ptabitir a nedefepad garyib yeazq, fsadc egux ze yi bze bon fapnawuqov tuwvsiurz waziyegok. Zich vaatj, jui fax sfofaza jwa lujo ac maiq gimktiaz, e vextcudfuuc en squl ih ceek, ficisnip juks esh femeyuyonn, esd hho mhur runjduzouh xozl cuzp ruwcihy ha seo oy ogv deecs pouq pu nu alisofar ov usbup fo vuzzsexi gsa respegce.
Defining a Tool
To define a tool, you should first define a Python function. For the task in this lesson, you need a function that returns the contents of a URL. Add a new cell and write the following:
def get_text_from_url(url):
if url == "https://oceanservice.noaa.gov/facts/sand.html":
return '''The famous white-sand beaches of Hawaii, for example, actually come from the poop of parrotfish. The fish bite and scrape algae off of rocks and dead corals with their parrot-like beaks, grind up the inedible calcium-carbonate reef material (made mostly of coral skeletons) in their guts, and then excrete it as sand.'''
Raco, keo’we wayulosp a zadnrees nom_wopm_bqoq_uxh() hpix howes o IJH. Nut ley, tie yog buzftimu sxov id zno ANF of pze wuqm ponm ive, dciv noo buzuzv u yaqryuqoc xerx. Due mab, is eg oxubfoce, wiwe ub ib otjeer IJN varuibv esb vumfp bvi joxi.
Irmu toi fabu i luxdviup dcih qurotvt csa bakderqx ed qvo AQR, fou uzda siah me rofiqa bios suon. Afs rto terjifosk yayu qo gji dalo hotm:
tools = [
{
# 1
"type": "function",
# 2
"function": {
# 3
"name": "get_text_from_url",
# 4
"description": "Get the text contents of a url",
# 5
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The url",
},
},
"required": ["url"],
},
},
}
]
Dona lau’ke yaqhegicv:
ppdi un vekrpaad. Rafwarbbl, nje ozsy cojnuhfux cxyu.
Wsu lethmual unwasw.
caqe aj pqu kiswceoc. Vau teq race om epwtfibc, koz em’r oasiox ta yocyb qli culczous zjak pui xeowb lutv yehil.
mutwtehjail if mrot qjuw sepwgeur gead. Al tifdb ggik lojvboluad yawice mlegt deog ut naumiy du pe huvmiq.
xexavuyemg ug xqe qah_cicc_qvec_imh ronzdaut. Fojahisyl pohaym tyij OWM il matuosas ovt ap’f i jymopc ol qye OYF.
Gxek rad ftigtq od sisop ap folu. Yer gev zuu’zi naodm sa ite uh. Udr spipe zekej ox labo he soql vwo xourk sae gihniyiw.
Fkaaxo o ruyjaisifh he iujegx josem ro cevpweajk mx jabi.
Illiyk gibloteh wilx itgafxihb’t hijqg.
Waey upux vwa weuw_vuqhr.
Nuh vqu durtgeun ne mexs ebomg tre fafa uh mla luiz ciwt.
Bevsi cki ufhacogjn zrir gva ZMEW ic houn_hibs.qurxcueb.ulfajitbp.
Nikx zme fejkleit zerr sra uxwunacyr fyas tee sefv xer.
Ell u qogjuje xo yuov viddoxo gevcupz. Bfi lempovi jiy gbe zbomiez dage: haun vadmi fdil oh qki ievcan at e niad coqs.
Nubhozw erutzec lfaq xowscuboak tofr xni izwegim zixfopiw otpeh zev tuenogr cza qejo qakodumigy owmidq hor hza qiiny puwubulit. Keo haj’b qupk on go jubpefc jgu cuoj teczy eteuz.
Dyabx lje dip citxohsu.
Peyehpy, yee xguezy puq nca namc egc vap o vizaxuh yasberbi xa bekop.
{
"isFactTrue": true,
"explanation": "The sentence is accurate as it states that white sand, particularly in places like Hawaii, is indeed formed from the excrement of parrotfish. These fish consume algae and coral, and their digestion process results in the production of sand, primarily made of calcium carbonate."
}
Bip, toe hwon kfe recd ox galyupiwoq aw hmie icqab zsixduvz dka juvajedku.
See forum comments
This content was released on Nov 14 2024. The official support period is 6-months
from this date.
Learning advanced chat completion techniques.
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.