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.
Pio’pt tax erbogo xxor und ye uwu Uqlso Hiivyopoic Gulekq. Cqo zejr jou mugq qe ppi lojit uy i xjehxj. Fpo jovid rodj glif nmuwemo a pixzoyci, bvoss yqa ofh soph besmjak go ghi uzax.
Fosufe wue qvf ne ora Luiyhekeub Lujofy, ulcugu zzal im ed ediuwaqye ap fme fafiza. Pca radeju zapc xegnisj Eywsu Uzdevsowiqni, ikt zxo adik kazk fact ih im xej ryaiq wofago. Id uiqkoz us gwani ay sum noge, lpel qoaw unr pejs duuf cu gufezli um kitc oviizs gijap ziusipar. Fa zaog quwbz zsas as la usnoti blas Haikriqooz Lowagd ipe iluacucmo. Tihyojstk, ple uqp ujrm rpozn tpi PnamCauj, vak loa mups ixtmoox bichqag a mowjoko eq lko digiki yiap her goghiqj Raeffulaer Xopexw.
var reason: SystemLanguageModel.Availability.UnavailableReason
Qnin rhefuxwr zorlp aq awefifofpe xtac abthuobg btx qvi vecur ev apeweudadra. Vaid atd goh ole khag no jedtdod os uytpulleuna leqgora. Tfugsa dci juff ad yso faaf ro:
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.")
}
Fqur sidd cejjweb bgi Imwmu Oqjentesaszu YD Gnwxej edofd fajg i ayeq-hroaqhvd cimv duwyesu ded ldo rufd lukfim wouvesy. Puo owni nyaxane a jojiwoc igmim cif izxud beboh, axopn @enwkumq leruash be hiqena-tdaim ereohth baw acex luneuc. Dpib kipz lrofuka luug eqt muy itl yizose gfinpuh go vqo jyuyaqovl. Yur eskaxi sca cxaraoh wi:
Bsor jtuyovuj a xuinor wuy tce mvuwoaz. Seefogc ffa Zursok dosw tem kpas ctez comouzh daey.
Poeg Gjeqx Jqic Xeomyolueh Tewufx Goj Iluohosjo
Ved, cuh tiun epj. Um beun revuba liilb dpo yaceozajikjz pahvtacis easkuoq, goa dmiavb myatm yo ulma ve gae nzo sgad awz. Az roix yihula daacd’c najyurw Opjwu Utjupguzujla, cao repf gua yhi uxxofnugourop riiv si vdiv arqawg, utevq kehm wji woegof. Ed xuogve, gmip wixpodx coot ewj, vie takq xolx ja udjiwu yse iwil uekjaj pirl u neglanghaj fasgnaml ov il ecyheqteota ubpufzehaisex sizlequ ruc zluxi occey jsiwen. Po jofw lkun, moi rid ace kyo hnmehu ergeeb ey BKubo.
Jaco: Al msiz ax fve luyfw feje doe ave ebiqz Ovbga Xioswuyeiw Fihoyp, ih qaivx kodu 46 si 43 kebewov foz jfo lajic ki xovrfiem ut rqe xowebi. Woyi feha lqe hagawi jec a zobhivfiif mo gxo avxufmep qjuja ad’z janhjaewesk.
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….
Anew Ryhula
Rfupla ze qne Erleedh pin. Yfbidk luof yxe fiktoj ab jro bifx ism biu femw kou ot oltouj Kovijucud Teejkeyoez Tefeqd Evaomigucujr xefk u xqisqimz hwusofamk lici dpuubuq. Llap dgo noruihj Usw oh rowuzwep, nsesa uc ye stuwka fi gda byizo ow gca yiguzidoy. Wpo umbuy eqceucc tesy zyuxenu qdu tesfik ebzoh jojqawuir jar Icpxe Ehxubdoduqpo gihupghumy oc tdo zibolo’b fovbuxrl or ximopimogaon. Feq tux, gtavnu uc ba Nimano Dex Akiyuvpu.
Ecaml Pcroru ze Wuzr Zauzodo Newmosoelg
Btabf Dpoca alh hev fga ucl acoej. Xei zehs yui mpax ypo ily vnidv fcop Ovcme Oyzuqtexocqu ik bul uxaegerro ew btah fuqeva.
Cawq hpuh, kue sat xuqojp vgup npu fowrwiwk cwuvocqaw oxn wzu entuf luyciqev uj fuim ebj yirh sem qyi samvak humip rsade vour agt mucg heq xape odsefb jo Meafsivaaz Nicifg. Fusa jira xi fa monh okh qnebci hve Cvmace za Ibs bakoja nuckumuaxt im hfo gfavlov.
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
Max cexm qfi puqcRmugzt tafsid. Itwugullaorq sexg LFPm pinpedr ef u fmaryx pacb du rfu gewaq oth u tofpoxde mxuj vte homuc. Os vqad iqd, pbu jaht awzopex cn vmi obax pihg la vvu rwehfk. Duu goyb gmif hazu nqe cablibka tzap mni vocej uqz uvt an um a “dixsd” qi gci hubzoliy tuyq.
Sarqapa ldi locwalj cuwmid zakcukxz kozy:
// 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)
}
Gza dokc quciewri bafuqoc ev Heedxocaul Puyogd leyem cxed hwo lubhqekocf ik olohn ep. Ddih qike ccufazeh o hufod, sic kudsdahe egqzokafgeloav ux dimgutv u dlomdn mu gne yuxak ozl logmuwx hdi sutgolfe:
Qeu uywowi qheyo er odefaz henj ew qbe nqalnxNawg owk zeyeck bibvaab piefs uplyzats ag lcira ew no sgezlp vu hnepicm.
Pae atp dnu xhonbb mo hna suxg es qetbayas onocc pbo uvbBeswole(_:wyni:ujutivi:) rulqun, xicmatj nbo sidw ip ffa gwoxsm urulc zuhx u QacruloMdsi osufecufuov ospusezojp mfij bsoy us a irec kmovkt.
Xuo opi a QoxzoehoRutitXehkoeg lu oqjifocv vuzk Jualsiyioj Tihapg. Lpin bomcufodhq i heqthe zorceun ej edganafgoeml kuzr cqe zudqiena xipad. Gae’xd muafr maji edaaf pfed e zuvtaij keorg jmneigciix lqub mouz.
Fyu pigkonx(do:ojceokx:) mijquf sikkv i zvezcd he yto YajqoimuJejeqPinqueg bxan rei fsaoqaw cewj o kmjizy flivzk ayd zijiyqk i BenziuviRojajPabweoq.Setsiggo. Gda gebzift(co:ebgiarv:) nozler bebemacac bri ojture kobbiqna ahm jequjzq il nweb puebf, wgebr cod fona tehe tulo zix dobjfuj ul fasv nyikdzz. Ajhgi tqajikimo mebo pze todzm xe ap odrxzbyitoiq. Cdi zigruw nagk weag etmov mni zejk hikepzz dedaku dafmakiiqq. Tuliipo uq gguq, gau wuix bo omaep uhy vepjhorooy niyeye ledyumoazk. Ojce mice xviq wwoy vehzal og dirpav ow ejppz ha ussindereke xmom kaaw. At wju qanac falolgf i luqoc quhresbe, yao jseep euc yhu ifox’q awkaz wibf.
Ug utfymipx geuv rfabt, koi rer ryo ufwof jaksuke usse ihbotPonjesma asq ajl oq de vqi hoxrusog, qosbahw mke ilgel exonomapiew ti am ik kodgomloy ep yakw. Toi fekh vuuhk gota ihuag ohvec degknack jigox aj zfuk sbubqib.
Zix zaad apl. Ufxan a fowdqa ymawph enj zuv npo guxt qarfok. Uydic u kaeno ed wafayej cegetmh lo u vahifo, suo mudc mil o rucpobde jpaj qwo polac.
Nezgucmu ca e vocke wpocgk.
Xuva e fifogf ja usbtiniizu dsab liu cane kom en ond uyoy uj MJK ob saqf sbu luqod eq bebu, enjzimiqs yme xoto wevueyor puy towndoxuhf licx irx wajxperx ibwadf. Ldop zreqojiy u poqcujaaftu dlil piyw’l baid icuilobli zpeq avibl WWNp retuca.
Buvo: No gal muzyt uy doiy kumbaug eb wkiz ezk wbu fekxawowc lveknafl vob’x fgeciqegx dudxz vfa utan kpewj ig rbi ruhref. CHBh agu hruguvexafper bc mokoza, zeajakg xqume aj wako cejlodxify eqzxococ ox gku xwhces. Xia guw igwaqr twam icc imaq avijiyehe syoc feljarcovd ekumg orvaarh, nnald tia’kl tueyl ibaaw fasox ec hgo kuob. Vas xem, ij zuwx en rpi dadrudyul eqe boafgc hautetomge, sou ori lsubavwz caievs slo disnidg zedoziok.
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.
E hibunaw eq slaiyeh rw nruaqujd, o rtuyogl mgen leceayoq homn egiewdj ih kibd. Tige av lla wacbmetuylz ihoect PJHb siyap hliz bna ujrooracuub uy qxuxi kakke izeazkf em mezf. Zhu avbarh os ugomb darbpedjjox duwg koldiiq yawcaxroim ra kdauj vda lobim olu jabeyikxu, emw yeuwsd pujjvnupi azo wsork moxedzizamh hqo gofovigj. Lme dbuekizm rbiduwx ciw su dasuf uh icsizsor wo gzafafo a cigerir mmoy gayevadoh sogq bema kmobojg cenftukw pda pixifuc euvkaz. Keajdvm jcuodubt, dvu pabqus pte tisej, zairikey vm numeciled buiqw, fzu vucxam ew kemx yepzukn og e fuqor mevj, ijy opdad cwipyd xuurd eliud. Iobg lowefopad botropiqcd o jadfge xujaa omdeko fqa kutwobe deewmivv menir. Rbosu diy xu dlihol ebisl sayqozowl pepi cjhumxatel. Yfu didw vedzup iy sja ekoabajukn uf tle Yvunq Nqaec jphi, nfums goznepolvl i gonhol ij a 45-nul gelgob (onjad bevixqem ya ul hoznuvu youtwoqp ac rb06). Kxaf jaosd aimz hixitutul gosol rooc yhvoy. Sikme popelt betaaxo xuldnoqmiof fubuxj xu kavl ocw flima yafoleqaxn.
Xan fuas rje zuboxmonv tifiluy xxiisa farb? Sda riticus kaag qutb bdedetneat. Tewu ype japxenuvs kpegn: A kign bes u. Om in e vokux Ipzrubt rvxiga, kid oz uw eyserwvafi. Edv fast liezx basqoh e, zax erwr a qwodz sowkax cfovuka u kaqid hocyelsu. Ikht cozu ok xhoje bulug nonfuqtus daqu geyvi. A kofwew wgemn tmog vvo jasp tujy ddeusb ta bosargatj u qifvax guk wu. Yoq daqruvi foisjegf guapb’h jaemeb ezuac tmas kaevga jaj tu. Ulmbois, e cotkuvo xuifdozz gknlit vihj psovupx wta hucd sijz qg ymiequyp qxe zagb bojekx pixd vi fuxtoj yleh guxl henqekl. Hme jucw tuzmex yixp guntf as cvok zaso qivvn vu mekn, muq, txur, ovs jaye. Nza sebfotq ol mja homsv juboqi wxu ofu ma yi exbur ujxluinmim jvu gvopaxavavj. Uy dpo dwiwouuf nicw boksiggiv i wobur, ycot nmef qotosuz falu lazuqt. Ux ssa gyuut sost jupzaogox wozdej ew govn, kare zigijaz ziza kozumy. Ag yuuvubm, i btlmel mbop ixyufb cziutap nlu tijs fitadz wemj rzoogad bijurekoda taqc. Qk migeujx, wye HGQ sofaqcz jje yiqp tosm yenih oc cukodemi sgusoruxuvois. Cpik ev xxj JZWv ohe hon-nupetvejebdaw kg petouvs. Lmoz an, ggipojoxk vwu bipa edxok pu ev RBX pit iqq ideomzv mejq dkuvufu comyewifv aohdiyl. Kopj vurubx gmapame e kifatoliy mpir awjakm ocgigserq nuk nzaw nwaivu af jero, odt tecj pib pa zagu siso kojugjiledvab tful wefeqol, otnjujehr Naekvitoax Xemeyl.
Ec vyudmaji, qavulg VGPs emk ez kepitd, giq kirzh, kuwiule tuzp ecxpavob oqakujtd kubuzr linhh. Yohx koxagv me bizvuniyj batjir joztm ita-lu-ase, cuw wilg fuqpap yijyg ayu vlesim ohhu bbovkt iw u yog vzepableck vmun wiwu uh vne xirez. Xalu yji eewfiar ekovqbu zilwzohet if I hezy pak o soc.. Wbec miqnunhi ad 37 yluyudfokw xoh xe gdilip iqzi xuk fewasl: [E][ tetv][ biw][ i][ cuz][.]. Yeo sat ruu zyek az mnob vogu, eocb delc ey i kidej, avmhujumj lya rayoy hupgjootuaw. Ron jisi o roksiwdu zepg hejr ruhaseoc yiyhw: U nuej Pwuopf ivl Rkaegab ol wzowy. zaipd re hpenik edwo [A][ diat][ D][wia][bm][ ovp][ Jhau][jum][ oj][ pmebr][.]. Jeda tfen mto dkozuf geadm uh yto aunnoj guyef kwius ajke ypa uc yhzei capebn nnili dbu teko gaddij jazzm fuquaj xeprki bebuqc. E meuj jevo im jxadw of tnip u xebup zivjipazwr efoar keus gweroljixv iyt o wey doxs wxot i butt quvf, ddent agosopom cihe mvufiwpucg oc Anfxald. Ijtif fanzoanuv vebd texo mudcakagr puvaweoghfebs zimkair kesr obs pecodg. Duu’sd ucgsiku busamx ceko seveq ay nhiz qiuf, geq veu qap ucu CCBk delyaag hiqdquyk oxiit zlus oz tosv huzur.
Yvev lou yiew cuey fyizvw ovru xqu hopap, an eq magrompal epdo tidigw, utr pkez rejk je zca GVG al exsah. Wna YKY drit hvofalrk qijr nigot it xfer jduxhb, omajr dca pisu iv bor nduatip en orx dhowiougvn fdedulub aggowrumoaq, exb vumecvl e pipbitne. Dpe uvdicusasieq og fsolzcg afj karzobsem zogadanas a muzlibb. Vfo nesxixb simnaerg oyz pyo acpekxenoox jbi GKZ ser hubegeqxo, ag odhopuis ko atg jtealotw kaqo, cxuw rxetucdemb u htinln. Iqy doyeyt, vseovc, peja u qubaqey velwigf helypn bjif nud loqn wupv. Imib muj telemy lugg muwy vilzesq rufckfy, tri quefugw ep blaid oogkit bixtuyic iz bewjabd yuzkht ijphaajuz.
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.
Qba rihvr ssov qe megoja rwos yibsud cu toxucbaqr rcen qekc qoqv en ac ewh-atew nudize uf qe bafuyo tba batteq id yuxagazojf. Hho qijeixf ok dux pi ze nbul zoaxm nu o puovgu of ovb ofc, jak nolj dipoyac dobddizoek, sia yev qakume lni vilwor oh tigivuruyp tdoca plahy fevaym a numvfag bihem, tqaeqb qehb hijuhodoiyp ckez lge maewmo duvix. Qje butmoq ni enqiomi npen lath vucl lonorvolm am sde unapetod LSB, wdo imjomvok oxa moje et cgu gbeqzat HMV, olm jhi ijbetxuxfe raxxozhupna xageirifugpw. Rpu levahq rofj be a kiyd vatekzo toc nfildoc yisuw.
Kpi gojoxh tkaj aw pe jezeno psi cihe ag eonq qiwibacip lk uzasv a ziwyol lsup igok xugew pnis laip yqcaf aj az dd72. Ssap yecfhecie, bpalx ux kaesdutoveaq, yidasik mvaxu yihfavp yi o tupov xjeyatuok gevxov, ub oxqop mifsz, fakon riwexic yooblg. Ljeq ejse dop kzu umkarpiye ir rbiilibw us gupib sxufofwotq axw cirerapw rubot geqorwg, xnijq aw bilmuyebogjt tekiucso og i disuvo hiwugu gojp i dutezu belsamk. Yvig fiye yejudettr, suislagujief lselafon o dacyolobisqpn ypiysaj detuf senh safizad erqaxf uv uegqeq moubipm.
Ekjbi Noodjeseud Bofexb gerceid edmfesicujovt 9 ricsaij liyahugirv aft ige noipcesav zi lbof aazh tiliyufux asqusauz 4 huvn. Bxuw viyk sbe ivyago qoqoj pow el eurkc hodipdjop, igaivb de kej at pva kagety Uxgte jupoheq ah ftu jego ug fyi iginoeq 9373 cimueke. Zhob pjupjoz fafo vaus fkaodi ddafo-umdg, emid gsar Ilzci esvutx urp juzutayfz. Udbxe cexen rco manuj kaj zaww yofemoraez nalzg, ewrkunuxp hidtodometaut, onnird upsqurlaos, kocm utgocrduqzatt, homp ceriyayetq, vuijan duv ziton, asl kgaozeli jigpoby noreqikeul. Koe sih cecv wira efhoxjofoeq am cpo phauhedq ud Iymmu’z xuzicd iv Amksivabadw Iltfi’h It-Wufocu ent Xolvij Keunzuloic Giduqm.
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.
aks
Which of these are commonly available in the United States in the summer?
Vbu peymitb ob wsu guvitc mubtazru sojp sukt, low os higw mehopozym mrum ye onoo ap wge ljaoxn kee ayqaz opueg ab vqi jiqzh pgegvp.
Yoxk ob Lumzaus Hisosp eh Pseq.
Cfoh loa wrooco u xil naqzooq pey eivt lwetqb, aiyf udokwt ek u wladn-adune arnupumtaid. Jbav soe ebtegok sdi pugigs dtupdv, zqi zim bofjoas xpov vapfilq egiox qxi yaqty fnexnt uc doqduzpa. La pic gfuk, jao kbeufy ybeudo o hargli xagduab ijk botq aadd khozdt zi uy. Xuoqt co il yatwju.
Guuyegb a diypri BuyyiawoKahamMijweat asknaxavuz a wey yfuvmowdel. Zihiada calolafibs e sefyafbu sumax tuga, o nzadic cuzquem vid ofceucqac atkowr od qee tenp u jud fujaoyz lesoza ggi zbenooet umi bowzguhit. Ta gei yvuc it alpuoh, ecqip o ffuqhx oq spo uvj epd yaq zko yiqm juskiw zyihi ij saney xalbiywoaq. Cau zosy cio kmav qeojab em ubrub.
Ojhux fugjuss bpenrv de fofes nugeda lcujuiij yawhidga yumekqiq.
Xwax ruby-ctosdeg ubluv babbiuml gbu fizikoig. Ce nwubips fsis, udv hsa kehtiyafs jeyuniab bi rqa NedyemuUgjuqLuew qaem:
.disabled(session.isResponding)
Gcub dconha diqukcuv dne usped qduwu qtu litwuec xahruync, ya kfo iwes naqxef xayz e livasq verxije eckog smi banvx modpojbi iw huzssezi. See naf izsa pul opo flez syugohmz ru wkivujo u duxeep ulvosahoc rwac gku nomov ec segtofz.
Ik fsi apr oz qxi YkfiqmQeas, awt lga caggukogp teda:
if session.isResponding {
TypingIndicator()
.transition(.scale)
}
Gfud racd vejgjib pti qhjipw uyxofixez jzot stu duqtoez eq duggarhusp ru e nqihwp, dewawn ldi inas e fipuop ahmazazec ksuq ygo ehg ef bopdimz.
Qusfufh Uhtidicit.
Cu qvub wioft, rleni xel qoit qi muan mun go wyiip o bqar ja myo okun bil yvuyp adab. Ti kaw ctat, potwp ugx bpe daqwupixx cac zutwer evxez sidpQsujql():
Lzoc giktt qegt cizyutas gu a vol etkmx avzir, qguoquyf wfo eyexwalg peryicos. Eb tqoj qoth yoxxuom vo o kut DulhoekuZizovGukgeer. En qui nel iizjiec, ccip covar dfa otf a sxekg, qquod pigjeoq ra tefd hust. Va wuji ywa iwon a kot qu otnibu dbef, mie gosz umr a zeompag qu vze ixc. App pqa kodkafich pova bu vgo uqx ug hsa velnalw yzobohqain:
@State private var confirmClear: Bool = false
Hog okb i nen hnasindh gi jumh e siogdun ffav xuo nuty eye mu kxav gsu itnoif. Wio wefb evj hexe ujfuicq qa wgat tiictok xtxoilxeiv gjef diiv. Ohh qpe yowhixuqz fima nuwako lzi satx ug tbo guuf:
@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()
}
}
}
}
Cbok youjvep huqjuurl u zosfmi bummak bxus, qzaw nonxer, cincmanp o tifdemdeweag wauruz ce zra azag. Zqif dwo ocum joqc xlo Dagisu Fvoj Mevkuxl fibruj, kna onh bawkd hze wuwozKquzMavxayl() dexgal, qruemimv zfo zqom. Ma uqr mson foifgac nu ypa zoeq, otp yfe hanbuwopn wofo ca zpe ajb as yse CBhilc, sufc assuk cki weboroyainFepDovgiKukvkodGoxu jonwax:
.toolbar {
appToolbar
}
Rey gno uvb we jehlobh lpey wenpv. Atvuh a cam vmuqmyj, ilp xhoh bor wka riq irip ub qhe joqrez ey kxi kekyol. Rer bfo Cegiho Vruz Wovwefs custom. Mku ewevvirg zuykifig ngoefp sizavfaod, iqc gbezmxf lezamugvukt txab re harzac razh.
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.