Skip to main content

stakpak_shared/models/integrations/
openai.rs

1//! OpenAI provider configuration and chat message types
2//!
3//! This module contains:
4//! - Configuration types for OpenAI provider
5//! - OpenAI model enums with pricing info
6//! - Chat message types used throughout the TUI
7//! - Tool call types for agent interactions
8//!
9//! Note: Low-level API request/response types are in `libs/ai/src/providers/openai/`.
10
11use crate::models::llm::{
12    GenerationDelta, LLMMessage, LLMMessageContent, LLMMessageImageSource, LLMMessageTypedContent,
13    LLMTokenUsage, LLMTool,
14};
15use crate::models::model_pricing::{ContextAware, ContextPricingTier, ModelContextInfo};
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18use uuid::Uuid;
19
20// =============================================================================
21// Provider Configuration
22// =============================================================================
23
24/// Configuration for OpenAI provider
25#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
26pub struct OpenAIConfig {
27    pub api_endpoint: Option<String>,
28    pub api_key: Option<String>,
29}
30
31impl OpenAIConfig {
32    /// Create config with API key
33    pub fn with_api_key(api_key: impl Into<String>) -> Self {
34        Self {
35            api_key: Some(api_key.into()),
36            api_endpoint: None,
37        }
38    }
39
40    /// Create config from ProviderAuth (only supports API key for OpenAI)
41    pub fn from_provider_auth(auth: &crate::models::auth::ProviderAuth) -> Option<Self> {
42        match auth {
43            crate::models::auth::ProviderAuth::Api { key } => Some(Self::with_api_key(key)),
44            crate::models::auth::ProviderAuth::OAuth { .. } => None, // OpenAI doesn't support OAuth
45        }
46    }
47
48    /// Merge with credentials from ProviderAuth, preserving existing endpoint
49    pub fn with_provider_auth(mut self, auth: &crate::models::auth::ProviderAuth) -> Option<Self> {
50        match auth {
51            crate::models::auth::ProviderAuth::Api { key } => {
52                self.api_key = Some(key.clone());
53                Some(self)
54            }
55            crate::models::auth::ProviderAuth::OAuth { .. } => None, // OpenAI doesn't support OAuth
56        }
57    }
58}
59
60// =============================================================================
61// Model Definitions
62// =============================================================================
63
64/// OpenAI model identifiers
65#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
66pub enum OpenAIModel {
67    // Reasoning Models
68    #[serde(rename = "o3-2025-04-16")]
69    O3,
70    #[serde(rename = "o4-mini-2025-04-16")]
71    O4Mini,
72
73    #[default]
74    #[serde(rename = "gpt-5-2025-08-07")]
75    GPT5,
76    #[serde(rename = "gpt-5.1-2025-11-13")]
77    GPT51,
78    #[serde(rename = "gpt-5-mini-2025-08-07")]
79    GPT5Mini,
80    #[serde(rename = "gpt-5-nano-2025-08-07")]
81    GPT5Nano,
82
83    Custom(String),
84}
85
86impl OpenAIModel {
87    pub fn from_string(s: &str) -> Result<Self, String> {
88        serde_json::from_value(serde_json::Value::String(s.to_string()))
89            .map_err(|_| "Failed to deserialize OpenAI model".to_string())
90    }
91
92    /// Default smart model for OpenAI
93    pub const DEFAULT_SMART_MODEL: OpenAIModel = OpenAIModel::GPT5;
94
95    /// Default eco model for OpenAI
96    pub const DEFAULT_ECO_MODEL: OpenAIModel = OpenAIModel::GPT5Mini;
97
98    /// Default recovery model for OpenAI
99    pub const DEFAULT_RECOVERY_MODEL: OpenAIModel = OpenAIModel::GPT5Mini;
100
101    /// Get default smart model as string
102    pub fn default_smart_model() -> String {
103        Self::DEFAULT_SMART_MODEL.to_string()
104    }
105
106    /// Get default eco model as string
107    pub fn default_eco_model() -> String {
108        Self::DEFAULT_ECO_MODEL.to_string()
109    }
110
111    /// Get default recovery model as string
112    pub fn default_recovery_model() -> String {
113        Self::DEFAULT_RECOVERY_MODEL.to_string()
114    }
115}
116
117impl ContextAware for OpenAIModel {
118    fn context_info(&self) -> ModelContextInfo {
119        let model_name = self.to_string();
120
121        if model_name.starts_with("o3") {
122            return ModelContextInfo {
123                max_tokens: 200_000,
124                pricing_tiers: vec![ContextPricingTier {
125                    label: "Standard".to_string(),
126                    input_cost_per_million: 2.0,
127                    output_cost_per_million: 8.0,
128                    upper_bound: None,
129                }],
130                approach_warning_threshold: 0.8,
131            };
132        }
133
134        if model_name.starts_with("o4-mini") {
135            return ModelContextInfo {
136                max_tokens: 200_000,
137                pricing_tiers: vec![ContextPricingTier {
138                    label: "Standard".to_string(),
139                    input_cost_per_million: 1.10,
140                    output_cost_per_million: 4.40,
141                    upper_bound: None,
142                }],
143                approach_warning_threshold: 0.8,
144            };
145        }
146
147        if model_name.starts_with("gpt-5-mini") {
148            return ModelContextInfo {
149                max_tokens: 400_000,
150                pricing_tiers: vec![ContextPricingTier {
151                    label: "Standard".to_string(),
152                    input_cost_per_million: 0.25,
153                    output_cost_per_million: 2.0,
154                    upper_bound: None,
155                }],
156                approach_warning_threshold: 0.8,
157            };
158        }
159
160        if model_name.starts_with("gpt-5-nano") {
161            return ModelContextInfo {
162                max_tokens: 400_000,
163                pricing_tiers: vec![ContextPricingTier {
164                    label: "Standard".to_string(),
165                    input_cost_per_million: 0.05,
166                    output_cost_per_million: 0.40,
167                    upper_bound: None,
168                }],
169                approach_warning_threshold: 0.8,
170            };
171        }
172
173        if model_name.starts_with("gpt-5") {
174            return ModelContextInfo {
175                max_tokens: 400_000,
176                pricing_tiers: vec![ContextPricingTier {
177                    label: "Standard".to_string(),
178                    input_cost_per_million: 1.25,
179                    output_cost_per_million: 10.0,
180                    upper_bound: None,
181                }],
182                approach_warning_threshold: 0.8,
183            };
184        }
185
186        ModelContextInfo::default()
187    }
188
189    fn model_name(&self) -> String {
190        match self {
191            OpenAIModel::O3 => "O3".to_string(),
192            OpenAIModel::O4Mini => "O4-mini".to_string(),
193            OpenAIModel::GPT5 => "GPT-5".to_string(),
194            OpenAIModel::GPT51 => "GPT-5.1".to_string(),
195            OpenAIModel::GPT5Mini => "GPT-5 Mini".to_string(),
196            OpenAIModel::GPT5Nano => "GPT-5 Nano".to_string(),
197            OpenAIModel::Custom(name) => format!("Custom ({})", name),
198        }
199    }
200}
201
202impl std::fmt::Display for OpenAIModel {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        match self {
205            OpenAIModel::O3 => write!(f, "o3-2025-04-16"),
206            OpenAIModel::O4Mini => write!(f, "o4-mini-2025-04-16"),
207            OpenAIModel::GPT5Nano => write!(f, "gpt-5-nano-2025-08-07"),
208            OpenAIModel::GPT5Mini => write!(f, "gpt-5-mini-2025-08-07"),
209            OpenAIModel::GPT5 => write!(f, "gpt-5-2025-08-07"),
210            OpenAIModel::GPT51 => write!(f, "gpt-5.1-2025-11-13"),
211            OpenAIModel::Custom(model_name) => write!(f, "{}", model_name),
212        }
213    }
214}
215
216// =============================================================================
217// Message Types (used by TUI)
218// =============================================================================
219
220/// Message role
221#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
222#[serde(rename_all = "lowercase")]
223pub enum Role {
224    System,
225    Developer,
226    User,
227    #[default]
228    Assistant,
229    Tool,
230}
231
232impl std::fmt::Display for Role {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Role::System => write!(f, "system"),
236            Role::Developer => write!(f, "developer"),
237            Role::User => write!(f, "user"),
238            Role::Assistant => write!(f, "assistant"),
239            Role::Tool => write!(f, "tool"),
240        }
241    }
242}
243
244/// Model info for tracking which model generated a message
245#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
246pub struct ModelInfo {
247    /// Provider name (e.g., "anthropic", "openai")
248    pub provider: String,
249    /// Model identifier (e.g., "claude-sonnet-4-20250514", "gpt-4")
250    pub id: String,
251}
252
253/// Chat message
254#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
255pub struct ChatMessage {
256    pub role: Role,
257    pub content: Option<MessageContent>,
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub name: Option<String>,
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub tool_calls: Option<Vec<ToolCall>>,
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub tool_call_id: Option<String>,
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub usage: Option<LLMTokenUsage>,
266
267    // === Extended fields for session tracking ===
268    /// Unique message identifier
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub id: Option<String>,
271    /// Model that generated this message (for assistant messages)
272    #[serde(skip_serializing_if = "Option::is_none")]
273    pub model: Option<ModelInfo>,
274    /// Cost in dollars for this message
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub cost: Option<f64>,
277    /// Why the model stopped: "stop", "tool_calls", "length", "error"
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub finish_reason: Option<String>,
280    /// Unix timestamp (ms) when message was created/sent
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub created_at: Option<i64>,
283    /// Unix timestamp (ms) when assistant finished generating
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub completed_at: Option<i64>,
286    /// Plugin extensibility - unstructured metadata
287    #[serde(skip_serializing_if = "Option::is_none")]
288    pub metadata: Option<serde_json::Value>,
289}
290
291impl ChatMessage {
292    pub fn last_server_message(messages: &[ChatMessage]) -> Option<&ChatMessage> {
293        messages
294            .iter()
295            .rev()
296            .find(|message| message.role != Role::User && message.role != Role::Tool)
297    }
298
299    pub fn to_xml(&self) -> String {
300        match &self.content {
301            Some(MessageContent::String(s)) => {
302                format!("<message role=\"{}\">{}</message>", self.role, s)
303            }
304            Some(MessageContent::Array(parts)) => parts
305                .iter()
306                .map(|part| {
307                    format!(
308                        "<message role=\"{}\" type=\"{}\">{}</message>",
309                        self.role,
310                        part.r#type,
311                        part.text.clone().unwrap_or_default()
312                    )
313                })
314                .collect::<Vec<String>>()
315                .join("\n"),
316            None => String::new(),
317        }
318    }
319}
320
321/// Message content (string or array of parts)
322#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
323#[serde(untagged)]
324pub enum MessageContent {
325    String(String),
326    Array(Vec<ContentPart>),
327}
328
329impl MessageContent {
330    pub fn inject_checkpoint_id(&self, checkpoint_id: Uuid) -> Self {
331        match self {
332            MessageContent::String(s) => MessageContent::String(format!(
333                "<checkpoint_id>{checkpoint_id}</checkpoint_id>\n{s}"
334            )),
335            MessageContent::Array(parts) => MessageContent::Array(
336                std::iter::once(ContentPart {
337                    r#type: "text".to_string(),
338                    text: Some(format!("<checkpoint_id>{checkpoint_id}</checkpoint_id>")),
339                    image_url: None,
340                })
341                .chain(parts.iter().cloned())
342                .collect(),
343            ),
344        }
345    }
346
347    pub fn extract_checkpoint_id(&self) -> Option<Uuid> {
348        match self {
349            MessageContent::String(s) => s
350                .rfind("<checkpoint_id>")
351                .and_then(|start| {
352                    s[start..]
353                        .find("</checkpoint_id>")
354                        .map(|end| (start + "<checkpoint_id>".len(), start + end))
355                })
356                .and_then(|(start, end)| Uuid::parse_str(&s[start..end]).ok()),
357            MessageContent::Array(parts) => parts.iter().rev().find_map(|part| {
358                part.text.as_deref().and_then(|text| {
359                    text.rfind("<checkpoint_id>")
360                        .and_then(|start| {
361                            text[start..]
362                                .find("</checkpoint_id>")
363                                .map(|end| (start + "<checkpoint_id>".len(), start + end))
364                        })
365                        .and_then(|(start, end)| Uuid::parse_str(&text[start..end]).ok())
366                })
367            }),
368        }
369    }
370}
371
372impl std::fmt::Display for MessageContent {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        match self {
375            MessageContent::String(s) => write!(f, "{s}"),
376            MessageContent::Array(parts) => {
377                let text_parts: Vec<String> =
378                    parts.iter().filter_map(|part| part.text.clone()).collect();
379                write!(f, "{}", text_parts.join("\n"))
380            }
381        }
382    }
383}
384
385impl Default for MessageContent {
386    fn default() -> Self {
387        MessageContent::String(String::new())
388    }
389}
390
391/// Content part (text or image)
392#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
393pub struct ContentPart {
394    pub r#type: String,
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub text: Option<String>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub image_url: Option<ImageUrl>,
399}
400
401/// Image URL with optional detail level
402#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
403pub struct ImageUrl {
404    pub url: String,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub detail: Option<String>,
407}
408
409// =============================================================================
410// Tool Types (used by TUI)
411// =============================================================================
412
413/// Tool definition
414#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
415pub struct Tool {
416    pub r#type: String,
417    pub function: FunctionDefinition,
418}
419
420/// Function definition for tools
421#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
422pub struct FunctionDefinition {
423    pub name: String,
424    pub description: Option<String>,
425    pub parameters: serde_json::Value,
426}
427
428impl From<Tool> for LLMTool {
429    fn from(tool: Tool) -> Self {
430        LLMTool {
431            name: tool.function.name,
432            description: tool.function.description.unwrap_or_default(),
433            input_schema: tool.function.parameters,
434        }
435    }
436}
437
438/// Tool choice configuration
439#[derive(Debug, Clone, PartialEq)]
440pub enum ToolChoice {
441    Auto,
442    Required,
443    Object(ToolChoiceObject),
444}
445
446impl Serialize for ToolChoice {
447    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
448    where
449        S: serde::Serializer,
450    {
451        match self {
452            ToolChoice::Auto => serializer.serialize_str("auto"),
453            ToolChoice::Required => serializer.serialize_str("required"),
454            ToolChoice::Object(obj) => obj.serialize(serializer),
455        }
456    }
457}
458
459impl<'de> Deserialize<'de> for ToolChoice {
460    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
461    where
462        D: serde::Deserializer<'de>,
463    {
464        struct ToolChoiceVisitor;
465
466        impl<'de> serde::de::Visitor<'de> for ToolChoiceVisitor {
467            type Value = ToolChoice;
468
469            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
470                formatter.write_str("string or object")
471            }
472
473            fn visit_str<E>(self, value: &str) -> Result<ToolChoice, E>
474            where
475                E: serde::de::Error,
476            {
477                match value {
478                    "auto" => Ok(ToolChoice::Auto),
479                    "required" => Ok(ToolChoice::Required),
480                    _ => Err(serde::de::Error::unknown_variant(
481                        value,
482                        &["auto", "required"],
483                    )),
484                }
485            }
486
487            fn visit_map<M>(self, map: M) -> Result<ToolChoice, M::Error>
488            where
489                M: serde::de::MapAccess<'de>,
490            {
491                let obj = ToolChoiceObject::deserialize(
492                    serde::de::value::MapAccessDeserializer::new(map),
493                )?;
494                Ok(ToolChoice::Object(obj))
495            }
496        }
497
498        deserializer.deserialize_any(ToolChoiceVisitor)
499    }
500}
501
502#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
503pub struct ToolChoiceObject {
504    pub r#type: String,
505    pub function: FunctionChoice,
506}
507
508#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
509pub struct FunctionChoice {
510    pub name: String,
511}
512
513/// Tool call from assistant
514#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
515pub struct ToolCall {
516    pub id: String,
517    pub r#type: String,
518    pub function: FunctionCall,
519    /// Opaque provider-specific metadata (e.g., Gemini thought_signature)
520    #[serde(skip_serializing_if = "Option::is_none")]
521    pub metadata: Option<serde_json::Value>,
522}
523
524/// Function call details
525#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
526pub struct FunctionCall {
527    pub name: String,
528    pub arguments: String,
529}
530
531/// Tool call result status
532#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
533pub enum ToolCallResultStatus {
534    Success,
535    Error,
536    Cancelled,
537}
538
539/// Tool call result
540#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
541pub struct ToolCallResult {
542    pub call: ToolCall,
543    pub result: String,
544    pub status: ToolCallResultStatus,
545}
546
547/// Tool call result progress update
548#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
549pub struct ToolCallResultProgress {
550    pub id: Uuid,
551    pub message: String,
552}
553
554// =============================================================================
555// Chat Completion Types (used by TUI)
556// =============================================================================
557
558/// Chat completion request
559#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
560pub struct ChatCompletionRequest {
561    pub model: String,
562    pub messages: Vec<ChatMessage>,
563    #[serde(skip_serializing_if = "Option::is_none")]
564    pub frequency_penalty: Option<f32>,
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub logit_bias: Option<serde_json::Value>,
567    #[serde(skip_serializing_if = "Option::is_none")]
568    pub logprobs: Option<bool>,
569    #[serde(skip_serializing_if = "Option::is_none")]
570    pub max_tokens: Option<u32>,
571    #[serde(skip_serializing_if = "Option::is_none")]
572    pub n: Option<u32>,
573    #[serde(skip_serializing_if = "Option::is_none")]
574    pub presence_penalty: Option<f32>,
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub response_format: Option<ResponseFormat>,
577    #[serde(skip_serializing_if = "Option::is_none")]
578    pub seed: Option<i64>,
579    #[serde(skip_serializing_if = "Option::is_none")]
580    pub stop: Option<StopSequence>,
581    #[serde(skip_serializing_if = "Option::is_none")]
582    pub stream: Option<bool>,
583    #[serde(skip_serializing_if = "Option::is_none")]
584    pub temperature: Option<f32>,
585    #[serde(skip_serializing_if = "Option::is_none")]
586    pub top_p: Option<f32>,
587    #[serde(skip_serializing_if = "Option::is_none")]
588    pub tools: Option<Vec<Tool>>,
589    #[serde(skip_serializing_if = "Option::is_none")]
590    pub tool_choice: Option<ToolChoice>,
591    #[serde(skip_serializing_if = "Option::is_none")]
592    pub user: Option<String>,
593    #[serde(skip_serializing_if = "Option::is_none")]
594    pub context: Option<ChatCompletionContext>,
595}
596
597impl ChatCompletionRequest {
598    pub fn new(
599        model: String,
600        messages: Vec<ChatMessage>,
601        tools: Option<Vec<Tool>>,
602        stream: Option<bool>,
603    ) -> Self {
604        Self {
605            model,
606            messages,
607            frequency_penalty: None,
608            logit_bias: None,
609            logprobs: None,
610            max_tokens: None,
611            n: None,
612            presence_penalty: None,
613            response_format: None,
614            seed: None,
615            stop: None,
616            stream,
617            temperature: None,
618            top_p: None,
619            tools,
620            tool_choice: None,
621            user: None,
622            context: None,
623        }
624    }
625}
626
627#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
628pub struct ChatCompletionContext {
629    pub scratchpad: Option<Value>,
630}
631
632#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
633pub struct ResponseFormat {
634    pub r#type: String,
635}
636
637#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
638#[serde(untagged)]
639pub enum StopSequence {
640    String(String),
641    Array(Vec<String>),
642}
643
644/// Chat completion response
645#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
646pub struct ChatCompletionResponse {
647    pub id: String,
648    pub object: String,
649    pub created: u64,
650    pub model: String,
651    pub choices: Vec<ChatCompletionChoice>,
652    pub usage: LLMTokenUsage,
653    #[serde(skip_serializing_if = "Option::is_none")]
654    pub system_fingerprint: Option<String>,
655    pub metadata: Option<serde_json::Value>,
656}
657
658#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
659pub struct ChatCompletionChoice {
660    pub index: usize,
661    pub message: ChatMessage,
662    pub logprobs: Option<LogProbs>,
663    pub finish_reason: FinishReason,
664}
665
666#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
667#[serde(rename_all = "snake_case")]
668pub enum FinishReason {
669    Stop,
670    Length,
671    ContentFilter,
672    ToolCalls,
673}
674
675#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
676pub struct LogProbs {
677    pub content: Option<Vec<LogProbContent>>,
678}
679
680#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
681pub struct LogProbContent {
682    pub token: String,
683    pub logprob: f32,
684    pub bytes: Option<Vec<u8>>,
685    pub top_logprobs: Option<Vec<TokenLogprob>>,
686}
687
688#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
689pub struct TokenLogprob {
690    pub token: String,
691    pub logprob: f32,
692    pub bytes: Option<Vec<u8>>,
693}
694
695// =============================================================================
696// Streaming Types
697// =============================================================================
698
699#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
700pub struct ChatCompletionStreamResponse {
701    pub id: String,
702    pub object: String,
703    pub created: u64,
704    pub model: String,
705    pub choices: Vec<ChatCompletionStreamChoice>,
706    pub usage: Option<LLMTokenUsage>,
707    pub metadata: Option<serde_json::Value>,
708}
709
710#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
711pub struct ChatCompletionStreamChoice {
712    pub index: usize,
713    pub delta: ChatMessageDelta,
714    pub finish_reason: Option<FinishReason>,
715}
716
717#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
718pub struct ChatMessageDelta {
719    #[serde(skip_serializing_if = "Option::is_none")]
720    pub role: Option<Role>,
721    #[serde(skip_serializing_if = "Option::is_none")]
722    pub content: Option<String>,
723    #[serde(skip_serializing_if = "Option::is_none")]
724    pub tool_calls: Option<Vec<ToolCallDelta>>,
725}
726
727#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
728pub struct ToolCallDelta {
729    pub index: usize,
730    pub id: Option<String>,
731    pub r#type: Option<String>,
732    pub function: Option<FunctionCallDelta>,
733    /// Opaque provider-specific metadata (e.g., Gemini thought_signature)
734    #[serde(skip_serializing_if = "Option::is_none")]
735    pub metadata: Option<serde_json::Value>,
736}
737
738#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
739pub struct FunctionCallDelta {
740    pub name: Option<String>,
741    pub arguments: Option<String>,
742}
743
744// =============================================================================
745// Conversions
746// =============================================================================
747
748impl From<LLMMessage> for ChatMessage {
749    fn from(llm_message: LLMMessage) -> Self {
750        let role = match llm_message.role.as_str() {
751            "system" => Role::System,
752            "user" => Role::User,
753            "assistant" => Role::Assistant,
754            "tool" => Role::Tool,
755            "developer" => Role::Developer,
756            _ => Role::User,
757        };
758
759        let (content, tool_calls) = match llm_message.content {
760            LLMMessageContent::String(text) => (Some(MessageContent::String(text)), None),
761            LLMMessageContent::List(items) => {
762                let mut text_parts = Vec::new();
763                let mut tool_call_parts = Vec::new();
764
765                for item in items {
766                    match item {
767                        LLMMessageTypedContent::Text { text } => {
768                            text_parts.push(ContentPart {
769                                r#type: "text".to_string(),
770                                text: Some(text),
771                                image_url: None,
772                            });
773                        }
774                        LLMMessageTypedContent::ToolCall {
775                            id,
776                            name,
777                            args,
778                            metadata,
779                        } => {
780                            tool_call_parts.push(ToolCall {
781                                id,
782                                r#type: "function".to_string(),
783                                function: FunctionCall {
784                                    name,
785                                    arguments: args.to_string(),
786                                },
787                                metadata,
788                            });
789                        }
790                        LLMMessageTypedContent::ToolResult { content, .. } => {
791                            text_parts.push(ContentPart {
792                                r#type: "text".to_string(),
793                                text: Some(content),
794                                image_url: None,
795                            });
796                        }
797                        LLMMessageTypedContent::Image { source } => {
798                            text_parts.push(ContentPart {
799                                r#type: "image_url".to_string(),
800                                text: None,
801                                image_url: Some(ImageUrl {
802                                    url: format!(
803                                        "data:{};base64,{}",
804                                        source.media_type, source.data
805                                    ),
806                                    detail: None,
807                                }),
808                            });
809                        }
810                    }
811                }
812
813                let content = if !text_parts.is_empty() {
814                    Some(MessageContent::Array(text_parts))
815                } else {
816                    None
817                };
818
819                let tool_calls = if !tool_call_parts.is_empty() {
820                    Some(tool_call_parts)
821                } else {
822                    None
823                };
824
825                (content, tool_calls)
826            }
827        };
828
829        ChatMessage {
830            role,
831            content,
832            name: None,
833            tool_calls,
834            tool_call_id: None,
835            usage: None,
836            ..Default::default()
837        }
838    }
839}
840
841impl From<ChatMessage> for LLMMessage {
842    fn from(chat_message: ChatMessage) -> Self {
843        let mut content_parts = Vec::new();
844
845        match chat_message.content {
846            Some(MessageContent::String(s)) => {
847                if !s.is_empty() {
848                    content_parts.push(LLMMessageTypedContent::Text { text: s });
849                }
850            }
851            Some(MessageContent::Array(parts)) => {
852                for part in parts {
853                    if let Some(text) = part.text {
854                        content_parts.push(LLMMessageTypedContent::Text { text });
855                    } else if let Some(image_url) = part.image_url {
856                        let (media_type, data) = if image_url.url.starts_with("data:") {
857                            let parts: Vec<&str> = image_url.url.splitn(2, ',').collect();
858                            if parts.len() == 2 {
859                                let meta = parts[0];
860                                let data = parts[1];
861                                let media_type = meta
862                                    .trim_start_matches("data:")
863                                    .trim_end_matches(";base64")
864                                    .to_string();
865                                (media_type, data.to_string())
866                            } else {
867                                ("image/jpeg".to_string(), image_url.url)
868                            }
869                        } else {
870                            ("image/jpeg".to_string(), image_url.url)
871                        };
872
873                        content_parts.push(LLMMessageTypedContent::Image {
874                            source: LLMMessageImageSource {
875                                r#type: "base64".to_string(),
876                                media_type,
877                                data,
878                            },
879                        });
880                    }
881                }
882            }
883            None => {}
884        }
885
886        if let Some(tool_calls) = chat_message.tool_calls {
887            for tool_call in tool_calls {
888                let args = serde_json::from_str(&tool_call.function.arguments).unwrap_or(json!({}));
889                content_parts.push(LLMMessageTypedContent::ToolCall {
890                    id: tool_call.id,
891                    name: tool_call.function.name,
892                    args,
893                    metadata: tool_call.metadata,
894                });
895            }
896        }
897
898        // Handle tool result messages: when role is Tool and tool_call_id is present,
899        // convert the content to a ToolResult content part. This is the generic
900        // intermediate representation - each provider's conversion layer handles
901        // the specifics (e.g., Anthropic converts to user role with tool_result blocks)
902        if chat_message.role == Role::Tool
903            && let Some(tool_call_id) = chat_message.tool_call_id
904        {
905            // Extract content as string for the tool result
906            let content_str = content_parts
907                .iter()
908                .filter_map(|p| match p {
909                    LLMMessageTypedContent::Text { text } => Some(text.clone()),
910                    _ => None,
911                })
912                .collect::<Vec<_>>()
913                .join("\n");
914
915            // Replace content with a single ToolResult
916            content_parts = vec![LLMMessageTypedContent::ToolResult {
917                tool_use_id: tool_call_id,
918                content: content_str,
919            }];
920        }
921
922        LLMMessage {
923            role: chat_message.role.to_string(),
924            content: if content_parts.is_empty() {
925                LLMMessageContent::String(String::new())
926            } else if content_parts.len() == 1 {
927                match &content_parts[0] {
928                    LLMMessageTypedContent::Text { text } => {
929                        LLMMessageContent::String(text.clone())
930                    }
931                    _ => LLMMessageContent::List(content_parts),
932                }
933            } else {
934                LLMMessageContent::List(content_parts)
935            },
936        }
937    }
938}
939
940impl From<GenerationDelta> for ChatMessageDelta {
941    fn from(delta: GenerationDelta) -> Self {
942        match delta {
943            GenerationDelta::Content { content } => ChatMessageDelta {
944                role: Some(Role::Assistant),
945                content: Some(content),
946                tool_calls: None,
947            },
948            GenerationDelta::Thinking { thinking: _ } => ChatMessageDelta {
949                role: Some(Role::Assistant),
950                content: None,
951                tool_calls: None,
952            },
953            GenerationDelta::ToolUse { tool_use } => ChatMessageDelta {
954                role: Some(Role::Assistant),
955                content: None,
956                tool_calls: Some(vec![ToolCallDelta {
957                    index: tool_use.index,
958                    id: tool_use.id,
959                    r#type: Some("function".to_string()),
960                    function: Some(FunctionCallDelta {
961                        name: tool_use.name,
962                        arguments: tool_use.input,
963                    }),
964                    metadata: tool_use.metadata,
965                }]),
966            },
967            _ => ChatMessageDelta {
968                role: Some(Role::Assistant),
969                content: None,
970                tool_calls: None,
971            },
972        }
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979
980    #[test]
981    fn test_serialize_basic_request() {
982        let request = ChatCompletionRequest {
983            model: "gpt-4".to_string(),
984            messages: vec![
985                ChatMessage {
986                    role: Role::System,
987                    content: Some(MessageContent::String(
988                        "You are a helpful assistant.".to_string(),
989                    )),
990                    name: None,
991                    tool_calls: None,
992                    tool_call_id: None,
993                    usage: None,
994                    ..Default::default()
995                },
996                ChatMessage {
997                    role: Role::User,
998                    content: Some(MessageContent::String("Hello!".to_string())),
999                    name: None,
1000                    tool_calls: None,
1001                    tool_call_id: None,
1002                    usage: None,
1003                    ..Default::default()
1004                },
1005            ],
1006            frequency_penalty: None,
1007            logit_bias: None,
1008            logprobs: None,
1009            max_tokens: Some(100),
1010            n: None,
1011            presence_penalty: None,
1012            response_format: None,
1013            seed: None,
1014            stop: None,
1015            stream: None,
1016            temperature: Some(0.7),
1017            top_p: None,
1018            tools: None,
1019            tool_choice: None,
1020            user: None,
1021            context: None,
1022        };
1023
1024        let json = serde_json::to_string(&request).unwrap();
1025        assert!(json.contains("\"model\":\"gpt-4\""));
1026        assert!(json.contains("\"messages\":["));
1027        assert!(json.contains("\"role\":\"system\""));
1028    }
1029
1030    #[test]
1031    fn test_llm_message_to_chat_message() {
1032        let llm_message = LLMMessage {
1033            role: "user".to_string(),
1034            content: LLMMessageContent::String("Hello, world!".to_string()),
1035        };
1036
1037        let chat_message = ChatMessage::from(llm_message);
1038        assert_eq!(chat_message.role, Role::User);
1039        match &chat_message.content {
1040            Some(MessageContent::String(text)) => assert_eq!(text, "Hello, world!"),
1041            _ => panic!("Expected string content"),
1042        }
1043    }
1044
1045    #[test]
1046    fn test_chat_message_to_llm_message_tool_result() {
1047        // Test that Tool role messages with tool_call_id are converted to ToolResult content
1048        // This is critical for Anthropic compatibility - the provider layer converts
1049        // role="tool" to role="user" with tool_result content blocks
1050        let chat_message = ChatMessage {
1051            role: Role::Tool,
1052            content: Some(MessageContent::String("Tool execution result".to_string())),
1053            name: None,
1054            tool_calls: None,
1055            tool_call_id: Some("toolu_01Abc123".to_string()),
1056            usage: None,
1057            ..Default::default()
1058        };
1059
1060        let llm_message: LLMMessage = chat_message.into();
1061
1062        // Role should be preserved as "tool" - provider layer handles conversion
1063        assert_eq!(llm_message.role, "tool");
1064
1065        // Content should be a ToolResult with the tool_call_id
1066        match &llm_message.content {
1067            LLMMessageContent::List(parts) => {
1068                assert_eq!(parts.len(), 1, "Should have exactly one content part");
1069                match &parts[0] {
1070                    LLMMessageTypedContent::ToolResult {
1071                        tool_use_id,
1072                        content,
1073                    } => {
1074                        assert_eq!(tool_use_id, "toolu_01Abc123");
1075                        assert_eq!(content, "Tool execution result");
1076                    }
1077                    _ => panic!("Expected ToolResult content part, got {:?}", parts[0]),
1078                }
1079            }
1080            _ => panic!(
1081                "Expected List content with ToolResult, got {:?}",
1082                llm_message.content
1083            ),
1084        }
1085    }
1086
1087    #[test]
1088    fn test_chat_message_to_llm_message_tool_result_empty_content() {
1089        // Test tool result with empty content
1090        let chat_message = ChatMessage {
1091            role: Role::Tool,
1092            content: None,
1093            name: None,
1094            tool_calls: None,
1095            tool_call_id: Some("toolu_02Xyz789".to_string()),
1096            usage: None,
1097            ..Default::default()
1098        };
1099
1100        let llm_message: LLMMessage = chat_message.into();
1101
1102        assert_eq!(llm_message.role, "tool");
1103        match &llm_message.content {
1104            LLMMessageContent::List(parts) => {
1105                assert_eq!(parts.len(), 1);
1106                match &parts[0] {
1107                    LLMMessageTypedContent::ToolResult {
1108                        tool_use_id,
1109                        content,
1110                    } => {
1111                        assert_eq!(tool_use_id, "toolu_02Xyz789");
1112                        assert_eq!(content, ""); // Empty content
1113                    }
1114                    _ => panic!("Expected ToolResult content part"),
1115                }
1116            }
1117            _ => panic!("Expected List content with ToolResult"),
1118        }
1119    }
1120
1121    #[test]
1122    fn test_chat_message_to_llm_message_assistant_with_tool_calls() {
1123        // Test that assistant messages with tool_calls are converted correctly
1124        let chat_message = ChatMessage {
1125            role: Role::Assistant,
1126            content: Some(MessageContent::String(
1127                "I'll help you with that.".to_string(),
1128            )),
1129            name: None,
1130            tool_calls: Some(vec![ToolCall {
1131                id: "call_abc123".to_string(),
1132                r#type: "function".to_string(),
1133                function: FunctionCall {
1134                    name: "get_weather".to_string(),
1135                    arguments: r#"{"location": "Paris"}"#.to_string(),
1136                },
1137                metadata: None,
1138            }]),
1139            tool_call_id: None,
1140            usage: None,
1141            ..Default::default()
1142        };
1143
1144        let llm_message: LLMMessage = chat_message.into();
1145
1146        assert_eq!(llm_message.role, "assistant");
1147        match &llm_message.content {
1148            LLMMessageContent::List(parts) => {
1149                assert_eq!(parts.len(), 2, "Should have text and tool call");
1150
1151                // First part should be text
1152                match &parts[0] {
1153                    LLMMessageTypedContent::Text { text } => {
1154                        assert_eq!(text, "I'll help you with that.");
1155                    }
1156                    _ => panic!("Expected Text content part first"),
1157                }
1158
1159                // Second part should be tool call
1160                match &parts[1] {
1161                    LLMMessageTypedContent::ToolCall { id, name, args, .. } => {
1162                        assert_eq!(id, "call_abc123");
1163                        assert_eq!(name, "get_weather");
1164                        assert_eq!(args["location"], "Paris");
1165                    }
1166                    _ => panic!("Expected ToolCall content part second"),
1167                }
1168            }
1169            _ => panic!("Expected List content"),
1170        }
1171    }
1172}