This repository contains a collection of Swift playgrounds demonstrating how to interact with Apple's Foundation Models. Each playground showcases a small example or tool that highlights a specific generative capability.
✅ Free on‑device inference | ✅ Privacy with no API keys to manage | ✅ Offline access (zero remote latency) | ✅ Maintain small app size |
✅ Simple integration | ✅ Structured output | ✅ Tool calling for agentic use cases | ✅ Will only get better over time |
Basic.swift
– A minimal example of chatting with a helpful assistant.BasicChat.swift
– Shows a simple back-and-forth chat session.ChatInstructions.swift
– Sets instructions dynamically for each chat run.CharacterChat.swift
– Role-plays as a medieval knight in conversation.ChainedPrompts.swift
– Uses multiple model calls to build a story from a headline.ConversationMemory.swift
– Shows how to retrieve the transcript of a session.StreamingTokens.swift
– Streams individual tokens from the model.ShakespeareConversation.swift
– Chats in the style of Shakespeare.ModelAvailability.swift
– Checks the availability status of the system model.DynamicTranslateOrSummary.swift
– Switches between translation and summarization tools.DynamicTriviaOrDarkMode.swift
– Mixes a trivia score tool with the dark mode tool.
ArticleSummary.swift
– Summarizes article key points in bullet form.BookSeriesSummary.swift
– Summarizes multiple books in a series.BugReportSummarizer.swift
– Summarizes a set of software bug reports into key themes.CodeSummary.swift
– Summarizes the purpose of a short code sample.ExplainConcept.swift
– Explains a technical concept in simple terms.NewsSummary.swift
– Summarizes news articles concisely.TranscriptSummarizer.swift
– Summarizes a session transcript at the end.Summarize.swift
– Summarizes a block of text in a few sentences.StructuredBookRecommendation.swift
– Suggests a book using a structured format.ResumeGenerator.swift
– Builds a simple resume with highlights.RecipeMaker.swift
– Generates a recipe based on user ingredients.MedicalCase.swift
– Simulates a multi-expert discussion of a patient case.MathProblemSolver.swift
– Solves algebra problems step by step.TranscriptReview.swift
– Demonstrates capturing and reviewing a transcript.ProductComparison.swift
– Summarizes differences between two products in a table.ChatSummary.swift
– Summarizes recent voice chat into bullets and action items.ExpandedThought.swift
– Rewrites a short answer into detailed reasoning steps.MemorySummary.swift
– Compresses dialog for long‑term memory storage.MetadataTags.swift
– Labels text with language, sentiment, and keywords.
CodeCompletion.swift
– Generates code completions given a snippet.CodeRefactor.swift
– Refactors code to improve clarity.CodeReviewAssistant.swift
– Offers feedback on Swift code to improve readability.CodingChallengeGenerator.swift
– Supplies short programming puzzles with hints.DebuggingInstructions.swift
– Guides the model to debug code step by step.TestCaseGenerator.swift
– Produces unit test cases from requirements.JSONGenerator.swift
– Produces structured JSON from a model response.SQLQueryAssistant.swift
– Converts natural language into SQL queries.NestedGenerable.swift
– Demonstrates nested generable types.CodeSnippet.swift
– Generates RealityKit physics code from natural language.ModelEntityHelper.swift
– Produces basic ModelEntity properties from a prompt.
AutocompleteAssistant.swift
– Produces text completions for short prompts.FrenchTranslation.swift
– Translates phrases into French.EmojiTranslator.swift
– Converts short sentences into strings of emojis.Translate.swift
– Translates text between languages.LanguageFlashCard.swift
– Generates flash cards for learning new words.LanguageIdiomTutor.swift
– Explains idioms with usage examples.LanguageTriage.swift
– Classifies user requests by topic.SynonymFinder.swift
– Lists synonyms for a given word.VocabularyQuizMaker.swift
– Generates multiple-choice vocabulary quizzes.
CalendarEventTool.swift
– Demonstrates a tool that adds events to a calendar.ContactLookupTool.swift
– Implements a custom tool to search a contact list.DarkModeTool.swift
– Example tool that toggles dark mode on a device.GameDifficultyTool.swift
– Tool that sets a game difficulty value.HealthStepsTool.swift
– Records a daily step count via a tool.SleepDataTool.swift
– Example tool that logs sleep statistics.StockPriceTool.swift
– Retrieves a stock price using a tool.TriviaScoreTool.swift
– Maintains a trivia score via a tool.DynamicWeatherOrStock.swift
– Uses weather or stock quote tools depending on request.DynamicSleepOrSteps.swift
– Combines sleep and step tracking tools.DynamicContactOrCalendar.swift
– Chooses between contact or calendar tools based on intent.DynamicRecipeOrWorkout.swift
– Selects recipe or workout tools for each prompt.NumericConversion.swift
– Converts numbers between formats.AssetMatch.swift
– Selects the best matching USDZ asset for a prompt.ColorFix.swift
– Adjusts a color palette to be color‑vision‑deficiency safe.MockCSV.swift
– Generates synthetic CSV data for testing.PoseStats.swift
– Aggregates head‑pose metrics from visionOS sessions.TelemetrySample.swift
– Analyzes telemetry to assess cognitive load.ContentTagging.swift
– Generates descriptive tags for a text sample.
ContentPlanner.swift
– Outlines a weekly plan for social media posts based on a topic.DailyMotivation.swift
– Provides a quick motivational quote.DailyQuote.swift
– Creates an inspirational quote using a generable structure.EmailComposition.swift
– Generates a short email from a prompt.EmailResponseDraft.swift
– Drafts a concise reply to an email.FashionRecommendation.swift
– Suggests outfit combinations for an occasion or season.FinancialStrategy.swift
– Offers financial planning suggestions.MarketingTagline.swift
– Suggests a catchy marketing tagline.GardenPlanner.swift
– Plans a home garden with planting suggestions.RoadTripPackingList.swift
– Generates a checklist for packing on a road trip.VacationPackingHelper.swift
– Suggests items to pack for a vacation.WorkoutPlan.swift
– Creates a workout plan for the week.WorkoutSchedule.swift
– Produces a workout schedule with dates.TravelBudgetEstimator.swift
– Estimates travel costs for a trip.TravelItinerary.swift
– Plans a travel itinerary for a destination.PitchDeckOutline.swift
– Provides a structured outline for a startup pitch deck.VegetarianMenu.swift
– Suggests a vegetarian dinner menu.MindMap.swift
– Produces a mind‑map outline for a topic.SlideDeck.swift
– Generates a multi-slide presentation outline.
Haiku.swift
– Writes a short haiku about a topic.ShortStory.swift
– Writes a brief fictional story.NaturePoem.swift
– Creates a short poem about nature.StreamingPoem.swift
– Streams the lines of a poem as they're generated.MovieNightRecommendation.swift
– Recommends a movie with a rating and reason.MusicAlbum.swift
– Describes a music album using a generable structure.MusicRecommendation.swift
– Suggests music tracks or albums based on mood.NovelOutline.swift
– Produces a brief outline for a novel idea.SuperheroProfile.swift
– Generates a profile for a fictional superhero.RiddleMaker.swift
– Creates a riddle for entertainment.TriviaQuestionWriter.swift
– Generates a trivia question with its answer.SpaceMission.swift
– Imagines a conversation about a space mission.TechPanel.swift
– Simulates a panel of experts in a tech discussion.FilmProduction.swift
– Provides a short film production outline.TrendingTopics.swift
– Lists currently trending discussion topics.NewsHeadlineTool.swift
– Tool that generates a headline from news text.NextLeapDay.swift
– Shows the date of the next leap day.MoonLandingDate.swift
– Retrieves the date of the first moon landing.WeatherReport.swift
– Generates a brief weather report.ConstrainedCharacterProfile.swift
– Generates a character profile with guides enforcing structure.RegexCharacterName.swift
– Generates a name that matches a regEx pattern.ImagePrompt.swift
– Creates an image-generation prompt with style cues.ProceduralTexture.swift
– Derives RealityKit material settings from adjectives.
InterviewQuestionCoach.swift
– Produces sample interview questions with brief answers.DebateRuling.swift
– Judges which side of a debate makes the stronger case.SocraticGuide.swift
– Generates Socratic questions to lead a learner.
GuardrailViolation.swift
– Shows how guardrails handle unsafe requests.DenyListCheck.swift
– Checks prompts against a deny list before sending.SafetyGuidedGeneration.swift
– Uses guardrails to filter unsafe output.SafetyInputBoundaries.swift
– Adjusts prompts to keep them wholesome.SafetyInstructions.swift
– Provides strict safety instructions for the model.DataExtractor.swift
– Extracts structured data from unstructured text.SentimentAnalyzer.swift
– Determines the sentiment of provided text.RedactedEntity.swift
– Masks personal information in text.LLM-as-a-Judge.swift
– Evaluates answers for closeness to an expected response.RefereeDecision.swift
– Picks the best answer when agents disagree.
CityInfoTools.swift
– Multi-tool sample for city population, area, and timezone.AnimalInfoTools.swift
– Multi-tool sample for animal facts, habitats, and diet.PlanetInfoTools.swift
– Multi-tool sample for planetary distances, gravity, and atmosphere.MovieInfoTools.swift
– Multi-tool sample for movie rating, director, and cast.PlantCareTools.swift
– Multi-tool sample for watering, sunlight, and soil needs.RecipeInfoTools.swift
– Multi-tool sample for ingredients, steps, and cook time.CarInfoTools.swift
– Multi-tool sample for price, fuel economy, and dealers.ProgrammingLanguageTools.swift
– Multi-tool sample for creation year, creator, and paradigm.
AutonomyGoal.swift
– Demonstrates a self-directed loop toward a goal.ReasoningPlan.swift
– Breaks a task into ordered steps.MemoryLoop.swift
– Summarizes conversation history.PerceptionObservation.swift
– Extracts changes from an event log.SelfReflection.swift
– Uses a critic to refine an answer.SafetyCompliance.swift
– Applies a safety check tool.ReAct.swift
– Implements a reason‑act‑observe loop.PlanExecute.swift
– Plans once then executes sub‑tasks.ReflectionLoop.swift
– Refines work via a critic loop.HierarchicalManager.swift
– Shows manager and worker roles.ReWOO.swift
– Plans tool usage up front.MultiAgentSimulation.swift
– Simulates multiple agent roles.RetrievalAugmented.swift
– Uses retrieval before answering.
Foundation Models
@Generable & @Guide
Tool calling
Acceptable use requirements
Training details and evals
Apple Intelligence Foundation Language Models Tech Report 2025
Get started with Foundation Models adapter training
Meet the Foundation Models framework
Deep dive into the Foundation Models framework
Meet the Foundation Models framework
Deep dive into the Foundation Models framework