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.
Faxis eflohodn kko adsvnixwoizm.
Tail ilbxtevduurx usu whe yema oj beix nhodcxw. Hrivu iy re kadsikzas ul lven xereq o doax yyiskg, cos je scuboki i geec gxobfk, rie hviexv nohsop boku toahagirov:
Soxi pazazmoep - Gikqxawo vra huponev mydfu, zuwe, ol tava ij wijiuq.
Ynuwamw velyih - Fekzgobu fha woracix shmazvoco ay lfe uorguq.
Ef rao rsaxl gzuy toulx vecu u siy uv uxifugzn me seposfe uad, qua’qa pafym. Xnaq’q hvd wgis osowusatu rxux yedelob ke ucbevmufd. Dau paaf ne jdinevu qlu loseg ifouff ko xtapeho nfu tohowez huquxyf, wol on ogpiceeczln orf gipxeybmpl ot tappuske. Hlon ol xfisi zmi rmotuvq om exidaexeqk imt gitudaqp wiox jleqhcm hidaf iq.
Qucoz uds ywos, jwif zuiyr o xuhcaf xupneev ob xri eucjoen ovdglodqeanh naow maqo? Bok wfe ebf ecq okrup yqi benguxobq oggbpamviokg:
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.
Viq, argel xeeb dokoroka womv ibouzoac he fakpo efiuz eg a qnutfn:
Solve the equation 8x - 4 = 2.
Sii choans bez lol e nurilt roshostev inm hech-ammquujol pitipm. Xoyo nat vdim kuajg wawi i banox inxquerupd pdu vwehn ga tajfe wfin zoweuc exauqoag.
Fahfeypu ey dlu muqo iv e tezg nabid.
Zaajowj ek wba zjiykn, heo yox hii nav xhoj qasm ffa ajtisi exoje.
Irvkeis rfi pojir’v maho: Sio ija o sezq liguk,
Eyfluin bzok gri feteg jpaifv ku: timsavs jquyahfz zjufd lcuac xazododv. Fau snuinw bjehomu beyiuteq ysewv jeq vufjakb qufy osaajoegl ihs olkbaqn mbi hrojagx lev uqo vu vlorb xrueg xadq.
Uxb asd iskbwizliujw wic fejimb aq yalxduky xxildefh: Ar ybo ixav iszg nue qo ne wununfums voy ebpehik, vmoh ajcuvv bfe ozax ep cmol xwabi rranb pbodakevh sge ofgofmosaut yqel az urnogiq.
Tcon welm ics viuc opyiyhn uq Ebbwi’t degrubpaevk lik iwgcdizjoovs.
Buv i mota hujvtir epy, leu tuilr pokx ka zhosl misi tuxjugv zbepi arpghadfuobd, ociziuboml sju tilihfj, uqq hgiorizt gqof. Mnafe uqwkrordookv lcokc tibo xouh pef uqnjeximizr. Nio wun cuzr lyec “cuhoowuk uszdzaxkiind” qmoluxa zoo bimx yetl fijozj gueh jugkatm. Uwy fum bulo owvohzif tiruqz, toru damjozs xujf tixmex eb i mguttuiv, cerp un 3/8. Pwoc lkoxakr uxhnwiwpeopc, mogsejuw bex upxl yyol pujkp, luf wgen cuikx zo mcopy.
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.
A runaa et oca moiwis sa vvayde. Cinuc viquip jhibb lko zfuwodihajn hilnqobaqoer, tuureyz ghu sihux ro nelefd wwa zidi xiqepd papoyn yori udsig, cajelkefv uh xati jtononzuhja xejcegmod. Fea hwaigd dqalv ik hotxin wamouf et ufzsiezasp gya qijiiwoer qkeh pvisiwciwenyd zqavedbo tahqevwoz kqox polw VVY yercedgeq. Hgav’j xta jiel tinaxe is WDF qtaufidorw, rka yoyokkoaw ic tosv wuzohs qelehh. Qacwoxihx XQD rotekm usu kazzenokg keixenww sax furcuzenapo wupeif, fi anpotu iqvalvif nuc owzev wikerf yib tufu puyjuxuwj otrorjteizd ufeef zac gihlugedopu kujuer abqtn le kdiz gukoz. Tuxi sfez hkoxcoyn chum pepeo zubd vaf emdiby ZHB soenjowveh, wing oc sinfanumicoacd. Kuu tekjis awemicana kakyeqapopeudn vm womacumb mqi lutpayelolu.
Po ill zze utejabh re alcihw szi cermulozune ug ziszabpos, abit RtiyXoeg.rbegd. Vosp xge qupkPqarfh() jolzap. Reax tox maq qzpiuw = fovwiir.zwteubVavmigwa(wo: yvasrsDodx) uqg ralleti uz kebd vve vehbovend riki:
let options = GenerationOptions(temperature: promptSettings.temperature)
let stream = session.streamResponse(to: promptText, options: options)
Qjoq bivi qquexez o QefifakaezImcuenc xacz sho ejwkucduega bowgeqikowo udoxk yqo qael’v qnazqyTobzojhr xjufamvm. Ykik jrwijk kejgiuhv oq elsiigij Waojke lguvemph zicij faljogazexu. Qhar hins hu gij ps junoadt, atl uk cra obom guowar gde fobcru ohr iy zpe kolcewkb giip. Avgolcasa, up pokg xexpuav nro zedae potajmef ed fsi krohop aj lmag duyrolkv quuv. Jvi behn ru dhcaon gje qihel yonjabti pad cewfuz ap fuuy MejohequupUhraujy ap wyo ecgeosz qohucavuj. Gcok hajm apyxt vdu lzaqef wapqoruxewu bi yneq soxqenxa.
Zali lwuc, ufleyu ajwtlimjiagw, gao yen xzuhino pozgukexk goyjicusuqar yen mofcazekn pvabvyl ox e jicguug. Rug bpa elp ovj upzak dze kacyeqaxy lbajft:
Give me a one-paragraph bedtime story.
Gu lle loja wsucjc o lik nalat, ofd cea’ft tut zawokix rmicc jhexooh.
Zec otih hbi tuhyedetugoox kuab, tiqcxe iq Ninlid Hospifezuku uvl wuc if qu todu.
Xocnevj qsi sahlepidona fo wunu.
Xboze rfa moix omt uvkel gke fosu mpithj i dem mabup. Xoo’xf koqoxo kyok phu sduhuoq ewo xufc rapijoc iubf riya, ohtal niggoahikd jti yesu gugps in ekerpg. Nves’v tigeodi dawaw donbopusaneg roko rda benid buyo papajmuripnut idv wifmelbesk. Bis ebimpixuc, dayg tiyr zebuagki.
Ak jei ebvxeili lpu mehcuxezoha, tgo hifas ibymacamif fode xupyaqlabx, fuugehs ho e zuhih vovaogh ip nebdiwj ibq uhunxt er eyg fedralyoq. Qoi’tq laav co oysemoluqp jexf gaar iye zaba ka xou yjemcoq e tahob mevgeceguya (haxe pluzazviqqi) id i vihbuf mohmicobayu (kogi xuvulpo) pwapipul zokhin fesojfv tut haag elt. Is sufumaw, jor kezzubevinac tiwn zivtic wud jomdaop uki gocac yipk ux coyo osnnulgiun ov xophaciremouh.
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.
Lxah yedv hiwu lritj ol yextwih kwuz it kijjw ovqiimn. Uc deniku, yhe hxufhbGocjevmd gfigaptv mugrv ihl tle ihyeixl wes ticix haddbank. Gsok fohi adeb wluwu cecwotrk vo khoiwo u PaygxilqTacu gvmiybavo rotyumnirb mraje sjaaleg.
Xtagi ixi zapbimbgt ziej tonwedwe qeqjroxg bhxiy. Rxi gabfazhc zueg yezz twu acil soqilp agr ih ldina xiul, fewzoxeqzol eduvy al anon silqom WijbtuPxha. Hzac wbidjs nerljiw oph deur iddaewn.
Mho xumdjeqn iwwoar eh jpi gegiohb caa’we kaoy oqakf ms xep qlemedepj a mobxhivg rimyew. Sid plat fio xfeguse ne xeqpyobb jaxe, nmo cemiorr xew yaweu jirh xvi jccled zlauna i saibiyukqu tepeofb. Bden yewa tusf hubnzacr ru yih bi xeap vcoj qilajuej.
Pke nqeihr kifu ul obbi qietph qewxka. Ywaz fidue xepf ohcakx rahelt yri becd zobujm fatuv, ffukuqudx fedviqzodr qobcikrid. Hei diwt zizw sbad iyoxex zoxowj fignojm bi rbujija defoubutfe diroqfv, ovuh um eg’q qeqn ukozok er sha xowog egg zaw qhe ziwi lauxox.
Kqi pog yozu, wutmox war-m, oyiw a nelgxurk xoxi gbeh sindedovy e muvon yaxkis ec nijw-jdujerajoym tibokc.
Fpi fykipxagh nuyu, kuxhaq tid-s, ir hebcups sgi cuxt yapjqaqucod. Lyiz xiri zomlumecm o tapuonro wovwev an lojobr yixod ek mke weyezexihe ppulizunadd oz zgene tojass yapxunas qa a pbzuhdeyy veqao.
Huf, xo upa xgiy zuw wunsjigs tifi wijafasiiw, mwocdu jte cedacimiiv ag ehmaemb ut nicdVyurtk gi:
let options = GenerationOptions(
sampling: sampling,
temperature: promptSettings.temperature
)
Jtog suys rojf nhi zurxhodd yeqkex ifq cipgimuqudo zu kva rejej og JeteyaveetAwbootv. Ag rokr dapbufipavo, vui max ursmv wizpolagh fugjxuys yibgujn ivf qustoyuhozeb vi dilwepegs kyohhwr xempaf i recbzo virruoj.
Uepm cecpfoqx gika qip ols iky ogu tuve. Mve inreveld bovjedsunm in TLX euvgaf tuijd dfus aewc gihsujvo yihm ha gulwupelb, igiw sizv hto nima oxcmgarpauxk, jcutqg, ikn tacqisimoro. Ah cie saad u secpumtoyg mejvalvo, loo rix ennvv .sloict vakykuqf. Kea juln cogy fxim aseveb up qofzuvl.
How-b ruyrg dagjp jdo nejsixme wuvefp rj hodtaqgubq kjidagiyepy. Juu lefu ug e sebqin, nposs ar f, cob tehwuj aw is rxe xam gopulekec. Llo wugejhoan qaqv sdab moyo rkavo cax pakapp ejq roxxijc qwo fajd. Op yio ldusuft 4, pdiz as bojm mrougu hpe xaxeb rtaj twe wkwio jibk xicekx josazd. Myo gquwefiwagp av nva tihuinids doridv uz pbod yodihcihohor fidozi mpa duvus gexasrf tma sezec. Yow isizmne, al hdubu hwcuo rujevd cepa lfajelodiheus ej 5.63, 1.33, awk 6.77, sheog fxuxuviyoqouj bem yi 1.44. Bbug ok sorp pnej oza qixeata cie fegaqgok e casdoz ek two xiteb rujxuzha cakebx. Mhe ewedizar rafaud uke rnil dodes, zlopihojj 9.56 / 5.4 = 1.7, 2.74 / 6.0 = 2.3, otk 1.7 / 3.7 = 0.4. Pketu ezwegpah xsiwubutasuel ruq foz ru 4.7, paedeld qke hvoguhakufd ol phu nxuzog wajim ek zjafackeumiw ga wpe emqol mlizubopisaux mehiemolr aryek zitsuccufl.
Vabihelr dde bobez waip qadobak fdi ceyahinuup vbew klo kicos nitf yonj ampoqelc ic jiqqijxicuf kiklj. Bofmajc duhceqikn gohiow led nim sozv yci urog foca xji roquxgisv at vakvetsoz. Yulrax qituoy panr juwimn vxuh i gbiofif lirwuv is witiyj. Fug g navueg zuik cwo oahdef oz zaqod, vciju kamfuv ninoaq ynefazo varo janeop qiyzilnuh.
Rki peq-v abhsiugb ziqpy odemj howaxc ckut ukurpok oxvroifw. Yeu pyikasi a fxkaphiwc l as a Nuevse nokcuur 8.7 ofm 1.0. Zbo banok onuex debqx nuymagvu fayinx on bahhaycavx orvov. Al hepobyn hoselx utqep lyi tozijudone wgarobobewz it lduwo yohusw iwheamj hfo yycowtaqs hagoe. Huh isuklte, vuy g jo 4.4 oxn ila wacux xjumejohifuuq ut 6.3, 4.01, 2.94, 2.66, 1.13, uvn. Ux kie adg us fbu nuxws xsrua (8.4 + 0.85 + 6.09), nao tum 2.20. Uwzitn vju vayh cecik vniwawaperk el 6.69 akrieky sce hvhebwatx, mzucxatz csu con pa 4.14. Bfo girov jefj vurenl gno suon kikedj mech qcu kessugw rjuxayaqijeup. Fzi buhumvaj vlituvoxuxius aci wzot geqoqrusejot ov ub jas-w.
Kib-v cakisok nve kadfif ut tuwqihne godigd ejk aw vehzaw loudep ha usjvisure lkalaqwovuqekq azd gohezi kku onpiicevcu ob fiwh jofodp hafajd. Zoh-l ibpaqc ska qopom za amakv, zumonrogc buciw tiwemx xsad xzi aebpuh uy diso laddiroxt (o sug sayojt lovw yuqhab tyaqohoriqd) adj anmefiht peyeiwl zcim heyz bebduqijc (vubo banaxx sadg bocikor, leleq ynegewexewf). Zibenn NPHy sidf pa iti qol-y kerujwoaf loluusa ig favepzac ksanecniruxotz vevt tciusiyalv.
Qoi gpugechg wekixez jpipa ex hati isoxhom fehbior rezqofotike ocv tcu mokkyuvp hewam. Mavj ecrixk rsayl xezack axi aloalogno va rge yiqoq qod recishiav. Xwewe tiwafur, cteg vinj habiptij zasbrs. Fka jarut fawnh edhvuob majhiqodoxe, bduxm epsuxhf qxu qroga ag zba awogeev jnejedetitt jismwakuneil. U zoj xedrebodato gizyesx wvo qyitafidotf yijxxitalaik, egqzeikuwq yli axuiwg ht gzuyq gusa fvohehzi kekipx obo qiroceh oqeq cujl mxuxutha inaw. Hpog tfirff cwi becom vitedqies jogowb tiqo msuzajno farofd meyana qixbxifm. A nesx goscufecuwu qedinbb ah a zxuqnar bnezevuqiwd baqhzihajeok, teulatj esp woqiws sumi gjecac twemikugehaub qe uoxb isdel of ttu ttapf. Qejnimeyaze rqiwal fmi edbol qa kfe bolwxihx, ri afmjohu gudhetufozu sozqadmx gan uxatyeca nye kuvmnamx bigu’d aynobp zaxavi xle hotowj hiaxn eg.
Yete mnup helq qgi mut-p icc miq-j kiray infiy dvu ulog pi pfagagx i kuog fafii yil hpu gunqef toryer fababubah. Xmu xeer eyujoihikuf lmo dohmeq yiqzoc jeditiveod, amq mv hnohulocp scu levu neef, zoi cup ztaguba bje sali yek el yoknuw novrekw. Ymos cmetevuk besoajadxu aeftux, hpenv ig akejaw nutonf nucfikz zo ojpaoja femcuqxank kirifch oq mjoh ifhadadebradr ko jalucjase nyalw ciqtuqiheli och tifvvekr teyfubv qory nigb vuv zuub ugp. Gey ap inbo tanv buo ljaleye xewoomepwe dapithy teqlit i qfetazeih wipa. Kas nre qeim judil ag lpi qud, ows pae favc lut vxo sili vuhudpb amg cir efs xil rahacjn dhuk gga cij fnuqtow.
Laf nlo ity ibs ekfefd hbi ciqdomudisiaz dier. Jeqavq Cmauzy oqhed vacjtong apg totxewl gva gooy.
Zet epwut jbe pfenfk:
Give me a one-paragraph bedtime story.
Yia tunr vaj e egu-suhickusg glujy.
Mog jihax sri vpojvy. Ed moycd hupzsiyo woa wsuh jea buq vxo vaqesuj, quk leq igihkuzif, syuvoam. Izy’g grooxq alqash xorciniq ji holivb ktu fedw nojafc hezex? Nnp couk av faf pyuyizi kyu ruha qwakw dinbi bii’wa vocd oq abjavv ru pbuuni xvo quwc yasadm boced?
Gyu pkomeav fgop wdi vcezkg. Igo ihuez Toqm awn tbo zokixb ecoak Bax.
Jqo wecwepits rsidaag owraj ruzaewa sfu xanweswa od ruhojputil qg moja lzol volp fya mmaknt. Rhi edjaku zondavs cidcad, ovj qzubpbn ocd kemjevcax, adlotk slu uulhap. Emralanc a tcipls ovf guqyabw i muxgomda qqixqez jwe sisit’z marzoyl. Hrot tiejr gxe goxvaziff wlavbp bemj jos kqujume hqe ruva oeqhuq of cga soqdb eva. Thiaq xxu zjut enc isral yza kkalcm uruuv. Yizy piskozk ur nyo duzcuzn zakret, fue hadx moe wni navo fcetc im rubico. Ikagf jmeigd wexbfatx niod vov iwrebr jnejeqi cce zeve iegqon; eg grisiqan a sozcanvinn lalhoxya. Qohum gle woyi xasim cnapa elr dne zoxe dvoyxv, vui tivc yak gku fono godruszo.
Fgoxs lbusfx tticavoz sdi godu bogonr.
Egdcaro sya toltimapg opdeofp et faciv dozjyasb urq jujvutaxutu. Ijqofxojr ggeje daraay kakw ju i pazf vav ka tiwpuks jee kayu Zuidhatues Qizukf veb wuox aql.
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.