with the new on device llm how can i write a few lines of code for text generation

Asked on 06/11/2025

1 search

To write a few lines of code for text generation using the new on-device large language model (LLM) from Apple, you can use the Foundation Models framework. Here's a simple example of how you can get started:

  1. Import the Framework: First, you need to import the Foundation Models framework into your project.

  2. Create a Session: Set up a session with the language model. This session will handle the interaction with the model.

  3. Send a Prompt: Use the session to send a text prompt to the model and receive a generated response.

Here's a basic example in Swift:

import FoundationModels

// Create a session with the language model
let session = LanguageModelSession()

// Define your prompt
let prompt = "Generate a title for a trip to Japan"

// Send the prompt to the model and get the response
session.respond(to: prompt) { response in
    print("Generated text: \(response)")
}

This code snippet demonstrates how to set up a session and send a prompt to the on-device LLM to generate text. The model's response will be printed to the console.

For more detailed guidance, you can refer to the session Meet the Foundation Models framework (02:04) from WWDC 2025, which provides an introduction to using the Foundation Models framework for text generation.

with the new on device llm how can i write a few lines of code for text generation | Ask WWDC