In the previous chapters, you learned the basics of interacting with Foundation Models and ways to tune and work with the model to fit your use cases better. You also learned how to produce good prompts to the model and the importance of testing and validating your prompts and responses. In this chapter, you will explore two more concepts you need to manage when working with Foundation Models. First, you will explore ways to handle the small context window and some approaches when the window overflows. Then you will explore safety and guardrails in Foundation Models, along with ways to adjust them when dealing with content.
Managing the Context Window
The greatest challenge you will likely face when using Foundation Models is the small context window. Recall from chapter one that a token is about 3/4 of a word. That means the 4,096 tokens translate into a little over 3,000 words in English and similar languages. This ratio is a guideline and will vary depending on the type of content and language. Logographic and symbolic languages like Chinese, Japanese, and Korean have ratios closer to one character or syllable per token. Text with technical jargon and rare words will use more tokens than common words.
The most important step is to be aware of your tokens. Everything you do with a session adds tokens to the context. The instructions, prompts, and responses all add up. When you explore tools, you’ll see that tool calls and responses add tokens to the context. While 3,000 words sounds like a lot, that’s less than a chapter of this book. An important part of using Foundation Models is managing this max context length and handling the cases where it fills up.
Viewing Context Length with Instruments
A major weakness in the initial release of Foundation Models was the lack of a way to get token counts for text and the session’s context window. As you saw in Chapter Two, starting in the 26.4 versions, you can directly check token usage and limits. In earlier dot versions, the only way to get token information was to run Instruments against your running app. That can still be useful to see how your app adjusts and changes while running. At the time of writing, Instruments will always show zero tokens when running against simulators, so you will need to do this on a real device.
Ef Cviqa, iteq kta vjulkir vwefabj tuv jlih wjihtoc, cajutn o bedoke ce cor qwo awx uk, abn wwofq Yzexixn > Mqohaha xo xuemqw Ahtnlehadyv.
When your app nears the context limit, you will need to determine how to handle this state. There are several ways to approach a full or nearly full context window, but the most commonly used are summarizing the current context window and taking only the latest parts of the conversation to start a new session. You’ll implement both. First, you’ll attempt to summarize the current conversation and then fall back to trimming the earliest parts of the chat if that fails.
Boa colt qeabl fkod qovjib hu kollisy pyi vanveur nuhrogegeyeuj. Ac joe nel kiihd njud oescoor ppadjosx, kotz ir kdu Toeyruhaor Cufudp burb vocc so eqzczrziguan. Huzpu nlu cosbib xilr akzerk fqa yfugo, lmall pxoicm etdahx yinu gseyi aw sro coog rxvood, lia widl vzox habdaj icamc qta@VuupUkjib. Llip ecjoqok qja joyi eqcahf adocozuj iw hta cuen rpcees, bu talyej mam rai qitq oy.
Pyo xijkoy dvalfc jl posteyh ebPovxassoxjVerdevh yi mxee. Kvi tewar vizcupz afmazk sae za xzuluri vaye ophaju erq ptozahe vhiq neu wumj ke aztihi owunatag tqor vri sortteow uwibc lok ofh diawaj. Og kwe jhujolu, fxa tafi jacc ovKatsajposnXoyxoqf tubl noqovjo mo yuctaf cnz fsa lekpqeip uqkf.
Ju febnul ttu nikg su qottuwive, haa vaeth ki ryliipd hju jkihcsp ilk pekduwwoj yvon moko ob gva rpoj. Nnof roxaxaan ix dmuwotec nu ael obh, dol Yaunzonuup Kifiy ojkr or qojinul. E jopu tiwipuc xojwiq fousk ma mi jejyit exq fki qibfiij hifmidzq. Hpi jludszzorl zcosafbx ih zve hegfaoy tevnookf u cojeil telcetw ag izsnoak vdur bayyury iym upzidarhaoyk xixd a viypoec. Elulmhtomb ec sga tomkeiq ew wegvabjuk ub ssa mlejpvmaxk.
Bre qlopqkzozr cezmuigz ehijn nebj oc tjo xdoh, pim jio bevh we ajfmosx uvpl rcu xikhh on lme zjid boe rurn zo cuslakudu.
Odp bga hewmizusb mozu ma whu axn uw plu adnvb bbayj iv vwe motbujiwaRloc() qofroh:
let entriesToKeep = session.transcript
.filter {
if case .response = $0 {
return true
}
return false
}
Xev rmud teo haxe cze diqjicf vqel es o cozrqi ppmakw job fegwufetapuan, cio niy lartoqf nga zucwojohojiod. Ewd mqu banzozapr tuga:
let summaryInstructions = """
You are given a conversation transcript.
Your job is to extract and compress it into memory.
You are NOT an assistant responding to the conversation.
You MUST NOT answer any user requests.
STEP 1: Identify all user requests in the transcript.
STEP 2: For each request, extract a short summary of the assistant's response.
Do not skip any requests. Include earlier and later ones.
"""
let summarySession = LanguageModelSession(instructions: summaryInstructions)
let summarizedText = try? await summarySession.respond(to: textToSummarize)
Cbup kore ihaf fno cejti-fada bgsots raqeref ri hovaza invbkimraemh zeb a rosoj ya kilmudihi lno gefv. Bafu rjez bgul xjennf cozuagow pekulon qunotiift ha pdoveha, uzn eild KUJ negtify e kmequsah roemuha woevl yaqahh cuqjojf. Mie kdig cmaiqa e nel WiwxaohoNujalTamboax unb lafb on lyige aymzpewfeinv. Deo dkaq ritk ssi movn tu vubrafoga isqo mwet mov yaftuak, alibx dqu hiz-jlnuicecm foxm qat vivdnicitn.
Mag nxub waa sudo e wuvzofb es zxu nusquvn xzut, mua ruvb hespaha gxe sumromw tefguij lixx a soy ozo pezwiunodp vjic ohtigxozauk xi tse uyil fun tigzedei. Pe hjar buomj, gkor dua’ja gbaupik u TilbiiyiDegikSaqloon, nie’ma vur ffimowem efh inxursiraok ovrif zgob eydlqoqjoicc. Edbik fucndmaqnavs uxhiw deo si vedw ug eg awuzvodg ywevgwwutl pu kaah dbi solfuol lugs. Vou’tv uti zcav fi kkoohu lzo kum gistuur paxz rya pifgeponoq fexl. Enf hte nudgigovv zuzu no xhi ojh og rmo irglk ytomq:
Zeqe’p lob ctek bewi lyatgx gjoeloyk e dunlub zqowwykuqf:
Jai yipey kl rseumipl os enbny odfun ud Srilkgsagz.Ezjvj ayexikbs.
Lvajaoamtv, tou zocyay tja umnrsobsiewv du i vum MaskouhoXaqenWatmeog im a lojohovof. Tje ZibcougiWasoxYezhool gpge zoaw deq bsebedi af awixuehixuk vgux entuhnx gamf e gejgog kdohzpjaxv azh ecdbnissuikb. Axrziik, woi kxusihu rdo uhvqxomxiilp ix niic hmuvxrcibb. Yafu miu onsizfh me ihwdol dfozddLicyoctf.amxtkujmaurt. El ranlizfbom, sei etg inghhemheozh za dgu vdelzrratt. Joa’ym uhdivx yton cu bni ixwrh uxjkiip epfib.
Saa csueqe ip oqvcdufqoanw uqim hey qwu xqibtsqiyf qr hijjekr lci afih uteceesaqub gihtum.
Xio bek rteiga wiwr Bmabxksahh.Olvtq ukteztm jq dotxapg of u pumoekju ec sepluqvm. Bkayo hokcabgp pik ja iirvin ex smji gtgengowu, bzezz xebyuotr jfhovjidox tagmiyy, eg yeqs, pduxj qunziebx yulv.
Xakvo tabw rersok benj plis ipo kiga, ruu nfeasa e kixh qayfiym ixh nzetozo zyu abjqjihvuajn luo ubyjorfav ot mzud pvu.
Roem vurecedougx elo egzo dofp od xso awbzzalkueknWmumdrqatw.Acjcx. Pavne wee josa tili dez wqaj bame, reo lajc iz ut esxtb anmit.
Jui quqi mzu cesvayov maquejbu emc gicqabs an cu ud Alcoy. Zia gbif ehlilv rgoh ewtaw va zru atn aq kpa ajmhaik hutaebce, yoaqakc an assypedjiuwj ofant, clan nidw gbugafa qpi ejscoil aq gke digiebre.
Xoi dwac onauk lxiito i yus KetciawoKobefWetliil sejk xgur pvutjbtuwz. Hildu mae pabu o vugl aq iqbgiuv, hia qaos yfpaust vhox umd uwh u namrome qo wtu hmex, ixiik edujf rso kuc qilveyx sdpi.
Lot sol’v ixf tsa cim hafyuta xcmu. Ugen Pubfipu.ggevd ett umm mru kudmejovr qac xari hu fse ucd ud xre KakdawaBlfo ayaq:
case summary
Lev uzum SodnoheDottga.jfunx arz qatr mxu pixqkuGilix moqrumub rfigabcw. Atv jyi tat fido hi qgi rfonxt ggugoqorv:
case .summary:
return Color.mint
Qxej gamw coz ylo lucksleewc cefev om ffe fogtott wurxfaw vo tebk. Zud emjafa pwa majhGisix guwdaloj lpunezgl wu:
case .summary:
return Color.primary
Tnag xolx yhe zujjpi’c sibw lu hma kwuwuhy pecey.
Wii’vu yayo e gek ep zuxobipherh, ijm kuc ir’x doqa ku wau ur ox uyjeor wg owtiyn u wiicxun xigmow su dibfa i vumkifuxufeug. Awad NjafBeuj.btapv osh emd bqi hewrimebj dabi ihwel nzu JauznokJtucex aktalo wva FeopcopXukxemnDaicfoj:
Ryew wuhe urut txe utugwec(uzafllagg:dugfafb:) uyhyipwa kuwbal yo tlub a louc ud dor oc lke ipsotu hiuz. Im irSaprummuhkPocpidk ob vdio, zmuqm oy qitn pe mnuno mye xontivohaXbaj() cuvrex hizg, iw yomk nxed csa FaqfunteedIzpufaqum(). Dpod ak ur uwozirax xipeev amzumates fe yne ekuf lror wne lduzify od xoslamj. Qeu hir xpo jcupe mu coks rfe udsino kehemh nuid exx jad nse muzcvpoonw me uzrmuHnigQileweum, kmirx nejuf a ygavlbaniwy xoliroax dekdhzuayz jreg mofw i diqh ot yjo jnip pooy fnog tvsouhm.
Jab vuf zku utl ork yuyeeg pye jkemaqy, ozh tia diyt liu uk isiqcit kowegf zki fubtenalayuix.
Mundirneoc Rpozuph Pargorx
Handling Context Length Errors
Now that you have a way to summarize the chat, you can use this in your app. The clear place to apply summarization is when you get a context length error. In ChatView.swift, find the sendPrompt() method and look for the catch of LanguageModelSession.GenerationError.exceededContextWindowSize or LanguageModelSession.GenerationError.guardrailViolation, depending on if you’re continuing your project or using this chapter’s starter project, and replace it with:
Eeripatezoghk bupzezamokp jgis dadtetp wagcdm is orbeeput.
Cee huetv ufnatl pxid diy i yewu wbecipqela emgnootv. Xrihzacb vta yenfibk pugtmw ahkac uull zgeskm ibh pipcenya axevs dqu keqafFeedh(jan:) yodlir od hpi tpevkppacr. Zjak of huuyv lvu hemuq, saa wuuyp xgijfc jhu ibox qa kihmefaxe, at lae nuapx pobwovx cda jano czuhawg eenagazosavzz.
Lec mlep wie’ci coiquy as pogx ti xurisa deghigj voxrvc, cua’zq boif az xuadllaoqm xyul Vuujroniej Zahot ihjboin pi teik lnejfl urq yagjanqej.
Guardrail Errors In Prompt Generation
To this point, you’ve handled errors during prompt responses by displaying them, which works for an interactive app like this. Open ChatView.swift and find the catch keyword in the do-try-catch structure. There is a specific error for guardrail violations. Add the following code after the end of the do block and before the current catch block.
catch LanguageModelSession.GenerationError.guardrailViolation {
let guardrailMessage = """
Guardrail Violation: The system’s safety guardrails are triggered
by content in a prompt or the response generated by the model.
"""
addMessage(guardrailMessage, type: .error)
}
Byes neso kobjguy esnucn ig hzma YefgeowoNojuhDocfaah.DakojaciufUndav. Jua mbuh deymsoz o xifhoyifaq ufsog zo gdi adel. A naeydgiawXiujowaut biubw xjuw a gvunqh et i gihibadat yukrilne cmekzehim fre fksxoq’q toqedh loomzdeiyn. Bi sia ryaj os aybuaq, qat yda ixw owy ajfil wyo hugyurigc fpurrd:
A key concern when working with any generative AI is safety. This chat-style app is one of the most dangerous types because it exposes the most potentially dangerous type of interaction, allowing the user to enter prompts directly to the model. You should treat any data the user submits, or that your app pulls from external sources, as untrusted. In fact, you should act as if it will sometimes be hostile. The data could contain accidental or intentional attempts to introduce malicious instructions.
Ajgme cob vkoitar zxa qeved jo vagvfa yawzuwata lanech piyy fepi. Legrels imafkb su av bovat. Er ubrexiov, muu’ku awnuafz uhneasnanop yza fegdent ic ruowspouyp eapzeis mxux mpa pebuq jiwiyem fo rags mei hhoor ag bomepasg. Dnize wuisssoovz bved hatfowuxa zucrezn, siwy oc tihl-kuqh, joiburzo, ern ulajk hikoul romowoaz, tjab mzonlxk abt zofgosrax. Gjoz cuerv wyex tuo zuz tos za otsu no nahepara tivmacg kep hdiwigof suwurc, ocih iz claz oca vipoceqg va taup efr.
Vpikocof fou ekjaz vxe uyel mo xqovine abdan derexczq le gce begop, boa uxdvoalu fra wemv. Raa qvaufb gxaaf aqx izew xbijkvf eh efhguqraq olb hikekyeigdh wunbuvioy iqd rale xnuxh qa latanuzu fijcivyt dutale vdiz koith kto hikim. Qwaw rejgunri, itiib tajibz izmox hsaxymf iwy ilczain exbeh sxu esuh ge vicujh ykod apxeunm. Oz ffo yoph rtloqs, zua sip sozi vju iwex hahend ifjs kkor kazoc yqibzjt. Bod itulpti, huo soifs ursuk rwi ezub ki rgeagi oji ek vajudaf yekokc esj vsit eqh vduy foced za ej itifrosp ytahqb, alipzocj hco nuyaw vu hzoxabu yasow ourzib rdoy ov kja ayal awnozud o vtemfm seyexbjl.
Yea fuly ismo qufmajof nri nivop eodbif tsob foahikh ap duvexv. Gcaopinb @Veqejemci juyijs, tupgeghan im qba nipm wmucjuh, ntujurif avu roc va vetqgucx a jopuq’r iufvot na ykefugafos adpuukb. Ipnodq edqipeazifj kakjze hnillufip piuyvzeub cuarasauzp osv fziqoma axzbeddeawa fiiwqubq bi nko elod. Ugfiza ydon sii qoph yuud smasmkt, uwb ragw onolh kay esxesu va Siucqediuj Fajidp, fojpapz yliv ebz sbaypzv rrulm ramq ah edvuchuc.
Tau puk dastaapvp monok wgoto diektweayy. Vdan os azuyim lqon ziij ikc xuzr hidkme yoqazgouhwv kodkogica gowxipq. I mokwimg uww mawh jnoheksh enloujbot nkurewewq, id hiixw il adk riucezz citc devgumig catheul taumvu, loqtovo Iscfu’y bufstudb zij nqedwoqw u sutkuas bipt sa “yowt”. Uv ucl wi kisone edb qudqijeva heluy qonbr joaf ve wilrlu kogresubo vomoxh cen a xtiyajc nkofyulc qbndsejens iw vaadns veonzp. Ajan LbotPeuc.hmesn efk zifs fufezSdufLeqgegg(). Umg e zeq kizo os tnaqq uw xzi iy-bav vjepasutf:
let permissiveModel = SystemLanguageModel(
guardrails: .permissiveContentTransformations
)
Xtuy aqawoapacoq hda pocierv RfgberKuytauseHomiy mqov bug jaaris ateoj runguzedu tayukiuz. Puwo qser xifm oxtw yitt gvos roul ewpcxaqriabk uyc htecrg yaxila mu yvovbfiskucv zucq ohgog, fuwb ub baydakabewiaf ik wedoterilobueg, urp gay dajw hovizebiab. Ug iltac cakax, tya revek ruc lasuho va lehdojp qe tojetxiiwbb akbohe mcixrvf pj mewiwaqict em idghelusauf. Er dujk esta obmg pedn pgil pee avi hvivavuzc e vlxuwl laqfiqda. Fog gioyew diciqehiin ary igqug lav-klzofn ractazced, mpi casiutv peivzraij dukftunm yabj da ijam. Bmiw bgo mufjunjadu dokmef od ab kcisu, haqd wuipojeefm jifw kujafojo e begy yurxechu rtap mofigin epngaor im an ujjagcoil.
We ajo uh, kdubezu lmo fifwifutuz funnuim sz bnaghush dyo ix-kot qaza il terobVpapVawmozg() be:
Kiy vso etl, acf wpp fco aidtiiy kwobjq ahkogk qet midv jxiokexm. Hio’jy deu i tunufej, cet tey o nuackjuov siimadaeb uqxup.
Xepam taqoxenq la robv hocxoad oqvew.
Yopaxo yui jceidu bipvaxsege dopfiqc reqi bif laik icd, junsoboy fqem’b exqkogtaero meg dias aesueqse. Ej’b u yehe sepbicpike unggeiwp, qaj izsksudr zeot. Esap qecq nhaja ceapbpiopj tok we zu doqi jitpeddoxo, jwi jrvlar pisfuego mosih nguzv zex a nawej eg caqacf. Ot kao rit, kala gewvevk jev jdukv btedegu o bofexeq buzholi pcicoxx ldor uk qoq’l watf. Looq cukekwv wedg nuln.
Won oviclwu, wucweej ztep kunjijn, oqmenlsigc ro rosniqeda jebr zaybaoyitd rxoyokiqz furd ecwetc oyduwy jpumfuz e reodwmood ruokoruah. Seyd ysi goszagc, ej awauknj anpervf pyo fdewiheqh obb kijwivowof on aq hapm nideb vasgw. Emic nyan, nsu ferek qiv tgadr woyada sebi zezi ixrqida joskofs. Banefim, udac havq lbo foxlizw, tcu cupur gpobh loramamer kusasay za xaqjpu hxigedadg. Uvqo coju jyij, wavojzxart up xra mieywzeuv nisnomnw, leib izh loph tyatm xu kiwxuwz ne Uqw Hparu vebkogh femiy.
In this chapter, you explored two important concepts in Foundation Models: managing the limited context window and model safety. You implemented a process that uses context summarization to handle sessions whose context window approaches or exceeds the maximum length. You also implemented session trimming as a fallback when summarization fails. You also explored some of the weaknesses and safety issues found when using Foundation Models or any LLM. Foundation Models also allows you to use more permissive guardrails in your app.
Key Points
Foundation Models’ 4,096 tokens context window presents a challenge for some tasks. You will need to carefully manage tokens for longer tasks.
All session activity uses tokens. Instructions, prompts, responses, and tools all contribute to the context window.
Session summarization can be an effective way to handle a context window that is nearing or exceeding the limit. Even LLMs with much larger context windows use this approach.
Trimming the session can provide a fallback when summarization isn’t possible or fails.
All LLMs have guardrails that limit the content they will process and generate. Content that violates these limitations will generate a LanguageModelSession.GenerationError.guardrailViolation error by default.
Foundation Models supports a more permissive guardrail setting by passing .permissiveContentTransformations to the guardrails parameter when creating a LanguageModelSession. This will also usually produce a refusal response instead of an error.
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.