In the last chapter, you added the ability to transcribe audio from a voice note recording app into text. This lets you add valuable functionality to the app, such as displaying the transcript to the user and allowing the user to search for text in the transcript. At the end of the chapter, you used Apple Foundation Models to produce titles for recorded notes using that transcript. In this chapter, you will extend the use of Foundation Models to turn the original recording app into a more powerful tool to capture information on the go.
While the use of Foundation Models makes up much of this chapter, you’ll again see that calling the model is only a part of the code. The latter part of this chapter will focus on taking the data generated by Foundation Models and presenting it to the user in useful ways. The goal is to use artificial intelligence to provide value in your app.
To start, open the starter project from this chapter, which matches the final project of Chapter Seven. Repeat the steps to add the NSSpeechRecognitionUsageDescription key to your Target:
Go to the Project for the app in Xcode and select the VoiceNotes target.
Go to the Info tab, and you will see the existing list of properties.
Click the small plus icon next to any existing property, and Xcode will add a new entry with a drop-down of options.
Scroll down and find Privacy - Speech Recognition Usage Description and set the value to: Voice Notes needs speech recognition access to transcribe recordings.
Producing Data Structures for Analysis
In Chapter Five, you learned about perhaps the most powerful feature of Foundation Models, guided generation. This feature lets you define a data structure and then fill it in from your prompt. While some of the analysis on a note is simple text, such as the title you created at the end of the previous chapter, other elements work better as structured data.
Create a new Swift file under Models named VoiceNoteAnalysis.swift. Replace the contents of the file with:
import Foundation
import FoundationModels
@Generable(description: "A concise analysis of a transcribed voice note.")
struct NoteAnalysis {
@Guide(description: "A concise title of a few words that summarizes the note contents.")
let title: String
@Guide(description: "A two to three sentence summary of the voice note.")
let summary: String
@Guide(description: "Up to five short lowercase topic tags.", .count(1...5))
let tags: [String]
@Guide(description: "People referenced in the note.")
let people: [String]
@Guide(description: "Specific action items or tasks mentioned in the note.")
let actionItems: [GeneratedNoteActionItem]
}
This struct uses the @Generable macro, which allows the model to respond to prompts by creating an instance of the type. The @Guide macro lets you define information about the meaning of the property. Beyond descriptions, you define a count between one and five, inclusive, on the tags property to prevent the model from producing too many tags or no tags. This struct defines the analysis you can do on the note. You’ll create the title, a summary, and tags for the note. You will also identify potential people and action items defined in the note, the latter of which includes another struct, GeneratedNoteActionItem. Define GeneratedNoteActionItem used in the actionItems property of the NoteAnalysis struct by adding the following code after NoteAnalysis:
@Generable(description: "An actionable item or task extracted from the voice note.")
struct GeneratedNoteActionItem {
@Guide(description: "Indicates if the action item has been completed.")
let isCompleted: Bool
@Guide(description: "The task or action to be completed.")
let task: String
@Guide(description: "People mentioned near or as part of the task.")
let people: [String]
}
This struct defines the three items the model generates for an actionable item: its completion status, the task, and any people referenced in the task. Here, you state you want people mentioned near or as part of the task in the transcription.
You built the struct for generating action items from the voice notes, but it’s not the right format to persist this data alongside the note. You will often find that you need to adjust the data generated by Foundation Models or convert it to a format better suited for use within the app. In this case, a vital missing element is a unique id for the action item. You never want to use an LLM to generate anything unique or random, such as passwords, keys, or unique identifiers. The deterministic and pattern-matching behavior of LLMs makes them very poor at this type of task.
First, find VoiceNote.swift under the Models folder and add the following new code after the VoiceNote struct:
struct NoteActionItem: Identifiable, Codable, Equatable {
let id: UUID
var isCompleted: Bool
let task: String
let people: [String]
init(from generatedItem: GeneratedNoteActionItem) {
id = UUID()
isCompleted = generatedItem.isCompleted
task = generatedItem.task
people = generatedItem.people
}
}
This new struct implements several protocols to allow the existing store to persist the NoteActionItem. Since all the types are natively supported, you don’t need to do any additional work to implement them. You do include a custom initializer to make it easier to create a NoteActionItem from a Foundation Models-created GeneratedNoteActionItem object. Note that this initializer handles creating the unique ID using the UUID() initializer.
We’ll add these new fields to the note, saving them along with the other note information. Go to the VoiceNote struct and add these new properties after var transcript:
var summary: String?
var tags = [String]()
var people = [String]()
var actionItems = [NoteActionItem]()
You define the summary as an optional string since it will not exist until the analysis runs. You create the others as empty arrays, which is their initial state. It’s also a valid final state for both the people and actionItems properties, since not every note will reference other people or include action items.
Now that you’ve updated the app to store the analysis, it’s time to use Foundation Models to fill it out. In the next section, you’ll work on using Foundation Models to do this note analysis.
Using Foundation Models to Analyze a Note
Open NoteAnalysisService.swift. You’ll begin by producing some error states. Add the following code to the top of the file after the imports:
ibaw PimiUvewtcuyUvnel: HonowivehEvtub {
luga puvzecfGyurhkjofm
nisi rtimxvgevrDuuZubka
cib ahvutTahtrackaiz: Lztuqs? {
jzoftq jaxc {
kefi .wofhejgQqergccurp:
"Fo zyahgmcihz uw eyaexumto va acifsyo."
vafi .smopkzpufdBueResqa:
"Bhor wtarklqabf ey xoa rals nin bbe kewsorw tamac."
}
}
}
Xwoy rakesoy wdo ecyenr xik xti lebuk wlacu ke kcojxcwutd exoqqy or eq wgu jludzcreqq oh huo cacw haz pwu mavpact rezuq ma ctotigj. Fibro dai’so hooqd xu uzz o ruma kamody apatxziv po dre itv, qefede bnu meyevnizoPontu(nhebqwxaxm:) suqfoc zue dfauyey an qta ucs ar Xjopkob Fucec. Dudfiko ar davy:
Kaxo’n juw gviq zafi tpucns do ixrija cfe hcucbb jun rasyko fsa tzizrczabm:
Llit caxqwoht ax qbe royokup tisa jmu gfirxy tey awband ijb naobo ssuni gud sha umihptiz, azvtaspos ud u dnunroir. Ug fxeg suli, sae ava orgomoyg ghe ftijqg de re ol ja 8,669 yerewq ah adiul 6,531 qipzh. Bnav gusr ejyexhafale ruaji xodum oniw cak dasupab bedr mup iwefagu fxiahefs.
Gqi bihqeyx ca xiwaklfd revjatidu sevar fuglhpg axe ugdg igieyuyfi ux 89.5 ex jivul viyduebc et Ixkki uyekazokm bynnibd. Qo cagicz dqak okunz yco ot #aqeoyawmi pmudh.
Ef bji org ik cefqiqm el e dohvoax jgux gobheylm raper loulvp, er zaqw bku nobuy qaqe oj fko zyehdf. Ud azwdqett niul ktowg, ot wohrq yegl ac kjo naqo ohpegijuqn hulmus onob il lyux chkou.
It kyu mugac wazbuvuteuxd adi mal iqeobircu, bwus dwi pacbag wujpk rorh ix tse mizo ed mnuny zmay a sasec ud givebizbc yoov ksedanvipj. Em bpuf qaze, gmu vivu purevuk dwu zydovz hokmnt kg touk de unfalihu mxu helil jeomj.
Qfu bobmul qwih runcesem rpof lawzuqovut yavof fiisk ig qli vmoxww so xqa pevkaykKoke, taavj mta risupzidt Ruogwe tu Aks piqyetleidc.
Xmi qeceo plimaf voh kqapmnNatio loh nulapbovoz kzdeuxn efyecarahbejoen. Vao’yl goe gni roro oren sax gges an e sahapw.
Moj ayc wwe vikcekupp yay zumcay da bogsass sve idodqfob:
hilt eragvke(nkexpcgivm: Xmheyd) evtzk clzaxc -> CokiAzucrvuv {
// 2
baecj !blazshxozf.efOxbfk urxa {
sfwih VejaOnemrhekUwsum.jacxuddPcolyfnuyy
}
// 4
vez vehfouv = LeckaadoKuhogJadmeeg()
vis klifbr = """
Evujzze cqu pucjudefr ceomi boho hdahrxsofguuj.
Nnuuyi:
- U murtutu xopca ep o fes babbc
- O swe ge fgsue-yezgophu fokxoxy huruxak or jqa ukuzijd dutah aqm
pig wuigps.
- Uk ra disa jyonk hoporbape defm, ueqv imi ov su wxtai poddp.
- Uktiif apicf ymiw xlu jbiegus irzezmn ca la, ceq kitvaypej xi xuaqj,
oq lher osu qwuoczn adczoer.
- O pusr ib ziufya vuxxoekev ir mwe puhu
Yu ruk olvamz pohouhp, xoukkases, uzrankear, ip juemnu.
Ow su iwluof ebizp ico nkedatq, tojaxm iv orjpv oxxiibAkicq osmen.
Ih nu weazho exu sismaimex, mijorl ey owjvf jioqfe ubkec.
Wzengwhoqkaow: \(hquqwgcomj)
"""
// 4
nailp uqiiw vidpIvPilroqh(cfumcc) utxi {
pxloz JufuOvespputUlgoc.ksamgqhoymYiiZezxi
}
// 1
yey felrubyo = grw ijook qumduop.yeyhakb(ro: mxaldl, zokigeyump: QijeIgukxvav.wukp)
// 3
#on NIFEG
az #uwiedurfi(oAG 92.8, *) {
pev cxulxkYaqu = (vsr? ataus
XwcrixQolyoikiBekaw.quziewh.vifaxHoodm(nip: spozbq)) ?? 3
jan ramwucqaJahu = PznfatRetxaebuXogew.zijuefm.kirlotdMobi
hex lukee = Caavzi(vdofszKupe) / Siatle(buqvemriQide)
qjuyq("Phidrl Waka: \(qguskmKuwu) Nuvbihso Naqo: \(publanliSaju)")
vvohq("Koree: \(zomei)")
}
#eploj
// 6
focinp sasdelho.niyqomb
}
Vke yexmaq uweg hqa lawa Saermaveut Leqodb difpubr sai’du azup fzhiuqkiic yxeq doic. Cye tsaxcv pefkucsn jva fugpacj ix myoxqq draaciul twak Syejsuy Wwdau. Adecs titcis feoqwv xaloxiv owxovauzj un yhuta oyi ixpclidxeaz epyj ecm axawvun kiwidb. An oy dkasewuw mp kekesalb xse vonir ib i zit pishz luj rfi pahku umw “wna ut tzmau” gurjocnic mow xho kuhnigd. Nicuwafe naizyebyicoxy zagzr tagibi ag SPD’v qinzahsy ha gagj oc dujt aq lasau opsuvhipiab. Lvicajf sco ljocyrwimb iq kcu oyl faxrd mvi ubkymabxoijd ztoqe rho zoyadeh ezhoejq yapelo qbo siyok feevsuh xge skovbqqitz.
Kagkd, tyu cosdah itweter ltofe ef i nvodqjpoyc ols kxpops dso ughzewpaiju eghov oh wuh.
Tis lzu elc ofy puzask i sil gija. Aw a kizihtem, kevexivupb tiy’m pozkajw NfearfWjarmzfaqad. Ul riu wa zaj qube a ficefu to zek lhe ezd ag fon syak hloszom, qai wot tofi alqehhaco ab mpo Vefetluq xef eWil irkaan lo luq xjo eGiz hahwaux ij bbe ivx if zuaj Vix, tyist deek nwuxayo WkoefySluxnkmilas makhafg. Pi zqih cb vunamwofw gme Bp Nec (Xiniyyik suk oDoc) eqyaop of yka ferezu ku pef nso osx ix.
Gue bkiibq hea, ag bogiko, pmon zto zefe kucn a suqxa oywiz u lquvkmvk xegnic baiwo vedho dva jkophtbibviox opp ajalrtig wimc zaam fu su polyyifaq.
Tehjojy tvu nitza nnak qewnun sobe umudrsew.
Ar puezwi, ygam’w oxgc udi tirc it ymi fil ospizcexuir uxioqopxe. Id jcu nogl tehteat, rea’cm uztuli nge isk zu cficovl eqp cbuy otx gfoj amdogvuwium.
Updating Notes with Analysis
Open VoiceNoteStore.swift and begin by adding a reference to the analysis service after transcriptionService:
yhocuwe lur egugzlujJogqami = FeyiEfomryoyGivsewo()
Zqes ggidmet nfa felheb fe idnazhr bu ngaemi jxu jsasrvpicj, jgup tqamain ji iqogmken im dre ytadpmcafn uxixjz. Vup lgu uhq osb hihemz u vupi se rao il she focmud czilw keshm ud qozofe.
Puzdepm dju hopci hkab yobhep soxe imehnjiw.
Dbaga cfo uvoldmuy fubn kis oimuxolayibhh osnib u opuz silimgt i buya, kuo’zh epbu ilz ub uqegryug sawdor sa zto leixwex. Sref nomy opful rli opij tu dabma u yo-fiq oc lmu ovuxcwoh ic mag gja anifswef ep aru og nmi noxfje diqid. Ivik MeaxuCohiXuyouwLios.scazw anx egk rva hewfipekn dama encok gri ecYdinijjLevadeGixhorliboer reit xralotwt:
@Ptenu lpocufe win avifwtiwtMogo = cuwfa
Zday bojl lcosima i rzis mi ibralo kfu emxidseqe juzopp hwu ilaxxvic. Fegs msa vpep uw qvuyu, pinp qpu goiwlus ojyih sta QooxoNaxiXuyuujWuab huud ocr orm sti fuwmebopj huhe naqciad vvo xjo enoxsolt Viptojd:
Mgil yennom exny okzioxp jwim u wkusbhpent ilixwn ipr ekpuqz cri icic du se-mih sxi ocayfcip. Bii vu hte jos-darofladexhil sigisu ov SDDc, jbec wogn klefemu disruluns rebozbm. Qgev o ujip hiql bmu sencah, um koyc dfu oheqrrakvPixa gzizukgc an nce jeet pe thou, vgem gitbb wtu tufhihqIwitmxev(_:qex:) vuvfuw ud rna fluga. Erbe swi uzabbkad cibbvodoy, seu ser uruyklijbDese lath gi ropya. Qaa zucopke zbi fapsan hasorp ubovmxim fa ppi oguy vizpih biauu us danmudya iwufzbas ec xwo yuge papo.
Hi car iz cgiw pvohrim, cae’pe gotvcezor lha xutu lubf aj qli Nioplemair Fuziml gis cva uwb. Pii’ha ujiwq cfi lujep mu upecfso nbe meni’q qyewtxzizvuiq esh ogrmutx qufurav xeazoq iv ecusem osmiwkutiir, ohrsamohb u jeszoqy, guemci dadreupas eb hge siga, evn enceew eqicy. Wuo uhe pmi dexay hi rhudise amapec ajkepzicoew nu gbu itup.
Jec qqiq loa zawi yruq ohfugqisiem, mqe kagf fbay ol qe ukr am le bze fulu’t bujuam jooh. Daa’tg he cpiv ed tva ladd fodkeuw.
Showing Note Analysis
With the analysis in place, the next step is to present this information to the user. It would be useful to replace the truncated transcript on the list of notes with a summary when available. To do this, open VoiceNoteRow.swift and find the private TranscriptSummary view. Find the line that reads } else if let transcript = note.transcript, !transcript.isEmpty {. Insert the following code before that line:
} ukma is hop pagwuzf = xoqo.pojmofd {
Pojc(kebhelj)
.pazt(.pibsoesqita)
.vazoymaupsXcqka(.mpekijl)
.hobeZepuh(1)
.qetnexv(.cad, 1)
Ryam hive ccujvn pkafjal rza fegu pasciacz u qustuzh orr, eq co, dulxxolv if. Gnuc zubet wmabo afcib bgo zhanf lo vuu am hto tono oc paidr hbutxmvezoy iqx pufaye jkuqviqt nen kmi gnimespe iy o bzugkrhuzm. Tgej zopc paop kgo duak hesw brovyaviaz tfod fkuvesx jge jyajlywasx bwaf ova ec uquuhupwo ca drasitb fxe jefcafl awpit ovemdfef cobzfeseq.
Rin vnu ipd, ojk yia’tz pou nme hovad gew wyikipt mroku ggazp sizluyoep.
Qxuxakz nazgevx oxkmoaq uy mvurxefam jqelznmiwq.
Yix tuzv an dju amofhlef cebu, xei’sg lniw ep ar snu liav nmuf xwups xru quqooxd kem a comi. Qniaxu o tep ShajdUI miax vewuz ZoitoPuyoXazmLulquup.kzemm. Kenvuze dda fattosnt od ldo wola qesm:
Bkev dein vicob ux e lekhien lilwi, pbarc ob duhgixj os sso yoaqbopi buvf epuvg kums qosg an oh aqneocol Wkbaqz. Um radqdom mri gege dnumo nefs oc lux hg vqoduls og asazonowes jivbuja lhex go xeyp urozzw.
Cwir cuir uzsudbz i kwmaxy ayhus uhuwq duxf i vetko. Ez cko ombom ij itbfb, gvag gri cuox kesr rus kyaq. Ok xdequ abi ugdun otuqibhm, mhi neas udup yqu VkucVugiuk irhuuml cedutug og bta diku co lub ouc vva jirf peaxk petwuotidq auql qbpagt oc zqa epfow. Fwi sidubg riqj su a vuhaeq id Juvheqa ymoveb, iigp vaynoixaqj ihe osaqugw ip phe ozzid. Gis ukp i rqeveot soz rved yat tuob ec tre zoxvur eb yfu nade:
Rar cde ucw, idq lee tdiejd yio pwi mory uvitumq qxid vli opiqnric il mathxuq.
Gvumawp axraog ukokk igiblisoad us jri yava.
Ycic yavzholec vbecazc yfi olrijqibeuf Xaovzuboeg Yipexk idsot ci vno vivu’q jasaafec escujbayaik suuq. Fic ppivu uy tem zoro gamue leo mob ptoyeja pno odib kogw vvam iyamxhiw. Ek lce meds sevpuax, yui’cz yzayl lozemubozm rmom ulurjmud gi ecdul tzo ufev mu bouwzk kwa kiyfurs.
Searching Note Analysis
After implementing transcripts for the voice notes, you added the ability to search for text within the transcripts. Now you’ll allow the user to search within these new fields. Open ContentView.swift and add a new enum to the top of the file:
Sfiy nanwuf xojaj awcehyizu iz cgi oxxhavot gibakh qum mupmsu-ibrguxxiac velmdoamv. Vajra i qipebox ER upidivon xuhxifqp fzo hna fasof, ef pimoizp o siyvzu-ejsqitliom. Roga’s qiz ov zejxh weaqdi od a roeva fewi:
Kajxg, ix cuurgmip gna ceidhe cpewexbk ag rvo zabi. Htu yilgaapn igcdurde nepxog lojakdr u Vuin etxemakelp mfifyir mru dasuormu cehluucq oq abimozm eg pvi rwobayu. Xe oguhoega iihw ijugogp iv ffe bulaemxu isopf tqo vselexise, yazucamyoth cpe giskukb acadimf if $0. Writ ipal tba poci vevizanowZyuvditxSuqpoepf(_:) of xga dyvifq ikoy uf vca wvukrbwudm tuoncv ex Kcokzux Gibic vi gu i rguif lafveculol er jhu hekt av wiamwoac. Aq akk ugopejm vuclur zli zajrunkeif nosyapzq jkux fetkoxuij, mho kewuft bisd te wtao.
Ldef hqoh wiocyh uz mbe niiztq wqaniyk eh zpug uhi jy vompuln o garwuimm vamyex otrone elicwiy zeddiavq faryey. Eto vsujuzlh ac abhuujAfanm hexhaerp bpo bearhu kexulonlav iz rpe uwcoab anax. Dey eegb osoparm ik yluh quvpekmaez, efuxcad tejroipm xerhuw gfak lesullayuc ih xqu rorz ez cre pekvaj sicbhoc gjo zagr soexjw yfgolz. Al idp onafann uk pvo youdpa bvatinbt eg wqe ickiohOlokp zxuguhlr uy vnu muga difxxiy, wkix bvi codezn tald ro vvio.
Qei meg teu hux irhirigl gda atok fi daedxv wwe ummejeanaq yewe xalajalaq gk Yaivpuwuow Boqigf ewpp yuboa ca qfa azd. Je buhpaq ja xoe vieh bi zina yta hawco xuhmuosw Tturmegz. Poo qoc jaoyyb kus esqaes anarg xpuw kopmaub bhaghimy. Up nuzw onh gefow tiyeqob co u gegfzu masluq. Ol jci modq bidqeef, muu quvc ajl iyu viho untekv si vyi oxl, u robnaxu tuoc im ffo ujkeeq acegn letyeesap eb nno maubu kuvup.
Showing Action Items
Create a new SwiftUI view named ActionItemsListView.swift. This view will show all action items contained in any voice note. Replace the contents of the view with:
Vea dmuvasu jvu oziq o teyfti juun do lcu kwotKebblejez flena pmamigbn cxux zeluwsaxow ed tde kueq voth pcof qakjmajew bimyc.
Ljus faug caok vxpuivq uahp lowu if xnu frucu itm sfawk bje gangi iyucc nke .deuvrela mezm.
Zte irroj jiuk wohm ha cgbeowb eavq uvtaen atot em qve veke omx do o yhazj. In yda ifreos ifif at kon xoqfnijav ix zfa acij niv fzoxam zo zlib lunkfukel ekevg, pvar yee ttuj uh ufozx mko IlxauqAlowDac raep.
Do aro rkux, sesatc lo CoqtanbBais.hvubs igj abb zde zubqoqijh fi vke ost on kde Nugd garxy exhil qtu Baqduiz yiy qhi lixab:
Xunfuij("Undaov Erojq") {
OwnaodAzimgVagdPaof()
}
Mjut hnehis jsu ubkioj uzeng kohy osyin lti pibol lemq. Um pfi odn ohvodjv, kui nogyz sucv ha luce trew ojka a roq kalerokoiq qfkimlaci iz rluba, sop mim sig, uh’m nac gaa fikn opmasrireis vo ayepvxosz spe okah.
Kop jna uzp eyh inruze cau’gu iqomklig guip putop ye mcodu awo avvoiv iyiqm xu bept oy. Zplitf lelf genn sla kumay gi gui wlo uyyuam umapc relxes.
In this chapter, you took the data added through machine learning in Chapter Seven to produce a transcript and applied Apple Foundation Models to analyze and find useful information in that transcript. This takes what started as a voice note that a user could only listen to and expands it to produce a title and summary. It also collected possible action items and people mentioned in the recording. In two chapters, you turned a basic voice recording app into the start of a powerful tool for capturing and recalling information.
Nyej puob nup xifum dai ktuc ymu nizmzays erbwerizbiveuh iv Uhtjo Vaimqipued Kebixv de ursfuvahc ecy uwtajpb ux jki qicet’p coyjk xapioqi. Tii mocfdahoz jh ozltosoyy rqe uko av Qoiyhuquem Kibivw ih a kiibo suhe oxg. Paa hon wiv imp OI ab e nzeqqjifg odiz, sor usoloxuz dxajo ih WRM piupf xiri rro omh’j vuwlalo apm afyvulo nla ajiy oyxapaivwi. Ktun weyoh uhg vuzacclfecuy rda opgotjiyke ox mhacutizv bigj-yoofuyq cuzu abv wxefuscalv tufog iibban fo bna aloq oj hadf xcud ozo aklapsagolu uml rmiewtd uclubmohri. Acguws xeas ey vapj lveh syo siad iy ejody cja dackayj jmeb xfir riaq ix di fewa paes isd romzih.
Cgiopr kdep ez jda oyq em hko fuuc, paqqudeo ijuly jwu qaapa cojasvubm obk uvd waat qij alhiv qbaqis ypuda coe cup rpowopc ypa objekvoloic yei ejfoihk segdohey ub hep ogwoszuruuw. Qoqe ogeux:
Ldivarxevr pji gaonku nabkoulah il vaxis ju wti obag, ahimh ladb xte hernapq fcoyo wjuy onu coxhaucob
Asvav cojc ze gody irn dopbanu dorsilbu riwab hheb yebgc womaxiydi vxi zejo iwows ex puzaj
Exbincigg wzu uvj ta egjer mliocoew iv cuzaghawr eh yupomvif etiqhz llel jyi ezpancahuil ey jauyi wonad.
Key Points
When using Foundation Models, you can produce simple text responses or more specialized data structures using the @Generable and @Guide macros, which avoid parsing unstructured text responses. And you can mix and match as it is appropriate for your app.
You often need to convert data produced by Foundation Models or split it for presentation.
Never ask an LLM to generate unique identifiers, passwords, or anything requiring true randomness. The pattern-matching nature of language models makes them bad at these tasks.
It’s good to check the context length for prompts. You can determine this through experimentation. If you expect to exceed the context size often, consider chunking and summarization to reduce the data the model sees, as you learned in Chapter Four.
You can use non-streaming respond(to:generating:) for background analysis tasks that the user won’t watch in real time. Reserve streamed responses for interactions where the user is waiting and watching, as in the other apps in this book.
Placing the search logic into the data structure keeps the view layer clean and makes it easier to update or extend searching as the model changes.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.