Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/apple-llm/ios/AppleLLM.mm
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ - (void)generateText:(nonnull NSArray *)messages
@"topP": options.topP().has_value() ? @(options.topP().value()) : [NSNull null],
@"topK": options.topK().has_value() ? @(options.topK().value()) : [NSNull null],
@"schema": options.schema() ?: [NSNull null],
@"tools": options.tools() ?: [NSNull null]
@"tools": options.tools() ?: [NSNull null],
@"guardrails": options.guardrails() ?: [NSNull null]
};

auto callToolBlock = ^(NSString *toolId, NSString *arguments, void (^completion)(id, NSError *)) {
Expand Down Expand Up @@ -144,6 +145,7 @@ - (void)generateStream:(nonnull NSString *)streamId messages:(nonnull NSArray *)
@"topK": options.topK().has_value() ? @(options.topK().value()) : [NSNull null],
@"schema": options.schema() ?: [NSNull null],
@"tools": options.tools() ?: [NSNull null],
@"guardrails": options.guardrails() ?: [NSNull null],
};

auto callToolBlock = ^(NSString *toolId, NSString *arguments, void (^completion)(id, NSError *)) {
Expand Down
11 changes: 9 additions & 2 deletions packages/apple-llm/ios/AppleLLMImpl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public class AppleLLMImpl: NSObject {
let (transcript, userPrompt) = try self.createTranscriptAndPrompt(from: messages, tools: tools)

let session = LanguageModelSession.init(
model: SystemLanguageModel.default,
model: self.createModel(from: options),
tools: tools,
transcript: transcript
)
Expand Down Expand Up @@ -155,7 +155,7 @@ public class AppleLLMImpl: NSObject {
let (transcript, userPrompt) = try self.createTranscriptAndPrompt(from: messages, tools: tools)

let session = LanguageModelSession.init(
model: SystemLanguageModel.default,
model: self.createModel(from: options),
tools: tools,
transcript: transcript
)
Expand Down Expand Up @@ -384,6 +384,13 @@ public class AppleLLMImpl: NSObject {
}

@available(iOS 26, *)
private func createModel(from options: [String: Any]) -> SystemLanguageModel {
if options["guardrails"] as? String == "permissiveContentTransformations" {
return SystemLanguageModel(guardrails: .permissiveContentTransformations)
}
return SystemLanguageModel.default
}

private func createGenerationOptions(from options: [String: Any]) throws -> GenerationOptions {
var temperature: Double?
var maximumResponseTokens: Int?
Expand Down
4 changes: 4 additions & 0 deletions packages/apple-llm/src/NativeAppleLLM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ export interface AppleMessage {
content: string
}

export type AppleGuardrails = 'default' | 'permissiveContentTransformations'

export interface AppleGenerationOptions {
/** Guardrails mode for the underlying SystemLanguageModel. */
guardrails?: AppleGuardrails
temperature?: number
maxTokens?: number
topP?: number
Expand Down
28 changes: 25 additions & 3 deletions packages/apple-llm/src/ai-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,35 @@ import {

import { createAppleLLMError, isAppleLLMErrorCode } from './errors'
import NativeAppleEmbeddings from './NativeAppleEmbeddings'
import NativeAppleLLM, { type AppleMessage } from './NativeAppleLLM'
import NativeAppleLLM, {
type AppleGuardrails,
type AppleMessage,
} from './NativeAppleLLM'
import NativeAppleSpeech from './NativeAppleSpeech'
import NativeAppleTranscription from './NativeAppleTranscription'
import NativeAppleUtils from './NativeAppleUtils'

type Tool = LanguageModelV3FunctionTool | LanguageModelV3ProviderTool
type ToolDefinitionSet = Record<string, FullToolDefinition>

export type { AppleGuardrails } from './NativeAppleLLM'

export function createAppleProvider({
availableTools,
guardrails,
}: {
availableTools?: ToolDefinitionSet
/**
* Guardrails mode for the on-device model. Use
* `'permissiveContentTransformations'` to lower guardrail sensitivity for
* apps that transform legitimate but sensitive content (for example health
* data). Defaults to the system default guardrails.
* @see https://developer.apple.com/documentation/foundationmodels/improving-the-safety-of-generative-model-output
*/
guardrails?: AppleGuardrails
} = {}) {
const createLanguageModel = () => {
return new AppleLLMChatLanguageModel(availableTools)
return new AppleLLMChatLanguageModel(availableTools, guardrails)
}
const provider = function () {
return createLanguageModel()
Expand Down Expand Up @@ -237,9 +251,14 @@ class AppleLLMChatLanguageModel implements LanguageModelV3 {
readonly modelId = 'system-default'

private tools: ToolDefinitionSet = {}
private guardrails?: AppleGuardrails

constructor(availableTools: ToolDefinitionSet = {}) {
constructor(
availableTools: ToolDefinitionSet = {},
guardrails?: AppleGuardrails
) {
this.updateTools(availableTools)
this.guardrails = guardrails
}

async prepare(): Promise<void> {}
Expand Down Expand Up @@ -305,6 +324,7 @@ class AppleLLMChatLanguageModel implements LanguageModelV3 {

try {
const response = await NativeAppleLLM.generateText(messages, {
guardrails: this.guardrails,
maxTokens: options.maxOutputTokens,
temperature: options.temperature,
topP: options.topP,
Expand Down Expand Up @@ -365,6 +385,7 @@ class AppleLLMChatLanguageModel implements LanguageModelV3 {
async doStream(options: LanguageModelV3CallOptions) {
const messages = this.prepareMessages(options.prompt)
const tools = this.prepareTools(options.tools)
const guardrails = this.guardrails

if (typeof ReadableStream === 'undefined') {
throw new Error(
Expand Down Expand Up @@ -472,6 +493,7 @@ class AppleLLMChatLanguageModel implements LanguageModelV3 {
listeners = [updateListener, completeListener, errorListener]

NativeAppleLLM.generateStream(streamId, messages, {
guardrails,
maxTokens: options.maxOutputTokens,
temperature: options.temperature,
topP: options.topP,
Expand Down
18 changes: 18 additions & 0 deletions website/src/docs/apple/generating.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ for await (const delta of textStream) {
> [!NOTE]
> Streaming objects is currently not supported.

## Guardrails

Apple Foundation Models apply content guardrails to prompts and responses. Apps
that transform legitimate but sensitive content (for example health or medical
data) can hit `guardrailViolation` errors with the default mode. For those
use-cases, Apple provides a permissive guardrails mode that you can opt into
when creating the provider:

```typescript
import { createAppleProvider } from '@react-native-ai/apple';

const apple = createAppleProvider({
guardrails: 'permissiveContentTransformations'
});
```

See [Improving the safety of generative model output](https://developer.apple.com/documentation/foundationmodels/improving-the-safety-of-generative-model-output#Use-permissive-guardrail-mode-for-sensitive-content) for when this mode is appropriate.

## Structured Output

Generate structured data that conforms to a specific schema:
Expand Down