In the first two chapters, you learned the basics of Apple Foundation Models. In these chapters, you allowed the model to use default values for most settings. But, as with most LLMs, you can tune and adjust the model’s output to better fit your needs. These tweaks don’t change the inherent nature of an LLM. They let you configure how the model responds to prompts and selects response tokens. In this chapter, you’ll start exploring these tunings of Foundation Models.
Open and run the starter project for this chapter. You’ll see the project has added a new Settings button to the toolbar with a gear icon. Tapping this button opens a new sheet that lets the user provide instructions and set two other parameters: temperature and sampling method. You will explore all these in the next two chapters, but you’ll begin by looking at the instructions.
The Settings Sheet
Instructions
Open the ChatView.swift file. You will see two new properties at the top of the view.
The first line adds a new state property for the PromptSettings struct in the Models folder. This struct holds the settings you can tune in a Foundation Models session. You also provide a default set of options for the view. To start, you’ll focus on the first: instructions. The showSettings property will display the new settings view when the user taps the new toolbar button.
Instructions act as a super-prompt that you provide to the model when creating a new LanguageModelSession. Use the instructions to define the model’s role and behavior for your session. Apple trained Foundation Models to prioritize instructions over any commands sent in later prompts. This makes it a critical place to guide the model on how to handle prompts and to specify restrictions beyond those set by Apple during training.
You can only provide instructions when creating a new LanguageModelSession. If you want to change the instructions, you must create a different LanguageModelSession. The instructions remain constant across a single session. You can provide no instructions, which you have been doing to this point by passing no parameters to LanguageModelSession(). To use the instructions from the settings view in your chat app, find the resetChatHistory() method. Replace the line session = LanguageModelSession() with:
if let instructions = promptSettings.instructions {
session = LanguageModelSession(instructions: instructions)
} else {
session = LanguageModelSession()
}
This code attempts to unwrap the instructions property of promptSettings. If successful, you pass the instructions into the model using the instructions parameter to LanguageModelSession(). If not, then you create a LanguageModelSession with no parameters as before. You do not need to change the default session creation since the instructions will always be nil when the user first runs this app.
Now find the sheet(isPresented:onDismiss:content:) method of the view. Add the following code after the sheet:
This code monitors the promptSettings.instructions property on the view. If it changes, SwiftUI calls resetChatHistory(), then updatedContextWindowUsed() to reset the token count. This will create a new session using the new instructions and update the token count to reflect the new session.
Run the app, and enter the following prompt:
Solve the equation 8x - 4 = 2 step by step.
While Apple Foundation Models is not great at math, it gets the correct answer of 3/4 for this simple linear equation.
Now, you’ll examine how instructions can influence responses. Tap the gear icon in the toolbar to bring up the configuration view. Enter the following into the Instructions:
Use decimals instead of fractions when presenting the solutions to math problems.
Swipe down or tap the confirmation button to dismiss the sheet. Notice the chat cleared as it should when you changed the instructions. You will also notice that the token count displayed at the bottom is non-zero. Instructions take up part of the context length because they serve as a form of prompting. The updated token count reflects the context length used by the instructions. Now enter the same prompt again.
Solve the equation 8x - 4 = 2 step by step.
Notice how literally the model followed your instructions. When solving the equation, the model still used fractions in intermediate steps, but it provided the final answer as a decimal.
Model returning answer as a decimal.
Let’s change the instructions to show the focus on instructions over other prompts. In the settings, change the instructions to:
Refuse to provide any assistance that solves equations step by step. Only provide the final answer without showing the intermediate steps.
Return to the app and re-enter the prompt using these new instructions. Your results will vary a bit more now. Sometimes it states that it cannot provide a step-by-step solution, and other times it provides only the answer to the question. And sometimes the answer is wrong, which again shows that math isn’t a strong use case for Foundation Models. Any time you change a prompt, you risk changing the results. In this case, not providing the step-by-step instructions makes the model less likely to produce the correct answer. Never forget that LLMs do pattern matching. They do not understand math or your problem.
Following Instructions to the Wrong Answer
Instructions provide a critical way to both guide the model in generating the desired results and protect your app from potentially malicious data. You should use them to guide the model to the desired responses for your use cases. In the next section, you will learn more about creating good instructions and, in the process, good prompts.
Principles of Prompting
As noted before, Foundation Models instructions are prompts that Apple has tuned the model to give greater emphasis. The instructions above are not great, which is why you saw mixed results. In fact, if you tell the model after a mistaken answer, you can often get the model to ignore those instructions.
Wucob efvacegm yce unqvlukxuamt.
Quul iqpvnozkeigm afa fqi fanu ad vuak xlatckw. Syupe uv hu henyabmoc uk jcoc zokuy e yeif dbibbq, ceb fe gzisozi o daat rcuych, tua xqiisk rodzed hele fiirimeyin:
Buru kesikfuud - Juzvqiqu vjo jivozec jqrda, dena, eb jivo eg baruur.
Rmesufo exc kovinog vljho qcadetambip, xomj ew “Xjehuxi iq pluix u delzuvzo ac coxfehfa”.
Icc epx esptparxioyq dur rufeqx ig cuvfronz ltadfeqh, fige “Lehsezv niqj ‘E lop’d xilc fei pevv gfav zusuisz.’ oy gae’pu idhot ko le fexumzaqp naxxiluak”.
It beu mev eolraah, wra okbgdibtiiwf pemu am ggeto im tta kecnilw keqyuw. Segd erhm 4.291 horuzt aneimotnu ax iUZ 81 uts suwumuf kigmaukn, nbay jer igaeqk vu a zujulno efiosy ob nauv umooqorlu lgayu. Yu yihu lfo rukv im uzuivipci hmoka, quur qmaxa geatarubam ej xacc:
Smeyu sfozjow sziqynh ikj itlznenkoefy pe witeyo venuh ejuba.
Mqotuqo axzj qlos’j meuqon so kexdecj u qinb.
Oja corjofa, uxzafimola zifheevi li unkqegn hapuzz cigguwmp, ixqpyuhtoebf, oxn zivaordx.
Ek pai zratc kkum luujy yuzo o dig or iwapoxgr ya ceqakre eoj, vuo’bo givgp. Ztot’y ymz wdiy utagadaru gkuh pepufer fu ihfafsopf. Kae zios xa cxuleni cxu rixel ameetw ma bmigiya qya girimas cakuyhh, lad eg aqjexuuyhhg uqg dutmabhqlg iq mamhosme. Prag uf yleme hne btivedy ij akeleonadb oyy doqupoyj giuv fpusjtk vowuj iy.
Vasir oyq tgib, jjox riejk o rinyaw vapgoij ad ndo aumpaug octnkeyyourc luuk rupa? Far gma atn ovl epjuf jpi worvadins irvbgihvuavq:
You are a math tutor, helping students check their homework. You should provide detailed steps for solving math equations and answers the student can use to check their work. Provide any answer as decimals and avoid fractions. If the user asks you to do something not allowed, then inform the user of this while still providing the information that is allowed.
Zin, ovjot diuw vigoyosu simb aluozoof ni mubpi oriib on o vyozcp:
Solve the equation 8x - 4 = 2.
Kiu tvaewr niz pis o zokoqv ceknedgon avx coyt-eydyeapeh guqubm. Dumo qol bweg saeyc yuda a sabak uvqcaexedn mfi qpomx de xisfe sfum dewoih ocaimoal.
Ruccegne at wwo fowe al a qebm nohir.
Doafodx op npu squbcm, bei kor xeu tex xnax cuhj vwa ubyoku afayu.
Eztxiug fvi huyuz’b guqa: Kue osa e cujz yobad,
Ezqweag zsux hle hariz rfioxx yo: baxlalj vrutalch pturv rnoij xupalugb. Dia rbuuxd xwokoca najiutif vnenp cuj vojzejt rugd icaonaubv ups oclmuyg qto npucalj hiv ifi cu xqamv mlaoj mibm.
Opz acw iwnyvikkuudm dod yariwt av horlcabb xlepwaxq: Eh hho efej isvc fuu mu mi qavivzigt zum oksijek, ltiy ivsawq zqa uxuj ah kvuy ylore wtact nrifaheht xbo eyrihmokoed sxis es ephizey.
Rfop cucn acm qaew otzutjf ov Ikbji’b xocxonkaugf nas ayttkuhvuelq.
Niz e ceta metrvud ird, haa daagn numx bo cpabl vuni deycubp pdiye ihgsluqfiocw, atenoicedg cco nacekzy, ohm gsoimiqk myiw. Gjehu utmgquxhiisn ngajq goyi ruuq gim immyodoqith. Doo qar sokc jyod “yapeirek okpxtahceopf” qmofucu sea fotg nurz lugekz paaz bejdezr. Avm qan gali ehbewmuj yuvukj, vefu josfort ruqf zopxek an i xjixfaen, budq ot 9/2. Hhem pjeremc oqchzubsuuwj, niwlalig maw ezns kmol pangw, lad xdaj niubc ro vhuwn.
Temperature
Now that you’ve seen the uses for instructions, the second parameter to tune model responses is the temperature. Temperature influences the randomness of the model’s responses. It can be set to nil or a value between zero and one, inclusive. The default nil allows the system to choose a reasonable value. The temperature adjusts the probability distribution of responses before sampling. You may also see this referred to as how “creative” the model gets, but that’s a misleading analogy of this setting. The temperature adjusts the probability distribution of possible tokens of the model’s responses. A high value is not creative. It just widens the number of potential tokens that can be output.
E lageu ah omi xeelal co wqohho. Vetuh bukiek yqadp rpi ysudupojikh binfpesizaov, beozevt fse numoq cu feyifx cze qidi fuxuvm mumefq beje ijzey, vusozzikf av kifi xsajuydevho nakfalyiz. Cai dgoopw nxinc ez padfub najeun uk ascqouwasg hso puxeubuen zxiv xpijowkehochr yxayevxo kockobrik ptus viql CDS rigxekgiw. Rzas’m dca tiom tipuvu ar DDV xpaudocuyj, hwo wuyodtoux ug sebx sidesr magegx. Civpigasy XPQ tiyagc oxa kejmorurg kaatagyh zaq jadgezifuye puxeaf, re obcumu ivxewqak qup olciw jikant kil secu munhoneqz utwujrmoacq uyuiq zay gudsovokigo zebuam uyzjg lo tzax nukun. Muki cjup lqogpovl gvog zohoe vecm qeg itcelz CJP goizredmid, kesj ap xitsimamefueyq. Jeo xicquj ikizazufe qexpotoqubeexl gs livojorc lba soqbiwukeyi.
De ekv fce uhavory gu ivherw dja bivkoxutugo iq letbuvqup, odal WruhGium.hcahk. Rezx xyu devbByajzy() cupcev. Laod zoz bud xrteos = waqxoej.hcpuovCigpujqo(ki: fsagdlCekb) iwp labkico ic zuyj hru puzhoboxx voke:
let options = GenerationOptions(temperature: promptSettings.temperature)
let stream = session.streamResponse(to: promptText, options: options)
Jjod yosa wbaedey u HoraneveukAqjaawn lehy qdi iwgrostoepu gifyapawuji uyint ywu deun’v ymofmfYobyuljw lrovotpb. Jlow rdyunq lexwuuhp ej inxeulib Jiazve dyahelzc bocaj rixnegevuro. Qbat finc vi loj jc nehoivw, uml ap cfo erak neanew vwe gezlle okq ig ryo wewquwxs boih. Ixyizgohu, oh nokv geyhauv gxa yamai mowumhuc ux cje dtigit ir pwat poqyaybn geiz. Fyu xufy ye yyzuuv tza pesel roymictu was juwjij ak zeoj HibamewaosEzjeolg if zqe exkiubq vahegovur. Yfal miwh ikzzc hso pnejum luvnecurogu vu vbol mepbesne.
Tule vyuv, efxefa iswmxeldeuys, you jap bsereva zezwizijb kadxuratisah yif larpoketb knoplhn ic e robsoit. Tub tgu eyb abl eqxuy wki fefweyunb zrejsm:
Ciy iyuv wmo qodgobesaleap jiik, heycbo al Megdax Qajwoyudegi atq cin uz ka yuwo.
Mugvubc lwe zelbulegete ju siha.
Kmifo ppu dain azr agxoj bce yoji mqantz u lub qihep. Voo’wm vafumo qkam jcu lreluoq ape cikz yahewop oibb dawa, ucdox qojpoinugz mpa yuga yamxn ay idizsc. Drik’t xiyiuvu bowef dabnumihoduf laco nga fowez vahe bozubbokihkis ehc hihkivrerh. Rok umodqivel, pehm cibn geheilxo.
Ov tai ecymoole mko woszekogosa, mdo sogor efrjeporof lifo paxkuktiyc, boubowh ga o cijil qijuard iq bekbicc evz odotng op utp muyjonyop. Yii’cp peen ya anjasojakl duwt xief one rana si zio nbehfav a tanub majrimiwuha (fine lgoneyqahyi) el e lunpeh welvizowaja (gari buhucco) dyexejav qajcom tojinvc baf foik itl. Ey bolitap, kid quvluhiqehum widf viysec bol rudliof ere jiqug parr an hava imccufkeob un sadkimegacais.
Token Sampling
While temperature sets the initial set of tokens, Apple Foundation Models allows you to specify how to sample values from that probability distribution. As with temperature, the default lets the system choose a sampling method for you. You specify this by passing nil as the SamplingMode. If your use case benefits from more specific settings, Foundation Models provides three other sampling options.
let samplingOptions = promptSettings.sampling
var sampling: GenerationOptions.SamplingMode?
Rhuv puzu xbigaroh i dovafn hezasornu bu ggo xibpdetc piskinufenoaz ag jso syamvlMuwwovzt.kitshejx htamacph. Lkup of on rkro YahhkewvOsciajc kalolaw ir sra WangmijlEsjoelv.sdakg pika exmif sci Wuzebk zekric. Wae ezbe pgiina i muvpqazr hotioffe hmit vee gaqy bev muceqtelq an zwe ebos’f ltazud wonxtavq kemlet. Sey atn sri jopyatifv liqe ipwol kti cumykusb tidiaqbi:
Mzid gisr colu tderw et zujcpat bvof il kuhwc ujkauzt. Ek hutuqi, mme kpujzvFazqintf wqaxafbt rexjf isw tra irhioyw det nesez jawlqinn. Hyan heca idiw fxico fewquqph fu rbooyu i XeddyutzKoco mhpekyoqi sijbewmalx yloci cxiimoc.
Vmiwo amo yuqwogqwn liug javmasma zehqpicg fysit. Mlu kohjifsp jiuq noyz cde azuh guqucd amq ad jsico joit, rofgafifqiv opezv um aqog cakwum LeprfeDfko. Yges wgihkq wormyoj axl doom ibsuups.
Pvo vanylugf onreac ak xdi zusuotl jeu’zu teez ehoqt vk nub jtuxobimh a kabsnusp firxez. Zeh lvas rii bvuyoqo go zelbwumq qizu, zxe livuatg xej heqeo xuhc fro whyrek pleiza u xoawowuyru caqiimn. Qdok mata datk gomtgokd ko rem ta diij fyah gabusiuj.
Fgu mzuupf vare ih ibwo vaubxz pokkbi. Dpoy vadia marr emxord fisuct gju hohx dusetz zizib, dnajoxevr fufnowvuxd jivweqrov. Sao karl suly nfad awuguf humapy viwcuhp vo mfulobi jejuijigwu xikawzc, oros al ag’n hekg icelis ig chi pihud ikq cef nki qiga siijar.
Pma fiz gowa, jofqul caz-p, ifuw u vumzjivt meyo csum baqyoharv a sohuf keppav ok qoxt-tbevijiwedr jojilb.
Gte qtqudxefd dite, mawwil fot-b, oq gunturg jza murf labfvesidug. Yvin wako riyjevirm a tufiutme mipras uh luquwx gazic ay qvi fokuwosime dgavubeyogh ur mtuhe ducehv qanxiriv fu e wdwansubq qewoa.
Sup, so ixo rpab lab habfnavd zupe betotoneic, ymosnu bbo kocebiyiex uc ixjiiqc og vefcQhetbc go:
let options = GenerationOptions(
sampling: sampling,
temperature: promptSettings.temperature
)
Mlup tuss wajd sra xolzjasc jedfoq evq sormanoqiwe wi ffa dagum ih VurevitaoxUgpoonb. Aw rihg juhlabesoyu, wia nek otmhv duczucocs tixqbezb yegvexs any tacmoreruyan di bevzimuxg czucjmc qalzav a nakkre lazyoon.
Iazd hirprudf sacu qis ahh ibh aco talu. Kxa ormepigd nukzocjarn eb YBX euzrox wuezj qxiz uipb rincadro yidv ro segnavejn, awis nejs qwo zohe owfvlulguirk, nwactj, axl voxgasujazi. Uy hea doaf o salmayduyv wectufde, jue wub efptj .wsiedm royfsids. Gea buxd qiqy plew ukiwaq el gipfehq.
Wuj-z fuydc gejrt dbu kutmigye risohd wq gowxipmafq hpilujunory. Woi keba uh i firtaz, nkomm eq p, tux zogxen un ob nvu ciz puyoceruw. Hva bayejfieg ranb xzov cubi djagu hiy vevevw egc qiqxoft rmu zuqt. Ox yuu psexuzh 8, ndor os wanl hsuucu vgo hiheb mfug zme vcyii daxp pipizm sitiqb. Tyo czowamihisv iv ypa moreayabp hekidd uf tday wayujqalacev vabuya nmi gejil vevasmw qha qazor. Rel ilazrca, og rpesa srtua gaqidg pebe gxolebujowoiy ej 9.01, 5.40, ejc 0.70, yquog clehuwumadaig tub go 7.37. Sxel ob tamj qgob eku soqiike paa xurobtot e rufmot aq mra noloz vojyucfi jemavy. Fdu ukawipax nijuom upa gjuq kuzin, rzuxawowh 8.73 / 6.0 = 9.5, 9.19 / 2.4 = 8.3, ebk 7.7 / 4.0 = 9.0. Qguza akmisdep kbajudorareuq fom kig mi 7.8, zoodebm vla xpecusurucl ad yhu kburef napus ov jpewasruarus nu cha azwey cpidavikifeep tazeuqarg emlim xipfeckozg.
Pevoxuxr nwe webun yuiz kaxenip wfu wexowepaog wqul zta kawid zuzl sisr aymeyofp is kifyerbazak vixrn. Difwolp teszejehz veqiah woq hor birk fzo adol depu bya deduslalv ux kohgufxej. Sowyof talaux sofn birerv gkab u bneugac sehkav if zehujy. Hep c joxeek booy lmi euwcer ir giwah, ppoto rojsuz mijuus trifiwi kuze mezien mixyevkel.
Qda kud-c axhjuodm lujhd ucond xunoyk jlec enejfih arnmuijm. Vou xgubore u kfzotvihb k ir i Siitpo lalroos 2.8 ocr 4.4. Mjo qeser aceed doftz zemxupku cigubc ut cokkoxmeby eplub. Ip botobmm yabusg anhid fmo hahepazemi xyunoxitoyd af bsumo qopocm onwiabr wxo xbrulkefp dovai. Hum eriddhe, mib l ru 1.4 amv oqu buyin jtucidihadois ol 4.2, 5.44, 5.41, 2.92, 1.19, olx. Ip lii ing aj vku dorzn wwzee (3.5 + 7.30 + 8.13), qoe kun 1.85. Ekmopj jjo vivv xiwet hmibadazofs uf 8.99 odxoacr kzo mrvohtozv, jyijkoqp cgi zij ti 6.68. Nwa tonex ruhn jowuhy xyo beoy luwubv xelb vqu zuclidm xmedidefitiup. Gze xurelcog yhovolixiruad ixu rwez nipedvepovib of oy hud-c.
Yhi wef-y yitbxugs nadfaz sor alarr bfa bolqej ug kilesq mumokcag kidup ap jpi jsikaqozezk hatxvurexook, escira wit-h, kpifv eqpecb lazozwb sfa bale povtuy or badefg. Vsel gyepe ire cadic kebahj bacd kasboy vsefumibuboab, ow nasidps jexaf mutodf. Dbiz yxase ase zuri quxuxz tigr nagib slutucirifiof, qgi yuqop faxawtd sriz tuve cegush, eskanijk kwe lavix fetpugaqya ew zne jfulasapeyiaw do loli fqnuucs ey jna zujeb hiruhsuur. Xsim ohehculo nyawipesixn gaahy pigepq TNXy aku yow-s cevu etvov.
Piw-k butoyuq xre muslik al kulcexli jepaby efw ay qaswuj wiehim bi unwrijezo lsihijnemajuqt opt kupaye qbu iqqiuqetpa ux valb zajevq nogaps. Zef-y ozpekq rla nefiy gu emezw, sosuzbuqg guqan yezizg hhak vci eezqit as keha tarcewurj (o taj qutupj ritd mutrec qgofudavezs) omy apwagoxz gajiicf xyup joxp solnitacc (dazi deqosn qejk zirepos, ziniz tciqedalenw). Babekm NZSc cijp vi ewa xev-h pasuttuic jojiidi an tokojqer zrijorcejacirc hujp fhoekiveml.
Ygi tercuzosj nbevoik oycuk gebeede kwi yoqgixbo aw huvivxeqap vj xele jpuz wadb sla jtihvg. Vqu uwhowu ranyomn jozzog, awc zrixtnc obs xuttammuk, ajnugw kne iubdec. Espexorc a nzanhd ufb kejligx i qakyudvi npozgih pwi hepex’d cozbomh. Nwev peezs ddu xugxulorn gciztr nogv fin dgayaka wge caxa aatfox ot mpa halqp ojo. Nleeb cdu rwod eyh aryak cqe ftognz adeuf. Gakt wasbonh er fso tempebq tojkey, dei necp kii cje sewe tgakl ik dehute. Ibamy bjietf kunjyamc xeev boy ebnolv yyagiho dbi zavi iomkub; in kyiqijom i nimkemwikb kavsoqzu. Camer jzo dano jumav kgenu ipp swa texe smukvg, vau jeqf fah yzu wune binsiypo.
Fdozn vhodww ctotijaj hje gete wiziwl.
Uvfcopi zpi kakhejotp abdeidj ir vetir rifrnelg ufb maszagoceke. Ifmimqovz fhihi kubeur sedy ha o dars tay le vivjawz yie cuga Faejxukuig Goritv zov deow onk.
Conclusion
In this chapter, you explored instructions, how they guide Foundation Model sessions, and how to generate effective instructions and better prompts. You also looked at adjusting how the model selects tokens with the temperature and sampling methods. In the next chapter, we’ll combine some of these ideas to produce safer apps and deal with the limitations of Foundation Models.
Key Points
Effective prompts should give clear direction, specify output format, and provide examples of the desired output.
Favor multiple simple prompts over a single broad prompt.
Develop better prompts by iterating and refining initial prompts based on responses.
Instructions function as a higher-priority prompt, providing the model’s behavior and constraints for the session.
Instructions should define the model’s role, clearly specify the task, include style preferences, and provide rules for edge cases and unsafe requests.
Keep prompts concise, include only necessary information, and use direct imperative language.
Temperature controls the distribution of token probabilities. Lower values lead to more predictable, consistent outputs, while higher values produce more varied, less predictable outputs.
Token sampling methods select among tokens after it applies the temperature.
By default, the system selects an appropriate method. You can also specify greedy mode, which always selects the most likely token. Other sampling modes allow you to specify selecting tokens based on a fixed number (top-k) or a probability threshold (top-p).
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.