foundation-models 0.8.1

Safe Rust bindings for Apple's FoundationModels framework - on-device LLM on macOS 26+
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Prompt and instructions builders.

use serde_json::{json, Value};

use crate::content::GeneratedContent;
use crate::error::FMError;
use crate::schema::{Generable, GenerationSchema};

/// A FoundationModels prompt.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Prompt {
    segments: Vec<Segment>,
}

impl Prompt {
    /// Create an empty prompt.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    /// Create a prompt from a single text segment.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self::from(text.into())
    }

    /// Create a prompt from a structured content segment.
    #[must_use]
    pub fn structured(content: GeneratedContent) -> Self {
        Self::from(content)
    }

    /// Append a text segment.
    pub fn push_text(&mut self, text: impl Into<String>) {
        self.segments.push(Segment::text(text));
    }

    /// Append a structured content segment.
    pub fn push_structured(&mut self, source: impl Into<String>, content: GeneratedContent) {
        self.segments.push(Segment::structure(source, content));
    }

    /// Borrow the prompt segments.
    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// Consume the prompt and return its segments.
    #[must_use]
    pub fn into_segments(self) -> Vec<Segment> {
        self.segments
    }

    pub(crate) fn to_bridge_value(&self) -> Value {
        json!({
            "segments": self.segments.iter().map(Segment::to_bridge_value).collect::<Vec<_>>()
        })
    }

    pub(crate) fn to_bridge_json(&self) -> Result<String, FMError> {
        serde_json::to_string(&self.to_bridge_value()).map_err(|error| {
            FMError::InvalidArgument(format!("prompt is not JSON-serializable: {error}"))
        })
    }
}

impl From<String> for Prompt {
    fn from(text: String) -> Self {
        Self {
            segments: vec![Segment::text(text)],
        }
    }
}

impl From<&str> for Prompt {
    fn from(text: &str) -> Self {
        Self::from(text.to_owned())
    }
}

impl From<GeneratedContent> for Prompt {
    fn from(content: GeneratedContent) -> Self {
        Self {
            segments: vec![Segment::structure("GeneratedContent", content)],
        }
    }
}

impl From<Vec<Segment>> for Prompt {
    fn from(segments: Vec<Segment>) -> Self {
        Self { segments }
    }
}

/// A FoundationModels instructions value.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Instructions {
    segments: Vec<Segment>,
}

impl Instructions {
    /// Create empty instructions.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    /// Append a text segment.
    pub fn push_text(&mut self, text: impl Into<String>) {
        self.segments.push(Segment::text(text));
    }

    /// Append a structured content segment.
    pub fn push_structured(&mut self, source: impl Into<String>, content: GeneratedContent) {
        self.segments.push(Segment::structure(source, content));
    }

    /// Borrow the instruction segments.
    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// Consume the instructions and return their segments.
    #[must_use]
    pub fn into_segments(self) -> Vec<Segment> {
        self.segments
    }

    pub(crate) fn to_bridge_value(&self) -> Value {
        json!({
            "segments": self.segments.iter().map(Segment::to_bridge_value).collect::<Vec<_>>()
        })
    }

    pub(crate) fn to_bridge_json(&self) -> Result<String, FMError> {
        serde_json::to_string(&self.to_bridge_value()).map_err(|error| {
            FMError::InvalidArgument(format!("instructions are not JSON-serializable: {error}"))
        })
    }
}

impl From<String> for Instructions {
    fn from(text: String) -> Self {
        Self {
            segments: vec![Segment::text(text)],
        }
    }
}

impl From<&str> for Instructions {
    fn from(text: &str) -> Self {
        Self::from(text.to_owned())
    }
}

impl From<GeneratedContent> for Instructions {
    fn from(content: GeneratedContent) -> Self {
        Self {
            segments: vec![Segment::structure("GeneratedContent", content)],
        }
    }
}

impl From<Vec<Segment>> for Instructions {
    fn from(segments: Vec<Segment>) -> Self {
        Self { segments }
    }
}

/// A prompt or transcript segment.
#[derive(Debug, Clone, PartialEq)]
pub enum Segment {
    Text(TextSegment),
    Structure(StructuredSegment),
}

impl Segment {
    /// Create a text segment.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text(TextSegment::new(text))
    }

    /// Create a structured segment.
    #[must_use]
    pub fn structure(source: impl Into<String>, content: GeneratedContent) -> Self {
        Self::Structure(StructuredSegment::new(source, content))
    }

    pub(crate) fn to_bridge_value(&self) -> Value {
        match self {
            Self::Text(segment) => json!({
                "kind": "text",
                "text": segment.text,
            }),
            Self::Structure(segment) => json!({
                "kind": "structure",
                "source": segment.source,
                "content": segment
                    .content
                    .to_bridge_value()
                    .expect("generated content bridge payload must serialize")
            }),
        }
    }
}

/// A plain-text transcript segment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextSegment {
    pub id: Option<String>,
    pub text: String,
}

impl TextSegment {
    /// Create a text segment.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            id: None,
            text: text.into(),
        }
    }
}

/// A structured transcript segment.
#[derive(Debug, Clone, PartialEq)]
pub struct StructuredSegment {
    pub id: Option<String>,
    pub source: String,
    pub content: GeneratedContent,
}

impl StructuredSegment {
    /// Create a structured segment.
    #[must_use]
    pub fn new(source: impl Into<String>, content: GeneratedContent) -> Self {
        Self {
            id: None,
            source: source.into(),
            content,
        }
    }
}

/// A transcript response format.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResponseFormat {
    name: Option<String>,
    schema: GenerationSchema,
}

impl ResponseFormat {
    /// Create a response format from a generation schema.
    #[must_use]
    pub fn json_schema(schema: GenerationSchema) -> Self {
        Self { name: None, schema }
    }

    /// Create a response format from a [`Generable`] Rust type.
    ///
    /// # Errors
    ///
    /// Returns an [`FMError`] if the type cannot produce a generation schema.
    pub fn generating<T>() -> Result<Self, FMError>
    where
        T: Generable,
    {
        Ok(Self::json_schema(T::generation_schema()?))
    }

    pub(crate) fn from_transcript_json_value(value: &Value) -> Result<Self, FMError> {
        let schema = value
            .get("jsonSchema")
            .and_then(|json_schema| json_schema.get("schema"))
            .ok_or_else(|| {
                FMError::DecodingFailure("response format is missing jsonSchema.schema".into())
            })?;
        let name = value
            .get("jsonSchema")
            .and_then(|json_schema| json_schema.get("name"))
            .and_then(Value::as_str)
            .map(ToOwned::to_owned);
        Ok(Self {
            name,
            schema: GenerationSchema::from_json_schema_unchecked(
                serde_json::to_string(schema).map_err(|error| {
                    FMError::InvalidArgument(format!(
                        "response format schema is not valid JSON: {error}"
                    ))
                })?,
            ),
        })
    }

    /// Attach an explicit display name.
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Display name FoundationModels associates with this response format.
    #[must_use]
    pub fn name(&self) -> String {
        self.name
            .clone()
            .or_else(|| self.schema.name())
            .unwrap_or_else(|| "GeneratedContent".to_string())
    }

    /// The underlying schema.
    #[must_use]
    pub const fn schema(&self) -> &GenerationSchema {
        &self.schema
    }

    pub(crate) fn to_transcript_json_value(&self) -> Value {
        let schema_value: Value = serde_json::from_str(self.schema.json_schema())
            .expect("validated generation schema must always be valid JSON");
        json!({
            "type": "jsonSchema",
            "jsonSchema": {
                "name": self.name(),
                "schema": schema_value,
            }
        })
    }
}

/// A transcript tool definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolDefinition {
    pub name: String,
    pub description: String,
    pub parameters: GenerationSchema,
}

impl ToolDefinition {
    /// Create a tool definition.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        parameters: GenerationSchema,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            parameters,
        }
    }

    pub(crate) fn to_transcript_json_value(&self) -> Value {
        let parameters: Value = serde_json::from_str(self.parameters.json_schema())
            .expect("validated generation schema must always be valid JSON");
        json!({
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": parameters,
            }
        })
    }
}

/// Convert a Rust value into a FoundationModels prompt.
pub trait ToPrompt {
    /// Convert the value into a prompt.
    fn to_prompt(self) -> Result<Prompt, FMError>;
}

impl ToPrompt for Prompt {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(self)
    }
}

impl ToPrompt for &Prompt {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(self.clone())
    }
}

impl ToPrompt for String {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(Prompt::from(self))
    }
}

impl ToPrompt for &str {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(Prompt::from(self))
    }
}

impl ToPrompt for GeneratedContent {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(Prompt::from(self))
    }
}

impl ToPrompt for &GeneratedContent {
    fn to_prompt(self) -> Result<Prompt, FMError> {
        Ok(Prompt::from(self.clone()))
    }
}

/// Convert a Rust value into FoundationModels instructions.
pub trait ToInstructions {
    /// Convert the value into instructions.
    fn to_instructions(self) -> Result<Instructions, FMError>;
}

impl ToInstructions for Instructions {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(self)
    }
}

impl ToInstructions for &Instructions {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(self.clone())
    }
}

impl ToInstructions for String {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(Instructions::from(self))
    }
}

impl ToInstructions for &str {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(Instructions::from(self))
    }
}

impl ToInstructions for GeneratedContent {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(Instructions::from(self))
    }
}

impl ToInstructions for &GeneratedContent {
    fn to_instructions(self) -> Result<Instructions, FMError> {
        Ok(Instructions::from(self.clone()))
    }
}