langextract-rust 0.5.0

A Rust library for extracting structured and grounded information from text using LLMs
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Core data types for the annotation pipeline.
//!
//! This module defines the fundamental data structures used throughout the langextract
//! library, including documents, extractions, and configuration types.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Status indicating how well an extraction aligns with the source text
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AlignmentStatus {
    /// Extraction matches the source text exactly
    MatchExact,
    /// Extraction text is longer than the source span
    MatchGreater,
    /// Extraction text is shorter than the source span
    MatchLesser,
    /// Extraction text approximately matches but with differences
    MatchFuzzy,
}

/// Represents a character interval in text
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CharInterval {
    /// Starting position of the interval (inclusive)
    pub start_pos: Option<usize>,
    /// Ending position of the interval (exclusive)
    pub end_pos: Option<usize>,
}

impl CharInterval {
    /// Create a new character interval
    pub fn new(start_pos: Option<usize>, end_pos: Option<usize>) -> Self {
        Self { start_pos, end_pos }
    }

    /// Check if this interval overlaps with another
    pub fn overlaps_with(&self, other: &CharInterval) -> bool {
        match (self.start_pos, self.end_pos, other.start_pos, other.end_pos) {
            (Some(s1), Some(e1), Some(s2), Some(e2)) => {
                // Two intervals overlap if one starts before the other ends
                s1 < e2 && s2 < e1
            }
            _ => false, // If any position is None, consider no overlap
        }
    }

    /// Get the length of the interval
    pub fn length(&self) -> Option<usize> {
        match (self.start_pos, self.end_pos) {
            (Some(start), Some(end)) if end >= start => Some(end - start),
            _ => None,
        }
    }
}

/// Token interval information (placeholder for future tokenizer integration)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenInterval {
    /// Starting token index
    pub start_token: Option<usize>,
    /// Ending token index
    pub end_token: Option<usize>,
}

impl TokenInterval {
    /// Create a new token interval
    pub fn new(start_token: Option<usize>, end_token: Option<usize>) -> Self {
        Self {
            start_token,
            end_token,
        }
    }
}

/// Represents an extraction extracted from text
///
/// This struct encapsulates an extraction's characteristics and its position
/// within the source text. It can represent diverse information for NLP
/// information extraction tasks.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Extraction {
    /// The class or type of the extraction
    pub extraction_class: String,
    /// The extracted text content
    pub extraction_text: String,
    /// Character position in the original text
    pub char_interval: Option<CharInterval>,
    /// How well this extraction aligns with the source
    pub alignment_status: Option<AlignmentStatus>,
    /// Index of this extraction in the list
    pub extraction_index: Option<usize>,
    /// Group index for related extractions
    pub group_index: Option<usize>,
    /// Human-readable description
    pub description: Option<String>,
    /// Additional attributes as key-value pairs
    pub attributes: Option<HashMap<String, serde_json::Value>>,
    /// Token position information
    #[serde(skip)]
    pub token_interval: Option<TokenInterval>,
}

impl Extraction {
    /// Create a new extraction with just the class and text
    pub fn new(extraction_class: String, extraction_text: String) -> Self {
        Self {
            extraction_class,
            extraction_text,
            char_interval: None,
            alignment_status: None,
            extraction_index: None,
            group_index: None,
            description: None,
            attributes: None,
            token_interval: None,
        }
    }
}

impl Default for Extraction {
    fn default() -> Self {
        Self {
            extraction_class: String::new(),
            extraction_text: String::new(),
            char_interval: None,
            alignment_status: None,
            extraction_index: None,
            group_index: None,
            description: None,
            attributes: None,
            token_interval: None,
        }
    }
}

impl Extraction {
    /// Create a new extraction with character interval
    pub fn with_char_interval(
        extraction_class: String,
        extraction_text: String,
        char_interval: CharInterval,
    ) -> Self {
        Self {
            extraction_class,
            extraction_text,
            char_interval: Some(char_interval),
            alignment_status: None,
            extraction_index: None,
            group_index: None,
            description: None,
            attributes: None,
            token_interval: None,
        }
    }

    /// Set the character interval for this extraction
    pub fn set_char_interval(&mut self, interval: CharInterval) {
        self.char_interval = Some(interval);
    }

    /// Set an attribute value
    pub fn set_attribute(&mut self, key: String, value: serde_json::Value) {
        if self.attributes.is_none() {
            self.attributes = Some(HashMap::new());
        }
        if let Some(attrs) = &mut self.attributes {
            attrs.insert(key, value);
        }
    }

    /// Get an attribute value
    pub fn get_attribute(&self, key: &str) -> Option<&serde_json::Value> {
        self.attributes.as_ref()?.get(key)
    }

    /// Check if this extraction overlaps with another based on character intervals
    pub fn overlaps_with(&self, other: &Extraction) -> bool {
        match (&self.char_interval, &other.char_interval) {
            (Some(interval1), Some(interval2)) => interval1.overlaps_with(interval2),
            _ => false,
        }
    }
}

/// Document class for input text
///
/// Represents a single document to be processed by the annotation pipeline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Document {
    /// Raw text content of the document
    pub text: String,
    /// Optional additional context to supplement prompt instructions
    pub additional_context: Option<String>,
    /// Unique identifier for the document
    #[serde(skip_serializing_if = "Option::is_none")]
    pub document_id: Option<String>,
}

impl Document {
    /// Create a new document with the given text
    pub fn new(text: String) -> Self {
        Self {
            text,
            additional_context: None,
            document_id: None,
        }
    }

    /// Create a new document with text and additional context
    pub fn with_context(text: String, additional_context: String) -> Self {
        Self {
            text,
            additional_context: Some(additional_context),
            document_id: None,
        }
    }

    /// Get or generate a document ID
    pub fn get_document_id(&mut self) -> String {
        if let Some(id) = &self.document_id {
            id.clone()
        } else {
            let id = format!("doc_{}", Uuid::new_v4().simple().to_string()[..8].to_string());
            self.document_id = Some(id.clone());
            id
        }
    }

    /// Set a specific document ID
    pub fn set_document_id(&mut self, id: String) {
        self.document_id = Some(id);
    }
}

/// Annotated document with extractions
///
/// Represents the result of processing a document through the annotation pipeline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnnotatedDocument {
    /// Unique identifier for the document
    #[serde(skip_serializing_if = "Option::is_none")]
    pub document_id: Option<String>,
    /// List of extractions found in the document
    pub extractions: Option<Vec<Extraction>>,
    /// Original text content
    pub text: Option<String>,
}

impl AnnotatedDocument {
    /// Create a new annotated document
    pub fn new() -> Self {
        Self {
            document_id: None,
            extractions: None,
            text: None,
        }
    }

    /// Create an annotated document with extractions and text
    pub fn with_extractions(extractions: Vec<Extraction>, text: String) -> Self {
        Self {
            document_id: None,
            extractions: Some(extractions),
            text: Some(text),
        }
    }

    /// Get or generate a document ID
    pub fn get_document_id(&mut self) -> String {
        if let Some(id) = &self.document_id {
            id.clone()
        } else {
            let id = format!("doc_{}", Uuid::new_v4().simple().to_string()[..8].to_string());
            self.document_id = Some(id.clone());
            id
        }
    }

    /// Set the document ID
    pub fn set_document_id(&mut self, id: String) {
        self.document_id = Some(id);
    }

    /// Add an extraction to this document
    pub fn add_extraction(&mut self, extraction: Extraction) {
        if self.extractions.is_none() {
            self.extractions = Some(Vec::new());
        }
        if let Some(extractions) = &mut self.extractions {
            extractions.push(extraction);
        }
    }

    /// Get the number of extractions
    pub fn extraction_count(&self) -> usize {
        self.extractions.as_ref().map_or(0, |e| e.len())
    }

    /// Get extractions of a specific class
    pub fn extractions_by_class(&self, class_name: &str) -> Vec<&Extraction> {
        self.extractions
            .as_ref()
            .map_or(Vec::new(), |extractions| {
                extractions
                    .iter()
                    .filter(|e| e.extraction_class == class_name)
                    .collect()
            })
    }
}

impl Default for AnnotatedDocument {
    fn default() -> Self {
        Self::new()
    }
}

/// Enumeration of supported output formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FormatType {
    /// JSON output format
    Json,
    /// YAML output format
    Yaml,
}

impl std::fmt::Display for FormatType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FormatType::Json => write!(f, "json"),
            FormatType::Yaml => write!(f, "yaml"),
        }
    }
}

impl std::str::FromStr for FormatType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "json" => Ok(FormatType::Json),
            "yaml" => Ok(FormatType::Yaml),
            _ => Err(format!("Invalid format type: {}", s)),
        }
    }
}

/// Example data for training/prompting
///
/// Represents a single training example that shows the model how to extract
/// information from text.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExampleData {
    /// The raw input text (sentence, paragraph, etc.)
    pub text: String,
    /// List of extractions that should be found in this text
    pub extractions: Vec<Extraction>,
}

impl ExampleData {
    /// Create a new example with text and extractions
    pub fn new(text: String, extractions: Vec<Extraction>) -> Self {
        Self { text, extractions }
    }

    /// Create an example with just text (no extractions)
    pub fn with_text(text: String) -> Self {
        Self {
            text,
            extractions: Vec::new(),
        }
    }

    /// Add an extraction to this example
    pub fn add_extraction(&mut self, extraction: Extraction) {
        self.extractions.push(extraction);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_char_interval_overlap() {
        let interval1 = CharInterval::new(Some(0), Some(5));
        let interval2 = CharInterval::new(Some(3), Some(8));
        let interval3 = CharInterval::new(Some(10), Some(15));

        assert!(interval1.overlaps_with(&interval2));
        assert!(interval2.overlaps_with(&interval1));
        assert!(!interval1.overlaps_with(&interval3));
        assert!(!interval3.overlaps_with(&interval1));
    }

    #[test]
    fn test_char_interval_length() {
        let interval = CharInterval::new(Some(5), Some(10));
        assert_eq!(interval.length(), Some(5));

        let interval_none = CharInterval::new(None, Some(10));
        assert_eq!(interval_none.length(), None);
    }

    #[test]
    fn test_extraction_creation() {
        let extraction = Extraction::new("person".to_string(), "John Doe".to_string());
        assert_eq!(extraction.extraction_class, "person");
        assert_eq!(extraction.extraction_text, "John Doe");
        assert!(extraction.char_interval.is_none());
    }

    #[test]
    fn test_extraction_attributes() {
        let mut extraction = Extraction::new("person".to_string(), "John Doe".to_string());
        extraction.set_attribute("age".to_string(), json!(30));
        extraction.set_attribute("city".to_string(), json!("New York"));

        assert_eq!(extraction.get_attribute("age"), Some(&json!(30)));
        assert_eq!(extraction.get_attribute("city"), Some(&json!("New York")));
        assert_eq!(extraction.get_attribute("nonexistent"), None);
    }

    #[test]
    fn test_extraction_overlap() {
        let mut extraction1 = Extraction::new("person".to_string(), "John".to_string());
        extraction1.set_char_interval(CharInterval::new(Some(0), Some(4)));

        let mut extraction2 = Extraction::new("name".to_string(), "John Doe".to_string());
        extraction2.set_char_interval(CharInterval::new(Some(2), Some(8)));

        let mut extraction3 = Extraction::new("city".to_string(), "Boston".to_string());
        extraction3.set_char_interval(CharInterval::new(Some(10), Some(16)));

        assert!(extraction1.overlaps_with(&extraction2));
        assert!(!extraction1.overlaps_with(&extraction3));
    }

    #[test]
    fn test_document_id_generation() {
        let mut doc = Document::new("Test text".to_string());
        let id1 = doc.get_document_id();
        let id2 = doc.get_document_id();

        assert_eq!(id1, id2); // Should be same ID when called multiple times
        assert!(id1.starts_with("doc_"));
        assert_eq!(id1.len(), 12); // "doc_" + 8 hex chars
    }

    #[test]
    fn test_annotated_document_operations() {
        let mut doc = AnnotatedDocument::new();
        assert_eq!(doc.extraction_count(), 0);

        let extraction1 = Extraction::new("person".to_string(), "Alice".to_string());
        let extraction2 = Extraction::new("person".to_string(), "Bob".to_string());
        let extraction3 = Extraction::new("location".to_string(), "Paris".to_string());

        doc.add_extraction(extraction1);
        doc.add_extraction(extraction2);
        doc.add_extraction(extraction3);

        assert_eq!(doc.extraction_count(), 3);

        let person_extractions = doc.extractions_by_class("person");
        assert_eq!(person_extractions.len(), 2);

        let location_extractions = doc.extractions_by_class("location");
        assert_eq!(location_extractions.len(), 1);
    }

    #[test]
    fn test_format_type_conversion() {
        assert_eq!("json".parse::<FormatType>().unwrap(), FormatType::Json);
        assert_eq!("yaml".parse::<FormatType>().unwrap(), FormatType::Yaml);
        assert_eq!("JSON".parse::<FormatType>().unwrap(), FormatType::Json);

        assert!(matches!("xml".parse::<FormatType>(), Err(_)));

        assert_eq!(FormatType::Json.to_string(), "json");
        assert_eq!(FormatType::Yaml.to_string(), "yaml");
    }

    #[test]
    fn test_example_data() {
        let mut example = ExampleData::with_text("John is 30 years old".to_string());
        assert_eq!(example.extractions.len(), 0);

        example.add_extraction(Extraction::new("person".to_string(), "John".to_string()));
        example.add_extraction(Extraction::new("age".to_string(), "30".to_string()));

        assert_eq!(example.extractions.len(), 2);
    }

    #[test]
    fn test_serialization() {
        let extraction = Extraction::new("person".to_string(), "John Doe".to_string());
        let json_str = serde_json::to_string(&extraction).unwrap();
        let deserialized: Extraction = serde_json::from_str(&json_str).unwrap();
        assert_eq!(extraction, deserialized);

        let doc = Document::new("Test text".to_string());
        let json_str = serde_json::to_string(&doc).unwrap();
        let deserialized: Document = serde_json::from_str(&json_str).unwrap();
        assert_eq!(doc, deserialized);
    }
}