simple-agent-type 0.3.11

Core types and traits for SimpleAgents
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Response types for LLM completions.
//!
//! Provides OpenAI-compatible response structures.

use crate::coercion::CoercionFlag;
use crate::message::Message;
use serde::{Deserialize, Serialize};

/// Metadata about healing/coercion applied to a response.
///
/// When native structured output parsing fails and healing is enabled,
/// this metadata tracks all transformations applied to recover the response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HealingMetadata {
    /// All coercion flags applied during healing
    pub flags: Vec<CoercionFlag>,
    /// Confidence score (0.0-1.0) of the healed response
    pub confidence: f32,
    /// The original parsing error that triggered healing
    pub original_error: String,
}

impl HealingMetadata {
    /// Create new healing metadata.
    pub fn new(flags: Vec<CoercionFlag>, confidence: f32, original_error: String) -> Self {
        Self {
            flags,
            confidence: confidence.clamp(0.0, 1.0),
            original_error,
        }
    }

    /// Check if any major coercions were applied.
    pub fn has_major_coercions(&self) -> bool {
        self.flags.iter().any(|f| f.is_major())
    }

    /// Check if confidence meets a threshold.
    pub fn is_confident(&self, threshold: f32) -> bool {
        self.confidence >= threshold
    }
}

/// A completion response from an LLM provider.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompletionResponse {
    /// Unique response identifier
    pub id: String,
    /// Model used for completion
    pub model: String,
    /// List of completion choices
    pub choices: Vec<CompletionChoice>,
    /// Token usage statistics
    pub usage: Usage,
    /// Unix timestamp of creation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<i64>,
    /// Provider that generated this response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Healing metadata (present if response was healed after parse failure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub healing_metadata: Option<HealingMetadata>,
}

impl CompletionResponse {
    /// Get the content of the first choice (convenience method).
    ///
    /// # Example
    /// ```
    /// use simple_agent_type::response::{CompletionResponse, CompletionChoice, Usage, FinishReason};
    /// use simple_agent_type::message::Message;
    ///
    /// let response = CompletionResponse {
    ///     id: "resp_123".to_string(),
    ///     model: "gpt-4".to_string(),
    ///     choices: vec![CompletionChoice {
    ///         index: 0,
    ///         message: Message::assistant("Hello!"),
    ///         finish_reason: FinishReason::Stop,
    ///         logprobs: None,
    ///     }],
    ///     usage: Usage {
    ///         prompt_tokens: 10,
    ///         completion_tokens: 5,
    ///         total_tokens: 15,
    ///         reasoning_tokens: None,
    ///     },
    ///     created: None,
    ///     provider: None,
    ///     healing_metadata: None,
    /// };
    ///
    /// assert_eq!(response.content(), Some("Hello!"));
    /// ```
    pub fn content(&self) -> Option<&str> {
        self.choices
            .first()
            .map(|choice| choice.message.content_text())
    }

    /// Get the first choice.
    pub fn first_choice(&self) -> Option<&CompletionChoice> {
        self.choices.first()
    }

    /// Check if this response was healed after a parsing failure.
    ///
    /// Returns `true` if healing metadata is present, indicating the response
    /// required transformation to be parseable.
    ///
    /// # Example
    /// ```
    /// use simple_agent_type::response::{CompletionResponse, CompletionChoice, Usage, FinishReason, HealingMetadata};
    /// use simple_agent_type::message::Message;
    /// use simple_agent_type::coercion::CoercionFlag;
    ///
    /// let mut response = CompletionResponse {
    ///     id: "resp_123".to_string(),
    ///     model: "gpt-4".to_string(),
    ///     choices: vec![],
    ///     usage: Usage::new(10, 5),
    ///     created: None,
    ///     provider: None,
    ///     healing_metadata: None,
    /// };
    ///
    /// assert!(!response.was_healed());
    ///
    /// response.healing_metadata = Some(HealingMetadata::new(
    ///     vec![CoercionFlag::StrippedMarkdown],
    ///     0.9,
    ///     "Parse error".to_string(),
    /// ));
    ///
    /// assert!(response.was_healed());
    /// ```
    pub fn was_healed(&self) -> bool {
        self.healing_metadata.is_some()
    }

    /// Get the confidence score of the response.
    ///
    /// Returns 1.0 if the response was not healed (perfect confidence),
    /// otherwise returns the confidence score from healing metadata.
    ///
    /// # Example
    /// ```
    /// use simple_agent_type::response::{CompletionResponse, CompletionChoice, Usage, FinishReason, HealingMetadata};
    /// use simple_agent_type::message::Message;
    /// use simple_agent_type::coercion::CoercionFlag;
    ///
    /// let mut response = CompletionResponse {
    ///     id: "resp_123".to_string(),
    ///     model: "gpt-4".to_string(),
    ///     choices: vec![],
    ///     usage: Usage::new(10, 5),
    ///     created: None,
    ///     provider: None,
    ///     healing_metadata: None,
    /// };
    ///
    /// assert_eq!(response.confidence(), 1.0);
    ///
    /// response.healing_metadata = Some(HealingMetadata::new(
    ///     vec![CoercionFlag::StrippedMarkdown],
    ///     0.8,
    ///     "Parse error".to_string(),
    /// ));
    ///
    /// assert_eq!(response.confidence(), 0.8);
    /// ```
    pub fn confidence(&self) -> f32 {
        self.healing_metadata
            .as_ref()
            .map(|m| m.confidence)
            .unwrap_or(1.0)
    }
}

/// A single completion choice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompletionChoice {
    /// Index of this choice
    pub index: u32,
    /// The message content
    pub message: Message,
    /// Why the completion finished
    pub finish_reason: FinishReason,
    /// Log probabilities (if requested)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<serde_json::Value>,
}

/// Reason why a completion finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FinishReason {
    /// Natural stop point reached
    Stop,
    /// Maximum token length reached
    Length,
    /// Content filtered by provider
    ContentFilter,
    /// Tool/function calls generated
    ToolCalls,
}

impl FinishReason {
    /// Returns this finish reason as its canonical snake_case string value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Stop => "stop",
            Self::Length => "length",
            Self::ContentFilter => "content_filter",
            Self::ToolCalls => "tool_calls",
        }
    }
}

/// Token usage statistics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Usage {
    /// Tokens in the prompt
    pub prompt_tokens: u32,
    /// Tokens in the completion
    pub completion_tokens: u32,
    /// Total tokens used
    pub total_tokens: u32,
    /// Optional reasoning token usage (provider-dependent).
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        alias = "thinking_tokens"
    )]
    pub reasoning_tokens: Option<u32>,
}

impl Usage {
    /// Create a new Usage with calculated total.
    pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self {
        Self {
            prompt_tokens,
            completion_tokens,
            total_tokens: prompt_tokens + completion_tokens,
            reasoning_tokens: None,
        }
    }
}

/// A chunk of a streaming completion response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompletionChunk {
    /// Unique response identifier
    pub id: String,
    /// Model used for completion
    pub model: String,
    /// List of choice deltas
    pub choices: Vec<ChoiceDelta>,
    /// Unix timestamp of creation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<i64>,
    /// Optional token usage for this chunk (typically on final chunk)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
}

/// A delta in a streaming choice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChoiceDelta {
    /// Index of this choice
    pub index: u32,
    /// The message delta
    pub delta: MessageDelta,
    /// Why the completion finished (only in final chunk)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<FinishReason>,
}

/// Incremental message content in a stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MessageDelta {
    /// Role (only in first chunk)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<crate::message::Role>,
    /// Incremental content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Optional incremental reasoning/thinking content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    /// Optional incremental tool call deltas.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCallDelta>>,
}

/// Incremental tool call payload emitted in streaming responses.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCallDelta {
    /// Tool call position in the choice stream.
    pub index: u32,
    /// Tool call identifier (may arrive incrementally).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Tool type.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub tool_type: Option<crate::tool::ToolType>,
    /// Function name/arguments payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function: Option<ToolCallFunctionDelta>,
}

/// Incremental function payload for a streamed tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCallFunctionDelta {
    /// Function name (may arrive once).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// JSON arguments text (may arrive in chunks).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

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

    #[test]
    fn test_completion_response_content() {
        let response = CompletionResponse {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![CompletionChoice {
                index: 0,
                message: Message::assistant("Hello!"),
                finish_reason: FinishReason::Stop,
                logprobs: None,
            }],
            usage: Usage::new(10, 5),
            created: Some(1234567890),
            provider: Some("openai".to_string()),
            healing_metadata: None,
        };

        assert_eq!(response.content(), Some("Hello!"));
        assert_eq!(response.first_choice().unwrap().index, 0);
        assert!(!response.was_healed());
        assert_eq!(response.confidence(), 1.0);
    }

    #[test]
    fn test_completion_response_empty_choices() {
        let response = CompletionResponse {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![],
            usage: Usage::new(10, 0),
            created: None,
            provider: None,
            healing_metadata: None,
        };

        assert_eq!(response.content(), None);
        assert_eq!(response.first_choice(), None);
    }

    #[test]
    fn test_usage_calculation() {
        let usage = Usage::new(100, 50);
        assert_eq!(usage.prompt_tokens, 100);
        assert_eq!(usage.completion_tokens, 50);
        assert_eq!(usage.total_tokens, 150);
        assert_eq!(usage.reasoning_tokens, None);
    }

    #[test]
    fn test_usage_deserializes_thinking_tokens_alias() {
        let json = serde_json::json!({
            "prompt_tokens": 10,
            "completion_tokens": 5,
            "total_tokens": 15,
            "thinking_tokens": 3
        });

        let usage: Usage = serde_json::from_value(json).unwrap();
        assert_eq!(usage.reasoning_tokens, Some(3));
    }

    #[test]
    fn test_usage_serializes_reasoning_tokens_name() {
        let usage = Usage {
            prompt_tokens: 10,
            completion_tokens: 5,
            total_tokens: 15,
            reasoning_tokens: Some(3),
        };

        let json = serde_json::to_value(usage).unwrap();
        assert_eq!(
            json.get("reasoning_tokens").and_then(|v| v.as_u64()),
            Some(3)
        );
        assert!(json.get("thinking_tokens").is_none());
    }

    #[test]
    fn test_finish_reason_serialization() {
        let json = serde_json::to_string(&FinishReason::Stop).unwrap();
        assert_eq!(json, "\"stop\"");

        let json = serde_json::to_string(&FinishReason::Length).unwrap();
        assert_eq!(json, "\"length\"");

        let json = serde_json::to_string(&FinishReason::ContentFilter).unwrap();
        assert_eq!(json, "\"content_filter\"");

        let json = serde_json::to_string(&FinishReason::ToolCalls).unwrap();
        assert_eq!(json, "\"tool_calls\"");
    }

    #[test]
    fn test_response_serialization() {
        let response = CompletionResponse {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![CompletionChoice {
                index: 0,
                message: Message::assistant("Hello!"),
                finish_reason: FinishReason::Stop,
                logprobs: None,
            }],
            usage: Usage::new(10, 5),
            created: None,
            provider: None,
            healing_metadata: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: CompletionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(response, parsed);
    }

    #[test]
    fn test_streaming_chunk() {
        let chunk = CompletionChunk {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![ChoiceDelta {
                index: 0,
                delta: MessageDelta {
                    role: Some(crate::message::Role::Assistant),
                    content: Some("Hello".to_string()),
                    reasoning_content: None,
                    tool_calls: None,
                },
                finish_reason: None,
            }],
            created: Some(1234567890),
            usage: None,
        };

        let json = serde_json::to_string(&chunk).unwrap();
        let parsed: CompletionChunk = serde_json::from_str(&json).unwrap();
        assert_eq!(chunk, parsed);
    }

    #[test]
    fn test_message_delta() {
        let delta = MessageDelta {
            role: Some(crate::message::Role::Assistant),
            content: Some("Hi".to_string()),
            reasoning_content: None,
            tool_calls: None,
        };

        let json = serde_json::to_value(&delta).unwrap();
        assert_eq!(json.get("role").and_then(|v| v.as_str()), Some("assistant"));
        assert_eq!(json.get("content").and_then(|v| v.as_str()), Some("Hi"));
    }

    #[test]
    fn test_optional_fields_not_serialized() {
        let response = CompletionResponse {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![],
            usage: Usage::new(10, 5),
            created: None,
            provider: None,
            healing_metadata: None,
        };

        let json = serde_json::to_value(&response).unwrap();
        assert!(json.get("created").is_none());
        assert!(json.get("provider").is_none());
        assert!(json.get("healing_metadata").is_none());
    }

    #[test]
    fn test_healing_metadata() {
        use crate::coercion::CoercionFlag;

        let metadata = HealingMetadata::new(
            vec![CoercionFlag::StrippedMarkdown],
            0.9,
            "Parse error".to_string(),
        );

        assert_eq!(metadata.confidence, 0.9);
        assert!(!metadata.has_major_coercions());
        assert!(metadata.is_confident(0.8));
        assert!(!metadata.is_confident(0.95));

        let major_metadata = HealingMetadata::new(
            vec![CoercionFlag::TruncatedJson],
            0.7,
            "Parse error".to_string(),
        );

        assert!(major_metadata.has_major_coercions());
    }

    #[test]
    fn test_healing_metadata_confidence_clamped() {
        let metadata = HealingMetadata::new(vec![], 1.5, "error".to_string());
        assert_eq!(metadata.confidence, 1.0);

        let metadata = HealingMetadata::new(vec![], -0.5, "error".to_string());
        assert_eq!(metadata.confidence, 0.0);
    }

    #[test]
    fn test_response_with_healing_metadata() {
        use crate::coercion::CoercionFlag;

        let metadata = HealingMetadata::new(
            vec![
                CoercionFlag::StrippedMarkdown,
                CoercionFlag::FixedTrailingComma,
            ],
            0.85,
            "JSON parse error".to_string(),
        );

        let response = CompletionResponse {
            id: "resp_123".to_string(),
            model: "gpt-4".to_string(),
            choices: vec![],
            usage: Usage::new(10, 5),
            created: None,
            provider: None,
            healing_metadata: Some(metadata),
        };

        assert!(response.was_healed());
        assert_eq!(response.confidence(), 0.85);

        let json = serde_json::to_string(&response).unwrap();
        let parsed: CompletionResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(response, parsed);
        assert!(parsed.was_healed());
        assert_eq!(parsed.confidence(), 0.85);
    }
}