oxi-ai 0.4.2

Unified LLM API — multi-provider streaming interface for AI coding assistants
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
//! Message types for oxi-ai

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

/// Text content block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextContent {
    #[serde(rename = "type")]
    pub content_type: TextContentType,
    pub text: String,
    /// Optional signature carrying provider-specific metadata (e.g. OpenAI message ID, phase).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_signature: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "text")]
pub enum TextContentType {
    Text,
}

impl TextContent {
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            content_type: TextContentType::Text,
            text: text.into(),
            text_signature: None,
        }
    }

    /// Create a text content block with a signature.
    #[allow(dead_code)]
    pub fn with_signature(text: impl Into<String>, signature: impl Into<String>) -> Self {
        Self {
            content_type: TextContentType::Text,
            text: text.into(),
            text_signature: Some(signature.into()),
        }
    }
}

/// Thinking content block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThinkingContent {
    #[serde(rename = "type")]
    pub content_type: ThinkingContentType,
    pub thinking: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redacted: Option<bool>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "thinking")]
pub enum ThinkingContentType {
    Thinking,
}

impl ThinkingContent {
    pub fn new(thinking: impl Into<String>) -> Self {
        Self {
            content_type: ThinkingContentType::Thinking,
            thinking: thinking.into(),
            thinking_signature: None,
            redacted: None,
        }
    }
}

/// Image content block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageContent {
    #[serde(rename = "type")]
    pub content_type: ImageContentType,
    pub data: String, // base64 encoded
    pub mime_type: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "image")]
pub enum ImageContentType {
    Image,
}

impl ImageContent {
    pub fn new(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self {
            content_type: ImageContentType::Image,
            data: data.into(),
            mime_type: mime_type.into(),
        }
    }
}

/// Tool call content block
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    #[serde(rename = "type")]
    pub content_type: ToolCallType,
    pub id: String,
    pub name: String,
    pub arguments: JsonValue,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thought_signature: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "toolCall")]
pub enum ToolCallType {
    ToolCall,
}

impl ToolCall {
    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: JsonValue) -> Self {
        Self {
            content_type: ToolCallType::ToolCall,
            id: id.into(),
            name: name.into(),
            arguments,
            thought_signature: None,
        }
    }
}

/// Content block union (untagged for flexibility)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContentBlock {
    Text(TextContent),
    Thinking(ThinkingContent),
    Image(ImageContent),
    ToolCall(ToolCall),
    Unknown(JsonValue),
}

impl ContentBlock {
    pub fn as_text(&self) -> Option<&str> {
        match self {
            ContentBlock::Text(t) => Some(&t.text),
            _ => None,
        }
    }

    pub fn as_tool_call(&self) -> Option<&ToolCall> {
        match self {
            ContentBlock::ToolCall(t) => Some(t),
            _ => None,
        }
    }

    pub fn as_thinking(&self) -> Option<&ThinkingContent> {
        match self {
            ContentBlock::Thinking(t) => Some(t),
            _ => None,
        }
    }
}

/// User message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMessage {
    pub role: UserRole,
    pub content: MessageContent,
    pub timestamp: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "user")]
pub enum UserRole {
    #[serde(rename = "user")]
    User,
}

impl UserMessage {
    pub fn new(content: impl Into<MessageContent>) -> Self {
        Self {
            role: UserRole::User,
            content: content.into(),
            timestamp: chrono::Utc::now().timestamp_millis(),
        }
    }
}

/// Assistant message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantMessage {
    pub role: AssistantRole,
    pub content: Vec<ContentBlock>,
    pub api: super::Api,
    pub provider: String,
    pub model: String,
    pub usage: super::Usage,
    pub stop_reason: super::StopReason,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_id: Option<String>,
    pub timestamp: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "assistant")]
pub enum AssistantRole {
    #[serde(rename = "assistant")]
    Assistant,
}

impl AssistantMessage {
    pub fn new(api: super::Api, provider: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            role: AssistantRole::Assistant,
            content: Vec::new(),
            api,
            provider: provider.into(),
            model: model.into(),
            usage: super::Usage::default(),
            stop_reason: super::StopReason::Stop,
            error_message: None,
            response_id: None,
            timestamp: chrono::Utc::now().timestamp_millis(),
        }
    }

    pub fn text_content(&self) -> String {
        // Pre-compute capacity to avoid reallocations.
        let estimated_len: usize = self
            .content
            .iter()
            .map(|b| b.as_text().map(|t| t.len()).unwrap_or(0))
            .sum();
        let mut result = String::with_capacity(estimated_len);
        for block in &self.content {
            if let Some(text) = block.as_text() {
                result.push_str(text);
            }
        }
        result
    }
}

/// Tool result message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResultMessage {
    pub role: ToolResultRole,
    pub tool_call_id: String,
    pub tool_name: String,
    pub content: Vec<ContentBlock>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<JsonValue>,
    #[serde(default)]
    pub is_error: bool,
    pub timestamp: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "toolResult")]
pub enum ToolResultRole {
    #[serde(rename = "toolResult")]
    ToolResult,
}

impl ToolResultMessage {
    pub fn new(
        tool_call_id: impl Into<String>,
        tool_name: impl Into<String>,
        content: Vec<ContentBlock>,
    ) -> Self {
        Self {
            role: ToolResultRole::ToolResult,
            tool_call_id: tool_call_id.into(),
            tool_name: tool_name.into(),
            content,
            details: None,
            is_error: false,
            timestamp: chrono::Utc::now().timestamp_millis(),
        }
    }

    pub fn error(
        tool_call_id: impl Into<String>,
        tool_name: impl Into<String>,
        error: impl Into<String>,
    ) -> Self {
        Self {
            role: ToolResultRole::ToolResult,
            tool_call_id: tool_call_id.into(),
            tool_name: tool_name.into(),
            content: vec![ContentBlock::Text(TextContent::new(error))],
            details: None,
            is_error: true,
            timestamp: chrono::Utc::now().timestamp_millis(),
        }
    }

    pub fn text_content(&self) -> Result<String, crate::error::ProviderError> {
        // Pre-compute capacity estimate.
        let estimated_len: usize = self
            .content
            .iter()
            .map(|b| match b {
                ContentBlock::Text(t) => t.text.len() + 1,
                ContentBlock::Image(_) => 7,
                ContentBlock::Thinking(t) => t.thinking.len() + 12,
                ContentBlock::ToolCall(tc) => tc.name.len() + 8,
                ContentBlock::Unknown(_) => 0,
            })
            .sum();
        let mut result = String::with_capacity(estimated_len);
        for block in &self.content {
            match block {
                ContentBlock::Text(t) => {
                    result.push_str(&t.text);
                    result.push('\n');
                }
                ContentBlock::Image(_) => {
                    result.push_str("[Image]\n");
                }
                ContentBlock::Thinking(t) => {
                    result.push_str(&format!("[Thinking: {}]\n", t.thinking));
                }
                ContentBlock::ToolCall(tc) => {
                    result.push_str(&format!("[Tool: {}]\n", tc.name));
                }
                ContentBlock::Unknown(_) => {
                    // Skip unknown blocks
                }
            }
        }
        Ok(result.trim().to_string())
    }
}

/// Message union
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "camelCase")]
pub enum Message {
    User(UserMessage),
    Assistant(AssistantMessage),
    ToolResult(ToolResultMessage),
}

impl Message {
    pub fn user(content: impl Into<MessageContent>) -> Self {
        Message::User(UserMessage::new(content))
    }

    pub fn timestamp(&self) -> i64 {
        match self {
            Message::User(m) => m.timestamp,
            Message::Assistant(m) => m.timestamp,
            Message::ToolResult(m) => m.timestamp,
        }
    }

    /// Get the text content of this message
    pub fn text_content(&self) -> Result<String, crate::error::ProviderError> {
        match self {
            Message::User(m) => match &m.content {
                MessageContent::Text(s) => Ok(s.clone()),
                MessageContent::Blocks(blocks) => {
                    let estimated_len: usize = blocks
                        .iter()
                        .map(|b| match b {
                            ContentBlock::Text(t) => t.text.len() + 1,
                            ContentBlock::Image(_) => 8,
                            ContentBlock::Thinking(t) => t.thinking.len() + 1,
                            ContentBlock::ToolCall(_) => 12,
                            ContentBlock::Unknown(_) => 10,
                        })
                        .sum();
                    let mut result = String::with_capacity(estimated_len);
                    for block in blocks {
                        match block {
                            ContentBlock::Text(t) => {
                                result.push_str(&t.text);
                                result.push('\n');
                            }
                            ContentBlock::Image(_) => {
                                result.push_str("[Image]\n");
                            }
                            ContentBlock::Thinking(t) => {
                                result.push_str(&t.thinking);
                                result.push('\n');
                            }
                            ContentBlock::ToolCall(_) => {
                                result.push_str("[Tool Call]\n");
                            }
                            ContentBlock::Unknown(_) => {
                                result.push_str("[Unknown]\n");
                            }
                        }
                    }
                    Ok(result.trim().to_string())
                }
            },
            Message::Assistant(m) => Ok(m.text_content()),
            Message::ToolResult(m) => m.text_content(),
        }
    }
}

/// Message content (string or content blocks)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
    Text(String),
    Blocks(Vec<ContentBlock>),
}

impl MessageContent {
    pub fn is_text(&self) -> bool {
        matches!(self, MessageContent::Text(_))
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            MessageContent::Text(s) => Some(s),
            MessageContent::Blocks(_) => None,
        }
    }
}

// String conversion for MessageContent
impl From<String> for MessageContent {
    fn from(text: String) -> Self {
        MessageContent::Text(text)
    }
}

impl From<&str> for MessageContent {
    fn from(text: &str) -> Self {
        MessageContent::Text(text.to_string())
    }
}

impl From<Vec<ContentBlock>> for MessageContent {
    fn from(blocks: Vec<ContentBlock>) -> Self {
        MessageContent::Blocks(blocks)
    }
}

impl From<TextContent> for MessageContent {
    fn from(block: TextContent) -> Self {
        MessageContent::Blocks(vec![ContentBlock::Text(block)])
    }
}

impl From<ContentBlock> for MessageContent {
    fn from(block: ContentBlock) -> Self {
        MessageContent::Blocks(vec![block])
    }
}

/// Transform messages for cross-provider compatibility.
///
/// When switching models mid-conversation, message history may contain
/// provider-specific content (e.g. thinking blocks from Anthropic) that
/// the new provider cannot handle. This function converts messages so
/// they are compatible with the target provider's API.
///
/// Key transformations:
/// - Thinking blocks → wrapped in `<thinking>` tags as plain text
/// - Tool calls and tool results are preserved unchanged
/// - User/assistant message structure is preserved
pub fn transform_for_provider(
    messages: &[Message],
    _from_api: &super::Api,
    to_api: &super::Api,
) -> Vec<Message> {
    messages
        .iter()
        .map(|msg| match msg {
            Message::Assistant(a) => {
                let mut new_msg = AssistantMessage::new(*to_api, &a.provider, &a.model);
                new_msg.content = transform_content_blocks(&a.content, to_api);
                new_msg.usage = a.usage.clone();
                new_msg.stop_reason = a.stop_reason;
                new_msg.error_message = a.error_message.clone();
                new_msg.response_id = a.response_id.clone();
                new_msg.timestamp = a.timestamp;
                Message::Assistant(new_msg)
            }
            Message::User(u) => Message::User(u.clone()),
            Message::ToolResult(t) => Message::ToolResult(t.clone()),
        })
        .collect()
}

/// Transform content blocks for a target provider.
///
/// Converts provider-specific blocks (like thinking) into formats
/// the target provider can understand.
fn transform_content_blocks(blocks: &[ContentBlock], to_api: &super::Api) -> Vec<ContentBlock> {
    match to_api {
        // Anthropic natively supports thinking blocks — keep as-is
        super::Api::AnthropicMessages => blocks.to_vec(),

        // OpenAI-compatible and other providers: convert thinking to text
        _ => {
            let mut transformed = Vec::with_capacity(blocks.len());
            for block in blocks {
                match block {
                    ContentBlock::Thinking(t) => {
                        // Convert thinking block to text wrapped in tags
                        let text = format!("<thinking>\n{}\n</thinking>", t.thinking);
                        transformed.push(ContentBlock::Text(TextContent::new(text)));
                    }
                    ContentBlock::Text(t) => {
                        transformed.push(ContentBlock::Text(t.clone()));
                    }
                    ContentBlock::ToolCall(tc) => {
                        transformed.push(ContentBlock::ToolCall(tc.clone()));
                    }
                    ContentBlock::Image(img) => {
                        transformed.push(ContentBlock::Image(img.clone()));
                    }
                    ContentBlock::Unknown(v) => {
                        // Try to extract text from unknown blocks
                        if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
                            transformed.push(ContentBlock::Text(TextContent::new(text)));
                        }
                        // Otherwise silently drop unknown blocks
                    }
                }
            }
            // Merge adjacent text blocks
            merge_adjacent_text_blocks(transformed)
        }
    }
}

/// Merge adjacent `ContentBlock::Text` blocks into a single block.
fn merge_adjacent_text_blocks(blocks: Vec<ContentBlock>) -> Vec<ContentBlock> {
    let mut result = Vec::with_capacity(blocks.len());
    let mut pending_text = String::new();

    for block in blocks {
        match block {
            ContentBlock::Text(t) => {
                if !pending_text.is_empty() {
                    pending_text.push('\n');
                }
                pending_text.push_str(&t.text);
            }
            other => {
                if !pending_text.is_empty() {
                    result.push(ContentBlock::Text(TextContent::new(std::mem::take(
                        &mut pending_text,
                    ))));
                }
                result.push(other);
            }
        }
    }

    if !pending_text.is_empty() {
        result.push(ContentBlock::Text(TextContent::new(pending_text)));
    }

    result
}