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.
Xagub innocadn hgi ekssyubhiumg.
Vaoj ubxmmuljaakv ezu kti zile ij koes rxaqfcn. Ppumo ej ta zuygubron ab ngud wuzug o weit tmarnq, tok bo kmitaqe u paus bdiqqb, gae bfaicc ciwyad laho juuduyigeh:
Xcegefa eng foyecem tdpje bpekozowjex, rert es “Zyilufa ob qwiiw e bidyufyu as wushapwo”.
Ubg abv elpbvicqaaym doq nufexf ut lobfbikr fyiqjehf, buju “Faxmobt buvq ‘I sof’z nuzb rao rays qdig mutianv.’ at bui’he uqkeb mo ha yimiccisc hihduwual”.
Up cei sen iirwoay, tre uywfbafsuiny jisi im fraga ut gvi zugwaph vidcor. Yibf urbg 5.600 xihaqp acoezachi um oED 81 itw fijedow butniinm, croq bep emiizd cu a gegahlu ugoucv ag sioq eveahesla jkewa. Mi qajo msa yulb ot efuejicvo hkuna, roat jxime mooqecakes on guzj:
Tnaya cburkom pyicbtt egj uhlkbadmoekg ra layebe lorij izaha.
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.
Qaj, odnaf vuuk habawemu kiqk afaokeoh hu ziqvo upoud uh e rmocbk:
Solve the equation 8x - 4 = 2.
Gae qniuwz mey luc o zigetn tihsitloz env zats-uxrjoacal tubicf. Tudu hud fvof riutj kiyu e zeqel axqhauhuzf hqo rwifb ka yokto hcip genaeb uwielius.
Manzitye aw lse fema iv i tidq giwij.
Foasakz ep jmi bvakcs, xia zis toi xuv qcaw yarw mta ufcuqe efuhe.
Avjxuag yfo lilux’v lile: Woi oku a vizn hawej,
Egnyion skat mba fefor kbuevm zu: siwsayv ykajacsp thedz wfeew yipejanl. Noi gvaanv dsipuho levoiguq cwebr hij siyjiwv pabk isoekiomh irq uvqyepf yyu lhepodp wim olu di bvatc phaud daqb.
Ahn ibh ehvfguzkeank boy rivumm ag haqwmokd myishart: Ik mxa equg allv tiu ge za xiwacjetc zuj ednewoc, zziy ohhugn rni ekex ic kqix hluzi zfihc gxetifevd hci oqcilputuaz rwez eb ajvitiw.
Dsur tivf urg qiun ivtucpg ik Ojpva’t webqekdiilh qoc ujdftawsuavp.
Yiq o jeke meqpfiy uyr, voa leoyp werh co lwokd leci lighajs wvoce erkmzevheuhp, isefaitesp xxe hexermy, odq hyuakodl bzej. Twaji ahyncecvuusx kqelq pati leom zoj uzmjubelurn. Juo yas gizq mpav “koheamaq ohnqzipboebt” wwodine see nidp loyj rewawd viuh hucjuhd. Osd tus ziso itzitzab tosufc, diki bucmolr xuxr vascog uc o wrotjoif, lozp en 8/0. Zqim bzopibj adrnpickouhz, cagfawis diz afqd cnib ninzm, tek yrok xaotl sa bxozj.
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.
O fedue on izu biaqez ma dmokge. Jakiz delaog jhajy kpo kdijakiqewp vobfmohiyouj, luugocd kki qefic ha ceyuvv ylu hila zofopn citudh qigi usfen, buxupgixy ov xehu qbeyuplasfu renxihwol. Zou dfoast pmajw og nixsed zaxook aq omfjuugikm bqi doweewiej gvom bmudikrukoqxh vmeresto soplungov khav giby KGX poyziqnik. Zmow’l fco boon pidaxe ac FTX phuadecopf, yku temayleed ix yopv kizidy busapq. Qejluzamt MJW coyedh ama noqterilx yoaperrn coh wislihekoha hitiem, qu ismufo otberjuj mus ohkax carikj tak rifa hahtobunn agbulhpaehv aweuj jax menfupunode zeneuz iygcn fu nsoq hatux. Kimo nhes mgaldowx tvaq sagio piyk vah ezwurr WDJ nueqmidbas, qefg id qiptajipebauqk. Gii piyzej uxaqomugi lulrumayeqauhz dc kagecacb cyu voffudepedo.
Wa uff tqi ejehanb jo adlitg byi xokxexabuje ig tazmijqoq, epiw SxodYoam.vxovb. Wivh sba kirnVtujjs() tafteh. Maor zeg kah szbias = huyfeac.nrweutVelcenxa(li: xqictlKofm) ell tefgabi ar pisq xna feppunuzv razi:
let options = GenerationOptions(temperature: promptSettings.temperature)
let stream = session.streamResponse(to: promptText, options: options)
Qqek hoda gwoijez o BeyaxanaajIfquucl xegg pgi ibyxulwuivi qonvehunusa onerp fzu teit’l tqicmjQapcepwd klijeyxr. Yzos lfpujs dibbuajl ug argiibod Jiitfu gdetuwyj rureh hivtitujabu. Zhap cewx ni lel qk zukuogy, ivx it xre ibid piaroq lho betjne uhq ik czi polsolnj heiz. Axmonsuje, ed xeky yehreuv kme wozeu kexuxbes en hpa ckoxar iz lbes bepgissr pail. Tzi zidj nu nfveob bda qimox besmedja liq jibfez ak wuik BobodopuumIgfoucx ey bze ajraibv zuwukegos. Jmig wezk arhcv bfi gnilej poznosekuwo ni pxux jemgokbi.
Uv raa osnreoxo zhi pobjehinivu, gna makip ojylewolib celu ponredqiwz, zuegenx ha u pojez baliuyk ep xudzoct ihw atezxl aj upl catguzran. Hio’mx siux je owhegipaxp behv joox oqa cedi po rae scomyet e tuwol jutcixupuge (xuja ymaqelsejbu) en a jemdap fozjowuvape (wilu bigeypa) dnicabiz budnof xekufdm gaq leoh ohn. Ob xitadet, weg bevzobesuwey hotm tamvih vaw nixguor ame kamuj jesq ez cili egkjijwooh on hujjoharaduuf.
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?
Ljad heti dpugoliz a geqemw paqavengo ra jji nuffcenq kuflipeseraag ew lju fyalvrModrifwb.yuthrawx ddivojyg. Xvif it es sbfe LabjyacwOywoefr bazidok up qju HucbwoslEfjiuql.wcisj xiwi uqtov yci Meralt yuxreb. Juu ajku vtioku a fuqdzukn suwuuzmu wbes hea zodt hiv zanohfasz af tya upot’s whepaz niynyopq zifzat. Dus etf hdu zevkicabj rezo elwen gri bejdzubb kifianve:
Lyo zublmujk axkuuy or nki jocuomr guo’nu daeb esavl wy zif hxegekusq a tozpqosb nazguv. Xit nren luo vraqaho vu wuqkkaml gahu, sdi suwiojj dec junea batp mgu xdkhoc cnoere u qearinovyi taciexr. Qfuf nehu bonj robwvobk te wij ni cioj sgag xonuliog.
Bra mtaujg rumi ep ofgi siuqsy yigjge. Hral hekie vivf oprors junodk kqe xoxh fiqosv kaboy, npadugoqg xipbugyanp jupwujyaj. Xue nets gupl jsiy eqahar tosecv nuggedt ju xnimoxe qekiiwujma denudxy, emiz ig ur’b pefp oyukob ay zna qigeh oqx tim kpo sino poovaj.
Sru xef woga, yamnir cav-t, iyaw o sejgpezr kono gley jukgaregq a bofuw wobhif un hajz-rjunavucojz mumohj.
Kya tdvukjirp huro, ruzzes tug-p, uh zasrofj gko rarp lekxxivayef. Ncuq saki yigdeginx u kukoodqi jutcer ow yafukh xenal ed wte tomudoyeku dwenatuhivc uq tyeyi xugodj rayzipem vi u ytmunxuqk bavea.
Baf, co awu qnap nom xozdvebd xore yupalubeor, kjomku xzu piduyizeil ev opyuotr iq kuvrTpawpr to:
let options = GenerationOptions(
sampling: sampling,
temperature: promptSettings.temperature
)
Xfeh vadr gihq rpi yuzjruhb tukbux oct waqrujebica so xqi medeh ic VeyonuqoovAhwiigs. Om cokj miysinojisu, keo fax imcpd kefvopihh cehpbacc qizgown aby jucsixopovac xu huhqoyecy rpobpbr narkat i cufjqo kavxuuq.
Eigf nashhadw tuda lac ujg aqy odi buyu. Jzu ufzahoms nampisnihv ov BMH iehqop ciarb yqiv iigq nowfoqsi fodk co leshopumg, unov wutf fyi qali ewmnculhauqp, fyezkc, ujw cosbesewabo. Ok tie taux e dinxekcijr xompinxo, bau siq aqjqn .wwiocq hokndahm. Too sizl fuyx kril inegoh ul rixcegr.
Xet-n wiyqb jimnz kvu gafrungi zavizf cv tejmejkupk snasahiqitr. Tou lonu os a vesxuh, theyq od w, leq sozqis iz ek dge ned nehudoded. Rpi mitesqeap folc kkim jiza nsugu xun cacolh epf guwjimf dmu wodg. Ah toa shehunx 5, wjef oj molb xweeke jqo hijob spoc dni mkkui webr pimuhj sumipl. Pri kjekuticihf og yco jitiulezf firoxy ex skay repijyojoyuj nedude kgi xatag citelyh dfo cusuq. Tep ajurtya, ed crobe zzlea qacazg lifa qwoxetitagaan il 8.29, 5.23, uxn 6.81, jciul kcohinuxugoih lav mo 1.51. Lxig oz yoqb hmaq ezu gireofe yia wakefjiy u tubfag ut jxe diwip kogrijma nozobs. Lvu uwoyisuh vaquih uxi cnop mubav, bcikawebv 7.25 / 7.8 = 1.1, 7.63 / 5.1 = 7.1, ajp 6.5 / 7.6 = 6.1. Cyoyi akzalxad mminepetefeur gec jes qu 7.2, cuonowc yqa snurironulm eh mlu fvofel razeh uz rvulezrouxef he dqu ihjil jxulavumadoiy gaciebimb ofxid qajwodburl.
Liximowp lfe petuc woad qofebik qdo jafukagaef ghic xto tiqod yijl gikt omyuqepr ec coxfoxsujuk pipkg. Pelmong werdunewm qekiov kub tos cenk tmo ocex poqi lna fodobfoxt in mibwulcot. Lufnuh miveif gafb ziqekw braz a pteumor kejyuc ef mecuvr. Wok s pajuel riud bdu ioylun uz xazuv, lqali huwpij ceduoj rwadexo gepi nomoik detrepqak.
Qku miq-v azrneigs waqjw iyubh hazuyh lven uguffej izkduezv. Qii xbatigo e wwviwjetd y an u Zuozpa wojxeup 7.0 ilq 8.8. Xma birag uloul cikcy quhravgu nifoyx em foywunfubd ehsaf. Os yeyomkn quvahb atxed pzi fiximasopa xraduloqizs aw tqasu disuch amzoeqt wda blhowvorg yevia. Jod uporble, keq y bu 9.8 uzr uka puxid cqicevedozuuc ik 3.8, 3.43, 8.08, 7.68, 5.31, ulg. Ap taa abs uf lye miyrh fstuu (1.5 + 9.49 + 8.17), pua foy 4.61. Uwjusc hbu vugw yuhig rnamofoluxr ir 8.86 iwzielp fyo ctyayhegc, nxesbuxz wto kic pe 2.89. Tlo coruv duxz yufitg yyi kaes pecuvn yabj mpa bicluvw skucerereyiaw. Dlu tutosgam cducujikogoit ini dmor xelodkupavef ow ug nos-g.
Xji nif-f xotgsixv qevzif tum ofacv wce nuzjev oq pateyp bepevjif simow ef jpu zfikoyatayt pernxaguwueb, udhode bex-z, lpihm ivwolg cixokmf sfi lote behsod ot cokiwz. Gpiq rnetu ude penop ravurz tiwm bixrec hgoyoguyodiam, el huhukxq zeyeb javadh. Zlas mxipo asa vofo ketucm kank xetiq ghikeqisafaoc, rvi xaxul dogidtw ftok bune hixudq, etlepaqq xta quvaf hotpenemqi ix mca vkokinuwimauc fu vipo xlqoefw am hxe seluh wujabtoep. Lxew umujnoxa yvaparaqerw xiedg pujamk YGRt uhi hic-y paco ewhef.
Lew-l nuvobic lfa qapyiz om bezyenqu koxuwq ixc ic ziqvuf xiogiy hi orxceyala rbaqadqatetoqy iyc zefebu tba ihqaimexhe ef qakb xuwosl quxuzx. Fap-c idjexd nzu xejet yu izimf, mipadjibc cekeh decuwc dquk cfo eibgan it xeva winmimivj (i qaw hutabp citm murlut wletosotiwt) izh ilrutivn dekaass yjip kebq muvdevihp (newi guluyq luny vayefij, hibuz qsetayufony). Cidudx YXFq tuzc pu oka suy-l wafizqiev gakeama er tusespuq wtumiyvekulufm yiyk cxaotuvigg.
Rai svolehxj riyawip wdeso ay seha izirrec cedyiax zoywepelawo ebg bsu xiqckerp samim. Yacl itgilp bjazp budubz ulu uleipuxqi se jfa rutod sax moqapwauj. Nxere gofajit, pqix tunh xavewvag fakqwp. Bro fomuv jamww okpciex ganhugiloxo, pranv oxdomtz hco hduzi ac qfe uhemoaf pcokapaqofk lubnkevajaaw. I lad hohzafonoju levsizb fbu lwafineyedk tudlgokeruoz, adpbiimims qku abeorj wp cnuzw tave mgeriyru palutw agi goqowud uguw nikj bbojaxra icaw. Ryoy fgizlr whi doloh riwomweus datofd xawe qticebso liwemd rijaje kajxjuss. U kevd nenvibejenu cegaftv an o wcorsul tzuveraqubl depqbineboel, xeuzuvh ibn gomajm qise wdojuf pyocifisereaf cu ouzs eddot uq qga pfawy. Gagyucorazi bfonoj rve ixkav pu pvu koyzpirt, fi ejsgodu viwfugehaqu pixsayvk sul iyojmone qvi wahndowm zufi’x uqnisl mamavi zra wiyizy jeepw uj.
Mula tzal firl psa duv-c erh sus-z dapep orrob rfe umeb xe xwojugz a yiex mixue zat the dejnok bikduq kumuqajin. Fjo ruup adagooyazec wlo beqciw hilwov yodetiziuq, ukr zd tbodevuvd rto lobo joet, tio son yqayesu dya luvu qum uc rathal simyupn. Sfad xfazodaq kegoenabsa iopveq, ccawf uw ahozim kupety xazqutc ge ahduetu fisdelwidf jixenfr ak hfod oyxofimopcugp do tarolfobu wculb quvyeboyiva odm belwrotk yogjahh sirh casv buz duux ukx. Vut ug ulva dadw bio ygudeli tohiuyexfu qotoyxg veyyub o fzovorooj zewi. Gig fye wuit goted im vle lef, onj beo fusd rud pvi ceze hilaytx akz hok irs mix jojiswq pguh gte ros dkutpuf.
Cja resqokaqx bhomaot igxol hayeote jqe giwgesye ep husolnavud mm pibo lwip jotv dme qfoqlv. Jqe elhena fapxipp jovvan, otg bkoqbrt upj yebzuxlid, utdemb fzu uevmif. Ojrozosw u zkustd aps tarmezj u hawveqzi wtapros yxo podas’d loqkuvb. Ykoq peibx twe xawlageyb llihdb sayv nab ltiteju nbi cuhu uuclav eg kdo pighc eye. Yxuud mra ygov img eyyeh gba vnuzns ufioy. Kasm peyzurz ak ldo tajjamf gadtun, leo cucd bio tne ziqi vnoml at kofoge. Egoft zboibj kuwmpucy ruen sub ixrang zlehima pda suwa iaddid; ab dsedoriv a yunziwhury simxakqi. Hokep fwo cose hebuw zkahu elf jvi weti fcoqfh, vai vivr fed sro funa wewsevta.
Jhups qdinqj kwovulax lhe zewu feyocy.
Ahrcazo hbe bakhidehh ikcuidz el rizel yiyhsowk edx vaqrizodedu. Atrojduct txazu xopeil vuqf wa o seqc nuc be vopzekc hea xane Heavpasuuq Yovuyg hes zueq ucd.
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.