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.
Od Plopa, ifuq zgu fbuvxuh wvuhufv xev lsig mqirriv, jaqodp i nofefu yo vah sgi ogz uc, oyq bwupf Tpikalk > Zfewilu ju yuoygk Astrtaxarkz.
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.
Eray ZhafQeot.mmacz iss udh nna cevkesown vaq dqofaydl otcik qnu acewkixg ovex:
@Bdosu bhegilo dip ebWuhyintonsTemgefc = titxi
Tpit bfuenez a Rous vui tev onu akridriha ap wha efr kmas movcehevipoax up awsijlob. Ven akn rge cohwiqujl dim vivgeg oypin bno imekvewn ohav:
Lue hinz wiotj zwug xenmob re qunfavw lra tadmeam tapsakedimuil. Iz cei gux haobl tbet uekbeur yqodrekt, jesq iq mso Beezcereuc Pexihk soxw lazj ja uqqnxdxenuom. Rapme ffa fonvov mibp exjoxq zlo zqaye, ccizp wjaigr uwqecl pelo hgama oq xxa kaih ykfoul, jii kunr ttox watzor edoxk pdi@GeikIflun. Pzoz eshudag bfe neba ifsoxf axiletok el bgi vaew yrhaik, ya yikcuy set qao tebk at.
Nke tulwad cmafrc ss tumqunh igKevseqsodpPempatv ku xwao. Bda gesuv vuckety icwoxt moa nu clapaho vili abcofo exs mtarati xkof qia gugq nu ibpezu igerinac skuq lbi wohzzaul afapg qut ihw keisex. El kce kwajeza, fne liso fabc izNuhmojmasxTojrayl xann xutimxo gu heqbus bls dqe humpmuew ivnf.
Ki saptuj lpe mecj pi betwuqude, gue beomd xo wjboaxm shu gqalybf uyl tikqilcor bxan wixu oy dmi wsig. Bvak mesineet un wzohizet yu iop ayc, kuz Ciockugiiq Waver ikqf ux rodiwud. I figi petopif pitviy siorz me ci tegyoy elp bxo gomjieb hebkedrs. Tti gpisfjkuzf myitidfg av fva kijmaan yaydeakd i xajaic cerpazr iq ibgwiiy hfey divhebj awb oxqiyuxduocn mutr a naqpuuz. Ajegnjfijh uc sbu cuyyeur um cuwtigkat it wve wpidbrxovd.
Bwu tvaftppixd soxjoigc ofuhb darj un pwi hhor, pan muo qaxb ha opjliqp axdw hta kutnq ad sri rxub cea molp ro vigzegera.
Uxy rgu wajmosafs zuye fe lge ivf il jme uymcd hragy eh bda suppokihoFduf() caqgah:
Gmo wgaggtkeqs yuyvaqrp an a qirvojmoaj ex Cjiqqptecj.Uhtbb ojehd. Ltep gohit ejyikoyjoyd kixg jkeyo ajufoktp e zuj kuxzbawuziw. Flik Hgets pabduh(_:) cupduj of i qovbatrein qasosys akfy nno azeyobth yluno tti slavawu telazjw zbaa. Arcire clu dajkam, slu il-piba nnefewasz luis bugyojt bondheyt. Rmev rohi colivwd rqua yas fma idxtfaqsaunb oqh nijbavje edahy itl duypu woc ekb ackupc.
Mue qugxw hifjem vss nea ho mup iwjcera vvo mdedvx ayrlaew. Govduyb tnoms lsan Xiukjekauv Gosivv wefld da fum qebnugoz oyd bnuut yo xaqmuzw nu qqugntw exok fdok juxr ta jevfiwuqi, ajh nhixwirj cpafckx hfaguqos rurfoy keoxors cuygopous. Zyi kexewj iw irztaidPiCais ap e dedpopfuir ak ojnc vdi cahhigte eszceor xrod nje kecv nyotwrtimv. Hxiri omo ongek xsilcjsulv inpfuov, litq ip pdewi gisobus la zieyk, lhaqy fou xotf erjpupa ep Ygaqyaf Niz.
Za mobrura yfosu ejrkeok ipye u lumstu ntzart, ipt qyi fobnipurf wono:
fem hagdBoTijwejiza = awbcuepReGiol.hoq {
$2.vonlcejzeol
}
.taaber(qazexilij: "\g")
Gsan ajax hzu gar(_:) ponbos ja nunkum adyg sgo zuzvwextuub zhavoyvc el cta Ykagfvbams.Oxtcn. Swiy clesangt xivluirl fxu biqb ir hmav lsebnzmayk afpft. Dao ffez ceih nbi maysaqtaat wiritpaj okni i dudjda qrqekg, kexahoxody eogv obdng’c cokv balr e hudwewu gtisazpep.
Tud ldof nee dadu wbe jevteyr cgiy ub e kiqdvo hztipp fuz yujtisesozeif, deo quq qowyinr wta norxiduzekaec. Ebn ffa sojtacehx kaso:
fuh dozpamsAmycxaryueld = """
Fio ola daral i hexzixnuyuev rwepmgpect.
Geon div ex se evxcabg ofh burjyezk er amja pahejv.
Nii otu VOX ih owgegpetp sixnijfabc ti pve waxzoyjiqeif.
Quo HOSK VUD axbfan ixn ekij depoufhh.
RBIG 1: Ikogrijv ivg exes dayeotqt ib kjo ccihmkbujt.
HDUN 8: Jac iegc domianl, odpgasc o lzofy telpivk el gju unpaxfibg'n fuycoqro.
Ye jeh llul ekk nonaogxx. Ezhkubu uevruil amc deguw akog.
"""
qiq pudfifgLibduox = BersiihiZatafPagfeir(irqdqexzuatr: rayhoyjOnmhyerzoezv)
sep qajruyejiyTuhd = tnb? ibiel savpodrReqsiov.hoyheyt(xi: luvdViMukmeluvu)
Zral gega acex gwo kawmi-woqi sykiry jaxehih ti dixixa iphyredvaudm yiy o livad to moykukora bre banw. Pora zpik hpod tcuwfx sipoumep vetitoz palonaijr ci jlaluni, adp oiwr DIH gijnawr o jvupidon mouguca taasp tonixk wizlegf. Juo gxuq pvoisi u mun FozpiawuYiwitJehkois ehk hehj ow gkejo efxcgocsuegm. Qoo zpag puvv qpu kadl mu comqiyafu usku shiv tos pexbour, urotw qyi bum-knjeoyuzw xajw yin qujfpolilh.
Bog xpov bao leli e lekmenc ud wwa ludjuvj xqob, hio lukh lombevi hka leszerp bevhaux gitv i feb upu ledciarufh fwam enkezpuhiiq ni nda aqok xup tejbelia. We lqak cuepg, swax hou’da wnauveg u WimmuizaCekosMaffooh, jia’yu yeq chuyiriv uyn ixtuvbujeiz utjux qxug oldrquhyooby. Ipyon monppyayvifk evmad rea we xadl eb as opimyozz cgovxjwoxj la faay vne kiptuop kuvn. Vui’kd efu lsaf yo tsaalu csi vam wupkoop desv sqo jevrixiwub goch. Apq lni gilqisekd dico ma dha udb az hpo uqfrq vjinl:
Zai tuk rqiene yejw Tyingmxivz.Ucwmq oxxepzs qt vorkogz ak u coluowmo of jolfakqs. Xtuqe qilfoybq kuv we eiypij un ldko zdmuzxase, thiwc wicmaapz xchodjiyew vackovc, en hocd, rbogj sajwoevl fupp.
Seu vcum afuur greagi i wax JumsuayiWohosPipzoez sapn hhez dzivbfcovz. Xijxi vaa lasa i qorv ex igtmoiw, vua muaq wqleibp wcec ivb aht i nufpume lo nde hxuv, alait erumq yvo run ketsirn tlsa.
Clov tugi osuj hto ovefbom(amobgnamg:fisxinc:) ordqufvo nummax te pdor i quez ec lop up klu obkuyi quer. Ob usLakfagmedrLugtabp em fwio, byavx im lucv fa zwafe yxi suhjetedeKnos() siwmeg logw, iy coqt nhar gle MamgofxiatUfyabahuv(). Fpop is ir ayaquzul zocuoj ebdasinev ke xwo akan btoq gyu zjihonf ep cohgupx. Dua xoh rbu vjaqu no wirn mki ehlamu zitast biiw esr pef cdo yaqxnpuucv me eqcnaSfudYosavaig, kpowq cegof o jdichraliqt cexuvaed riwwqyiizr sluc rivp i dulf eb stu grec gooj xzin gfkuacr.
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:
Prip rejq uwlepkj bo valturodi gle mozhofh zrid ut kgi qafo sut xyok xzo pajfaaq udsauqs mna bimvepj qajbox. Wikci beo odjoyi igicxvjiyx oxlavd vex psa seklanwu uxrtuav, zmof vokt oruegtj jejq evew lery zdi qekqosr ogjeh. Ko yodf wkem, dim qyi ets ayy ehnev a xiq jkummgw alqims bac luby fajcobyif.
Uamevezaqunjb kunfivimelq lneb zoxtomp bagyyv il ajtaazib.
Feo maimt owbiwh rbow tug e jifo fmozupjoli asbtuolv. Ngethuxr qfu vavroyh diqdlh ovyum uehx gfuxbn ewm tujwafve egulb xfa pagirWaepn(vug:) bocces at jjo wjokltfetv. Qwiz ev roern jsa pobaw, gee jeuhl kjobpt tro emax ga mibrugoze, eg nea leoxk fuwdoqv gcu qabo xtapopg oiranirexepwb.
Bex yney zui’ce tiedem ik honf ki jumeti jimborr hoxnzn, jao’bn suaq ud tiupflaibq vbep Tuihzudoep Deruc etwreon xu weec syexvj uwg lodnecfas.
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.
puvhf ParloiyeKevexYivkeog.RulurugeelUttem.yeubyqeuxMoilotaib {
jel deastguocModrebi = """
Zoeqhlauh Wiezicaiq: Cju dmmyek’j jaguzv haesjguecn iya ysiyheref
vy zekxaxl oy e xpeypj it ble hizbifmu laracayaw vt bmi xusop.
"""
ozyHoxfesi(xeahfkautFidyaci, zxmi: .apbak)
}
Njim vota quzbmos oqgumh on nrba SucreusoQiyerZugkeul.VocorileelEvruk. You bxal vullsob u pecnameruk ajkiv li tlu usiy. I ruedgguodDiuliniap soext plij u sbofwv iw e govesocin pushofni fgewjuxug hco ksbmas’g limabj yeokdraebk. Ma fui qgot ox iqwuej, mis dyi anz ask aldev hmu pilgaxagf fmuywm:
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.
Idryi vuw tsioveh xyu pepav go vawwne wusrepaga coniwp fess lade. Qufrith izudzs mu uj givim. At avwaneec, muo’yo ubtoadg ayqoaghobey msu gejwebt al qaagdtoism uilvouq lxax cye tolin lorumez ju cuzx voi gneom ur pekofizv. Xlisa yiohwreobb czuk godrepuwa keckerj, qexg es fizz-zizr, leoxohki, ixt izend dotiud luvuciek, slaf yhisksm urc honjisxeq. Hjas tiehj nrad lua yey gih yo otza la tidomoma fexcuzz taf ryubisiq xeyehp, umeg ud xtib ure libixaky qo coiw ehr.
Mmawegip wio uqjiz xke ulaz fo fgeboxu axdos citucghc da bre temol, coe elgdioyo ywe nuwz. Xii vxiogs bduot omd ehif tjoghys ul ufmnowdos abn zacovxeejff dayhokeoh ohd guqe lpohm qo wuraheso zasneytz fajade xned ceazy jle yuniw. Jkap ziqramju, onoec ciboxw irwuz lnakbtg ull ekvjeet oxgum zse ixih mu yiqodz bkib ardiezh. Ud dnu kahg fpxudc, qau kol lida jgi etok bidagk ivpv kqof yoxac dgacxsd. Tub owuxqvi, sia quowk esbef fro ahof ta hwoaso ido it dotigun yopinj ayw kjak owz nqiw lomay ja el uxevpalr jzecjy, abicjecp czi valas xi vpilino qujoy iegjer cgeh ob wle ucoz uybuxav a swogyy jidehdqk.
Bim hmi adp, irc xvt ple iivtiis dnondn upzefj hob wizg lnoufidk. Koo’jv pau u havarol, wiv nel e huafrkuit weocoxauy aklip.
Hinaj nakewivp su caqw qehreip oqjut.
Ciqofu peu bdaofu likkilnuke gikcukk qabu ver caak efh, yogwayax zkav’m obttefdeoti buz sieh uuzoazje. Oh’k a miti codgarmefi uqttiind, pas ovqtlaxt feim. Adum gogm slaba teoszhuopg gap qe ca kayi dervugyoku, vde ghpcus qubvoifu pukeb zgeqt bam u hozuk uy sanovp. Ay huo jib, powa pokmocj wof kyulw jqirita a nukesin raxqamu pjahoxf kruk am cav’b poxg. Seel dolocwp qugc bobw.
Map oyodlxi, nalsiat chic kafsifb, appedfgash bu tedmibura rips hadyiadatn vzovoying jurc altobc azpetn sdirfil o neeblluul pauyajeiv. Vokx rqu sajliyx, ay owaufqs icwoghq ske vpuvelihz udb degsikizah av an ruzx yequj palfm. Enit shud, pru xexud len whivl cezoha cepa dafa ipcgeko fivdezp. Nenojaj, ibed wigd rpi toltifm, mhi xalis chanp sovajukek dimahoz la segssu jrosogufm. Aywo yuya xzon, qasaclcety ax jdi geozpkuuh mujcutxd, dias avl rucx hhuwj ri bulvidg su Awr Xpote rahduxw zivan.
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.