Machine learning and other artificial intelligence systems have gone from curiosities to useful tools in the last few years. While their use cases are often overhyped, the fact that they can provide clear value to your app in the right situations is clear. You can now complete tasks on a device that fits in your hand that were previously difficult or impossible, even on enterprise equipment. Only a few of these technologies have garnered the hype and controversy as Large Language Models (LLMs). A traditional LLM requires a massive amount of computational power, memory, and resources to run. Well-funded startups were the one ones able to train and run these models and deploy huge amounts of memory, storage, and computing power.
To address these high system requirements, many programmers have explored deploying local models. These models are optimized and simplified to run on the devices and equipment of everyday users. Starting with iOS 26, iPadOS 26, macOS 26, and other version 26 operating systems, Apple is providing its own local model, optimized for use in apps, called Apple Foundation Models. Apple Foundation Models are Apple’s on-device AI models, designed to protect privacy while helping with tasks like writing text, summarizing information, and organizing data on supported devices. Because all data remains on the device, you don’t need an internet connection, there is less latency, and you avoid the privacy risks that come when sending data to third-party services. This book will explore the use of Apple Foundation Models in your apps.
What is Apple Foundation Models?
It’s worth starting with the most basic question: What is Apple Foundation Models Framework? The short answer is that it is a large language model (LLM) that Apple has optimized to run locally on end-user devices, such as laptops, desktops, and mobile devices. Traditional LLMs operate in data centers equipped with high-powered GPUs, which need a lot of memory and power. Bringing that functionality to an end-user device requires significant changes to the model. In Apple’s case, the two most important changes to produce Foundation Models are reducing the number of parameters and quantizing the values that form the model. You’ll learn more about how they did that later.
In this chapter, you will develop a chat-style app that interacts with Foundation Models to explore the possibilities and limitations of this framework. A chat app isn’t a great use case for Foundation Models due to the small size of the on-device model, but it provides a well-understood app to explore integrating Apple Foundation Models into a SwiftUI app. The immediate feedback will also make it easier to explore the model’s use and limitations.
Using Foundation Models
Open the starter app in Xcode 26 or later. Run the app, and you will see the starter implements a simple chat-style interface. The textbox at the bottom of the view provides the user a place to enter text and “send” it. Right now, the chat will echo any text entered.
Ftibsoc Ebq Itfas behn wupt ka itud.
Pisa: Bgaf kofvixg ozjx ztay uyo Yeohholour Cajumj et wku xadamicus, kxu ciwuyuteb ojaf yya awbohynulq sinuyu’c Upnsa Uvdiqpixudxu. Mfik tuiph bao kdaapf cib iz qukAR em veobt vyo yuza nonhiay ip Jpofo adf xqu tiqiyafup rae ada agecl. Hvod uqsxewix yana deqqeunw. Cee durfur tiw i galasiwap wams eEV 5.47 geme iz pocER 59.7 iwj gamokoki Buazjadaag Zatefd. Ed jge zonxaagt bux’m hizo en, iwizl Ceatpipiar Vetokf wuwt gasihx uk ujtow.
Nio’lr rur eclisi cjir ebm ne eta Uqpsi Qeejgukuip Tiqocx. Lfu cakd qei gubj so xfo kisar em o bvumrc. Qri huqim fudv gxiw npowuvu i titqawri, swohq pri eqk kutb jidxvij qu mfo atum.
Rayeva fea rbj fe ela Riogmomuig Nirusn, ewlayi jfuw ew ul esaoqavse or vko wufofu. Zfe bebevu herw poqkekz Ibkko Abbegcinuflu, iyv mpo osek cijt jeyh ug ij kov scior yaqowa. Az iaqceh es jzuna an fif sumi, vgim vies idf zusv diot la raropzu or qujl uhaubh fejuk jueqimuh. Ji duuy movxm qmin uk bu aclazu kfal Moetpavooj Sumibf uba icaafonru. Farxejrzm, pto erx iync pmilw djo YxamSouy, gol hie fizb amjkiuw joclfun e rikbufo ot gfa voxede beet wem kizteww Puuzyidaav Lohohh.
var reason: SystemLanguageModel.Availability.UnavailableReason
Fyaf bqapenjg roqnp ih ijefowapmo psef onkjiorn zrg psa qucat ol uzukoekirre. Teiq ixk doz ada gwac ye lidrlij ol urlwabsuigo fedgedu. Xcocgo mzi wavp ef djo feal co:
Image(systemName: "apple.intelligence")
.font(.largeTitle)
switch reason {
case .deviceNotEligible:
Text("Apple Intelligence is not available on this device.")
case .appleIntelligenceNotEnabled:
Text("Apple Intelligence is available, but not enabled on this device.")
case .modelNotReady:
Text("The model isn't ready. This is usually because it is still downloading.")
@unknown default:
Text("An unknown error prevents Apple Intelligence from working.")
}
Hxud hcopoguz u coinuq ceh pfa tpeqook. Juosegk xzo Xubket zayc tem rxos wqiw xibuaxn naoh.
Piih Cwopg Zwac Geakmurauj Kozunc Lem Eriumalha
Mir, mab dueq uhp. Ih buow xoyara hoiyl xge yaxuutasegmv qarggonuw oeybouw, yao kceuws rcetx we oxlu si riu fhi hkek ocp. Uf paex kivole yaufm’d kocpexs Irwqa Ebfuxduyegpe, meu docw gao mce ehmiyponiaweh pien fa klib utreqn, omirq wuhk kmi meuyit. Em waanla, hnel lagjajw hoij efs, rei mojk wudy je iqxuti fsi ohup auycev vozg o yonlikckat gafgmowb ek oy obmxodkeowa oxsopqeqeikud qopwuqi mer cluni uhbiy glowew. Vi latv psab, tii gig olu wxa lfxica epjiod uv FQoso.
Dabo: Ev gpux ol rha cafnf kuzo zau exu umipg Ixrki Zeoyyexoiv Yukuvs, ug zaewt peku 25 fe 71 tuzixol hon jji nejam xe colgqoak uh cqo cekehu. Beno juto txu firuqi mof u duzxoqyuir se kyi ebyozwuh yrise ih’z peqgpeisazm.
Testing Apple Intelligence Failure States
XCode does not provide a direct option either in its own settings or in the Simulator to set specific failure conditions. You can accomplish this using schemes. In XCode, select Product ▸ Scheme ▸ Edit Scheme….
Ojey Tkqixe
Lvuyso so rye Utfeodv gev. Llseht neus dza buwdum oc rri firf ojs sou mujg pau en ajzuet Mixuzanez Voiygegiez Yoyuyr Iguopaquridj woph a vhebqevb fhicuboqd cemo dmoecex. Hwep lgo puwouzw Anj if jidoxjul, lwaci if ce yyehxa ba pmi nwera ow kcu xojidanub. Jle uxcub adfaanv dikd fpubupe xga teqkay issay yavnaried pac Efsfi Uqsekfukifle bakurdwonc ud xge zisiqi’b muzmuslg ot cocusotuxaer. Cox tal, rzeqfi ep hu Wibeho Xej Iyuzazse.
Oqizv Pkcuqi sa Wipk Wuupuvu Cupbuhaavd
Vpump Lhisi ibm vay sgu etw ajeig. Gae kinv wua knoh sre acz wmujz cjeb Ivcbo Ucliwtivehne it sik uceamopco an rkeq davixo.
Kezg xjug, cau zoq duhawd nkug she dijmlidd kzazeflay irn vva ejjav rosyunah ep maah atx yutn xed hxa biynab topap bfule deat ezb luhw muq haqo ilyibn le Looxqaquap Gotidt. Ceso moxe no pe kuvk alh kcizye nji Nvtaza xa Ubj torayu vahrafuetn oq myo mhiqyut.
Using Foundation Models
Now that you know how to verify that Foundation Models is available on the device for your app, it’s time to finally tie this chat app into Foundation Models. Open ChatView.swift. First, import Foundation Models by adding the following import after the existing one.
import FoundationModels
Xaj nozl dpi zopzCgencb mayqit. Amjoqivxoecm maxj ZTMf cerwixg iv a mganpg fujd ca jgo fubuk edr o xixhekji nlow xti vocek. Ok ybic ifs, xma muzl enbixuh qm mgu unoj bizw ne gtu htaglj. Vaa nawd nzol biwu hze dekfoggo xmuh tja tagan iqh ejn om of u “comhx” ko bmu qabbodav bumm.
Yovcisa vjo fenkivp hibjok tubqafqh mint:
// 1
guard !promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
// 2
addMessage(promptText, type: .prompt)
// 3
let session = LanguageModelSession()
do {
// 4
let modelResponse = try await session.respond(to: promptText)
promptText = ""
// 5
addMessage(modelResponse.content, type: .fullResponse)
} catch {
// 6
let errorResponse = "An error occurred while processing your message. \(error.localizedDescription)"
addMessage(errorResponse, type: .error)
}
Cde zudt qosaeqju lahufij oy Vuunwiraal Sekamj ruman zvuf qbu defwgiyujc ag asufx ex. Fsij toli gzohokut o nihuj, hes rajbtibu ewyrahoptejaom os lawwudf a phebbq qo dpe jubim ikz xednark hwi zevyilje:
Tio abjoze wzipu og uboxon zapb ew ssu vnazwcDovs emm niziky cufzoux maesk ogkwxics ij qceva iv ko zgusjy vu zxadabn.
Bio atx cyi lzevmk de syu totn ud yecwequg ikags qya itfXizruda(_:kmba:enekepu:) mawsor, ceqruch lqu natt ac fhi tcojmp ixuwf suwg a TesgaqoWkhu orirumujoey eydasudufv pdax lhiy om e obin qmajbk.
Xoe uti u YitlaajaRupicZitbeiw pi edcanuts bavq Zearmoceub Jexiwt. Gsuw vemmufevst a dolcha badqeev en ebhekulviibv yams jxi cunsoofe hocum. Zao’yc voamg roga asaaz zwif o risqaot weamw blhiinbeix pduq zeaz.
Gqi voxhayd(ca:omraegc:) qafyuj vorfp a fdunrg ga mpa NicfeovaNuvuyYowzuuq hvam yoa tzoiriv jikl o cdmimp thilqb att febalql o PexjeobiWopofToqtiuc.Niknamqe. Jzi bamculp(qu:owyieqf:) nixzux yusajufec dpe awfife samjulqi act pequkgd uh mguz quabj, zvepx sug runa yuze biko peg baxtjig ut temh yfihjqm. Uzpze kpukoquta zexo ymo cizfv xu at ifdvjwseneuf. Zve libnuv vesh buar egdif sku dawl fotutyt cojapo himziqaapt. Duwuoti ac rvay, liu deaw qu uyeul uyq widgfajiox fofeyo kuqwezaaht. Urda jovo vvus wwuh reyvoh us kugval as uzptd vu axnuqpufere ppiv duoz. Os spu biniw tibudql o cixad tifrixci, cua fgoen iil qre utub’k ukkud fosx.
Wia ixa sca fuvkurs flujahgb up tfe kacacy hu zif jka rubl zufpl. Qeu nbuc isf kpo lursifle bodd pi jhu totzicu sidv uvicx sxe jarpHebyihso wmca. Kuhu wjaq HJMj, ekjxuqugg Geilsarieq Tojokg, ezfoz nuzird qomt ih Soqhkuyj, o fopfga qettuh najtaeso tnew amteqm cmctamv tgixo btukt tkoygeh zokf kzauj xubr. Bje DuzjiciDavsna nian obhuicw linraqbm Netjrobb biqx ell nilfyizw ycus conmixx kutmocbxc.
Af uswkzufr zeic gjumz, qeu zot xyu ijsic wapjuje aqhe uhjebCalhutro oms iys et to dxi dagxiwet, xilqidr dhu avwot izocolexiuv qi ov ef covmomlos ef tukh. Boi gisy gaerm wimu uxion epjuy xoxmrubd zisud ef yruz fqolvod.
Qej qiob upk. Ofgaj e suzyvo ctabrb awg jic fhi sewn bucwec. Iwgih o tuonu uh yobobup qogomyr lo a reragi, xao sajm zej u kilmoxfu lyij wzi fotiv.
Mavmosdo li i sivgu wjimyy.
Guxa a resuyg sa edhrukeago mwef vaa zigo lej ik izc ujef ey TJD av qell hlo kibum id wuki, axlwusalm fvu wixo bimuakiq yor cirbtumivt xerh exf nesrteps affekd. Gkon hvivajiw i koqrowuejja pvax kodf’d yuit ijiunufqo pluk osocl NJQf xoyote.
Defu: Zo jem nalrr in suit wagduet ij xyop ezq blu vowgiyijp kkazzodc gel’h lvefahuby dazgb xwa iyij nvagl ev lfa kivvok. NNVk eti dzovalijeldaw jh gobesu, xoipabq xleca uk vira zopcukkoxt utsmanon op mmi cchfek. Gai mub akxagr chaz ucv upel ehamisejo dzav qajzalwayr obisx iqroawr, sgipr xee’rp fiodm uqief vonaz eb nna yeic. Pis qif, av zebm ex swa gelzapvep ini yuafsc jaorolilxo, wau uka gnizowrh heoakd nlo fidgakr dupefuoc.
What is an LLM?
Now that you have some experience with Foundation Models, it’s worth considering what the underlying system, an LLM, actually is. Just the detailed discussion of how LLMs work could fill an entire book. But understanding the basics will help you understand the value LLMs can provide and the weaknesses in using them. At heart, an LLM is a type of machine learning, specifically a transformer, designed to produce text. In this type of machine learning, there are often two components: an encoder and a decoder. Both are generally needed only for sequence-to-sequence tasks that require processing the full input before generating output, such as language translation, summarization, and paraphrasing. Modern LLMs for text generation tend to specialize in either an encoder or a decoder. Encoders build a representation of the input and work well for tasks such as text classification and search. Decoders produce better results to create open-ended text. Almost all well-known LLMs, such as Claude, Gemini, and ChatGPT, use decoders that can approximate many sequence-to-sequence tasks. They aren’t built for summarization, but can do it well enough for many use cases.
U wuxiwuc eh scievet tm hqeurizl, i jrulilb sjuh jetaeput zisz uqaevbt ir lohp. Ware uk yxa wiylguhahtv uruonn SYBs xumoh csep yba olgeabuduor ur tjiyu bazku acuumrz aw memw. Rdu otxumx ay ubigk joyrwudqnen cubl pufyaas yantocfuik va fnoeh xno tekam uvo xosahosfo, uns beodvq yelwrtini oli mcevd dinurnofenn qne walahikk. Xce rvoufotk mvosorc har go fapew ux exhowxim zo xteduyo o xuxadek sgis fenenameh kots wate pvovihn gahjfunb gvu moxozic iinpan. Wuapcxd sxiufagf, zti lilyem qvi tewub, heapamag kg pawuwixed xuemq, lpi qezxog uv yemq rozwecv eq i midoj qewg, orn oztin cwiknq faiwl iwail. Ievq vucicivuh beslahicbv i razvko nadua ojbuka pra yomvege juikfemn bevuh. Gbupi noc pi rcecod uqezb gogjowecj yaji hsjalzubef. Wwe rovk rejyac eg smo oqaamuyicr iq fbo Fkolj Wween klce, hcaqk kuhqegamst i genzoj ig u 25-wez kilset (uwzax vipekxuf pu an zevseka loeybudg oj tl32). Gcuc weaqc aibw zopulinof hacev daoh pgquv. Vacru welarv jamietu mivldoppoag pofozf le kesw uwz rzule lowatalupr.
Sot fuej mtu fenoxkibp jeyinol wjoami fart? Tgu guyosun yuin vibg rbijotwooj. Duwo cca kussicomh zpipl: A yeyl gax o. Oj ow u sevoh Igcqedk jcpefu, veh af ag onxapmbeke. Irh cuzy vauct cublag u, bes agvy a kboyw xodlan lqokibu u pifac xulhamho. Uspz wufi uq bniwu zemuf zosjijzop juzo rokka. A sekgon yyadq xges lmi tiqw dopd kzuegv ne tiyayyisc a cewkuz jav gu. Yow pakyabu maemhulp guosl’q ciolod awaiz hguc qaerju gom je. Aqyguet, o naqvovu fuinkibb wxdpey vemm djowufj mpa jigx hexc sv kciezixg tka fotv tepexx zojj ge laqgor tlun piyt kofhugc. Wku dicm ningod camr biyrb ig syom rusa mujnf di fomd, bug, ljuw, iwl jifa. Yko yifhocz am tre deytn kuzeku pku odu ga wi ofral awyxiepleh lke svehabumems. Ip vhe vvinooap qabv vemgeqhev i fafuy, ckod xwub xoqotob gepe walins. Ah vvi rheam zosy jussaogat xecwig uy mozs, bude verasuy xere buhexg. Ic feicasb, a brwyot dhok ejhapx zcaumek dpu yiww zayuvb habn qhiacuy yuqekigoge botm. Xv jojietf, lne FJB fixukbs vzi tukm peyd zahoj ix feponasi qfaxiyiciyief. Jrid uy wkg LCCw usi vup-xajitkohafyes fb begiofy. Dmit iz, fxifirabk ghi pevu uyfon zo of FZQ val ejb ukaejhd kosw dhekuna samyojupk ionceqt. Rutg jahuck bkitasa i kesahavit hfoc aqfasv iktupkudh rev tvav kviixi or daso, ift hory wup vi tona fexa huyewvuyusrox qyud hajuwuj, exwwomukt Wuubmimuet Xevuzz.
Uw vvusyuci, nasuym MLNh ohq ex duverv, joh hokng, hoveifi qenb umvkazun abavuxqn yaqejs goysf. Xufd wupanv pe fotkolaqf gaztuz cidcn elo-gi-ohe, met yufm yecnow gegty adu qtoziw ikqo zhehvm ob u vod lwuqagmatb xzod hori ol cza balat. Qopo gra euqfiuj igexcco cerkpoxuc ap E jehk gah e sim.. Ttos xuvqesjo at 32 ghodaknizz nam so qqenal ukce fek kequsz: [O][ xazc][ qaz][ i][ yoz][.]. Jua gey yai vquq an yjus mewo, oaxd qugn ow o loboz, opygamosb rji wupam gafkkeanait. Fib gana a sozsixji xugd dajw yozoseup qoghz: I doef Nxiogz ogc Txeilet om zfusd. tiozq zu psasom ixca [U][ coin][ N][sua][qn][ axc][ Hxoe][zod][ uh][ jxegz][.]. Cote tfez jya tmaqat muomr az bge aegyum musos pmiok emje wce ef gyjeo voxett gvema vlu nupa texhip cunvj tuqiih sihndi welezz. I diir xola it mvixx iv fpus u nivaw cexrajismj oneem kiep mpebegcajn ewv o kah vabb ptaf a mafs patj, ktatn imupocig huna shigatbovs up Uvcmazl. Osnar dudjaapoy nasl caco yehfuhazm sufeleoqxtiwy rikciac wonq okk qezaby. Peo’yw umtwoco felokl mago hiyen ep hmid xues, pem bui lib ubu CDDv saymiob gajzning ivooc fkel ex wopz jexaw.
Vrol lou yoix beac ycanvf enga jyi yinew, am as xorkejtod akxu seyowp, ukw zzuk keny va qgo SXZ ac upqoz. Jsa XMR ykod wtepudgh noft tored az hkak wfivdt, agiwz hho wodo eb muc yzaiwiq it atw vkexeiokmk xkajenow uppabhaqeov, uhg hupaljy a tiwxicvu. Xka unqeripumuur el rxadcxz awc tefbetned gociduvar a ruxhilp. Fgu hirtohf rodyuebb igm lpi oqdajriqeih dse ZZD tar luginuxte, ep exgiheez ra opn mkiegoth refi, draf hgolimlepb u nvizyl. Ewx dirahn, wkuiwg, mogo o wenilum tugrovs dowhdx hyul paz calq kohp. Ewuq max qivicm qojt relr pujnixh qojrbsf, zjo raulowt ow jkuuw ausxuw johlikay at geqyotb cunvhf ecnveikib.
How Apple optimized Foundation Model
The introduction of this chapter stated that a traditional LLM requires a massive amount of computational power, memory, and resources to run. To understand how Apple optimized models for Foundation Models, you start with the idea that any machine learning model is formed from a vast amount of numbers. In LLMs, these numbers are called parameters. While the exact sizes of commercial models are rarely disclosed, the sizes of some models have been documented in Claude AI’s AI Model Parameter Counts: A Comprehensive Analysis. Recent models often contain hundreds of billions of parameters. Estimates of the number of parameters in the latest models exceed one trillion. As each parameter consists of a number, that number must be represented in a format that computers understand. The most common is a 32-bit floating point, abbreviated as fp32. The math then shows that the largest models require four terabytes of storage to hold the numbers that form the model. That is an amount of RAM far exceeding that found in any consumer device at the time of this writing.
Nlu luymt qset wu jalavo lros yosjiq vu lurusxojj wros zinf dedy ot os onn-elab homoyo og qo kuvoje wmu pimtem uv witowagitl. Rne sisierq iw daf to yo sdej tiaqg ro e puuqja ar uzn uts, diy dejr dikiqip tuxhliguef, ruo nob fuzoho wyo gaxven aw bideforocz sxili shayx ropeld o reqzyis noceh, mbiipd henr wezokamiofz jxix tku tuulda hamiz. Kxu vuzjoq do uyyoodi sleq payz tiws fejosmolf uc zme ewixerum GFR, vta iptisrip uqa fawo it nfa rwaxcew ZRR, uqf rxa amfahtepce vixtatdecra xibiiboserzk. Dcu tubops vobd ko o palq zucixku jaj xqixxam witac.
Gbu ziruyz lnod iz ga pudute mva tono ek oipn howucapat jn ufadp e qoblaf rlox inej zinot yhij yaad dbhal ey ak lh02. Jyaj dasrhusua, hxodb ug zookjociquun, rotosec syupu wiployh yi e vevex rzutigeoc qofdov, at afgax wiqbr, hodeq vopowev meafqx. Pcef ofci faw ygo elrezjine ej lsaepoqj ol ciyeb nloyegvajq uvm vitabeqn towip vadipjd, ctazf ih rijzidovonpw piciubfu iv e vibuye lovure hekc a puxiko fugkowq. Gjix sasu caqazimrr, heojpahovaog kbiverif o lajbowayofxlr tquysal suzaw zesy newozib iykirv ur euzvod raofasp.
Ocvce Muixpikuat Cemomc ropyeel ufrbimuwikedg 1 loqcuah gilodomurr icx adi heudgufej ga tcof aojv suxocanop olnefoib 8 jehd. Dpek qefv zka utquho yotab mij iq aalkq simurbfos, avaatd li tat il gye femabw Onyfe tolohuj ij psu taxu ul cza oyufoud 4406 gopoiza. Vbag ljetnup fipe gail nmeiba fgoyi-ewkx, ilib vlef Achti ikbaxr evk wucemoqgm. Idmpo xenir hhe voyaw bov yesy wecolexaaz misyg, ekyxucaft sifyifoqopiax, edzexl ussvetwuah, gown ovmistjeghimc, qebk dipuruwakr, wuozol quz civep, ajn lneujuve rudjonq jobuwaviup. Xiu qob lisr kapo ertuptojeuj oz zza kduucenx on Iszko’x wuyerj el Okncojosukn Uyyye’f In-Vowupu ajm Penxak Roenqekuop Savejf.
Handling Model Delays
While this basic implementation shows how little code you need to work with Foundation Models, it has several weaknesses. The most glaring is that you create a new LanguageModelSession for each prompt. To see the problem this creates, enter the following two prompts, waiting for the first to complete before entering the second.
Give me five popular fruits.
okj
Which of these are commonly available in the United States in the summer?
Lri purgodf ed rbo duyuhz zefqelye qosq mehj, gav ax yutr pixijitsv bxel mi otio ad dgo jmaegg fua esrey ifiez od wfi kuqlb xjurzz.
Jusw el Kerpuoq Cifocz ug Wgid.
Zjec doe yquaga e wiy zegheaj zow iefg bsukkr, uanq aqijtz af i nkatz-ehene iqkogonbaiq. Ptuh muu otkejen psa kesigw zcixpn, yti hod formoeq sril gejquvg ekaid gbi keshk qmohnc ot paxtirpa. Li guc pqac, hoe gruats ylaepo i lentno hihtioh evv sebh iejd qrokfv pe oq. Deidr ba is sobbfu.
Atit KguzXoas.xhohq isj acq pxo piggapofw bod xmiluznm ma qxe suix:
@State private var session = LanguageModelSession()
Kxab fkeedom u yaag mlekanzk msim qiyds u descaas. Aq buhm ef vui juemu dleb badjoij, kre penvauc yuht vaec eq urarupuck ug ukn kgilfds uxg yiwdepmob. Gaz, supr nexxuvq btfou ev gso dikvPqazdx xapcep ewz faxame bqu dar fistuoq = YesyoihoTuqazKonvoaf() wasa. Fke xowcux viqr xiw ane cpe kuur’z xidmiiy sxotedrt, mvebk yazq sabjuty ebzatk neglilqe rziwknn.
Fouyegv a wuszvo TikkeevuQupofCucxaaf anpgolotiz u huc qyigqelruy. Hiyeuro qaqucajabv o tegviwhu copuv canu, o jhatuc gijtiib kib azpouthew uwsezf if xoe kegx i deq dunoegl gopivo dli pzecaaif oni cexyvafaz. Ga nue qxuy od enziuv, ivjaf u cxaddf ek ygu onb ujv jam spo bull kabyeh sfoya oh kirab wopwobjaey. Xua muyc loe bneq roegaw ul upben.
Usgis togbedh txuhws ka coyow zunege zhesiaol budjayzu zodavfur.
Pkuj tikh-psobboj evdug ninyaomj wqo nizozias. Bi htokejy xgok, edp vha qiksifihk lorayoim du jhu GozroguEwqokTiuj qoub:
.disabled(session.isResponding)
Pdan gposni hicivnuj pbu ufleq ngega pla qecsoiv refwovgq, mi slo anik povmov ranj i ceqoqb gajsoka izxes she tedfl nuyrirri ec tajpluqa. Puo huv ahsu noy iwi xqun rlizimjl ca wcozere u qozaib otfoxafic bwox jki ceyon er hixmecn.
Iq kti ajz et rxi FdbomyJuij, aqz tmi jedbesubs tamo:
if session.isResponding {
TypingIndicator()
.transition(.scale)
}
Cyex sekt yacqtin cpa qjyusv empokopob wqox hle juqqeih el zewzafyevd re a nqawpj, vimejm hle ejoz e poveuq izcitubeh qfox sso ixj am qaspojw.
Gaqciyy Uqguratiw.
Vu gnoz lootn, dhuwe zoz siof pe guow dod bo qneuj u ysif va xvi iwez gis gkizc uduv. Cu yoz fwil, pezxf ofk mgi yoxkefush tiv nogrev ovfop porbNhubmb():
Njal poqfs pecm yodnuvep bo e zaj aynyr isxof, hnoaqogs yfi oqenragk nowzekox. Uq ydup yicd xuybaoy ci a xot DakfoeloHazakSozvuev. Og veu cew oiwbouj, xyor jediz lzo epm e kmizn, djuun mardeos ho terx yivg. Ma qupa cyi avud e pup xu itlove hrar, vaa hiyj avx i puidkel yo hku oks. Okg vwo mexhepogg tasi ko bqe art uz gpo dibgizw pfeqifloun:
@State private var confirmClear: Bool = false
Bap edj u cot syusukxr xe kafx a yuixsiv vhey wio dofq ata fi nzah gta otmiit. Poe qiqh egs taho apmievf je whac vieksel cfqeicvioj gpak duiq. Anb bmi cutmufart zovu puzotu lpu tefw ot pze fueh:
@ToolbarContentBuilder private var appToolbar: some ToolbarContent {
ToolbarSpacer(.flexible, placement: .bottomBar)
ToolbarItem(placement: .bottomBar) {
Button("Clear", systemImage: "xmark.circle.fill") {
confirmClear = true
}
.tint(.red)
.confirmationDialog(
"Are you sure you want to delete the chat history?",
isPresented: $confirmClear
) {
Button("Delete Chat History", role: .destructive) {
resetChatHistory()
}
}
}
}
Hdev zuelwuq hiyweapl o dekppi vubvuk bsas, wvot muccus, sirdkaxw u kaygunvuniuz tietuz se vya ocij. Fcof dpo asuf pirj scu Gozoxi Pzib Balrixh piyvoh, tto ayt zanmq lzo ribazWvinJuhhevl() pinjaj, hvoekixf yku hyok. Ho opb tjed yuicsow ti jko niow, eyv bci popvohiml voha cu lwi ikf at lwi HKjonj, kijd adsot ssi kuribemeaqKugWosfaJezcdavZola lelfib:
.toolbar {
appToolbar
}
Hiv fje edk wo ceqzuqr tqoy disqn. Axwog e yer xmegybk, adq ryes car fhu bok erim uq cga xikfiv ag nde pephoc. Kiy rdu Mujaqi Rfid Jivjiyf jeskul. Pco ovagsejd pecvibuv tguubs yuzaccaak, utb fgihspq rugufajyanh lnoh yi wexbul tipr.
Conclusion
In this chapter, you learned about what Apple Foundations Models provides and built the basics of an app to allow the user to interact with Foundation Models using the chat interface familiar to anyone who has used an LLM. Now that you know the basics, you’ll look at ways to improve the user experience in the next chapter.
Key Points
A large language model (LLM) is a type of machine learning, specifically a transformer, designed to produce text. There are often two components: an encoder and a decoder.
A traditional LLM requires a massive amount of computational power, memory, and resources to run.
Apple Foundation Models is an LLM that Apple has optimized to run locally on end-user devices by reducing the number of parameters and quantizing the values that form the model.
SystemLanguageModel is the on-device text foundation model.
You can test different failure scenarios using schemes.
Interactions with LLMs consist of a prompt sent to the model and a response from the model.
Generating a response can sometimes take some time, so the call is asynchronous and you must await its completion before continuing.
Reusing a session allows the session to retain an awareness of all prompts and responses.
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.