Skip to main content

albert_api/
types.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4pub const TERNLANG_VERSION: &str = "2023-06-01";
5
6#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
7pub struct MessageRequest {
8    pub model: String,
9    pub max_tokens: Option<u32>,
10    pub messages: Vec<InputMessage>,
11    #[serde(skip_serializing_if = "Option::is_none")]
12    pub system: Option<String>,
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub tools: Option<Vec<ToolDefinition>>,
15    #[serde(skip_serializing_if = "Option::is_none")]
16    pub tool_choice: Option<ToolChoice>,
17    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
18    pub stream: bool,
19}
20
21impl MessageRequest {
22    #[must_use]
23    pub fn with_streaming(mut self) -> Self {
24        self.stream = true;
25        self
26    }
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct InputMessage {
31    pub role: String,
32    pub content: Vec<InputContentBlock>,
33}
34
35impl InputMessage {
36    #[must_use]
37    pub fn user_text(text: impl Into<String>) -> Self {
38        Self {
39            role: "user".to_string(),
40            content: vec![InputContentBlock::Text { text: text.into() }],
41        }
42    }
43
44    #[must_use]
45    pub fn user_tool_result(
46        tool_use_id: impl Into<String>,
47        content: impl Into<String>,
48        is_error: bool,
49    ) -> Self {
50        Self {
51            role: "user".to_string(),
52            content: vec![InputContentBlock::ToolResult {
53                tool_use_id: tool_use_id.into(),
54                content: vec![ToolResultContentBlock::Text {
55                    text: content.into(),
56                }],
57                is_error,
58            }],
59        }
60    }
61}
62
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64#[serde(tag = "type", rename_all = "snake_case")]
65pub enum InputContentBlock {
66    Text {
67        text: String,
68    },
69    ToolUse {
70        id: String,
71        name: String,
72        input: Value,
73    },
74    ToolResult {
75        tool_use_id: String,
76        content: Vec<ToolResultContentBlock>,
77        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
78        is_error: bool,
79    },
80    /// Base64-encoded image for vision/multimodal requests.
81    Image {
82        media_type: String,
83        data: String,
84    },
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88#[serde(tag = "type", rename_all = "snake_case")]
89pub enum ToolResultContentBlock {
90    Text { text: String },
91    Json { value: Value },
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct ToolDefinition {
96    pub name: String,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub description: Option<String>,
99    pub input_schema: Value,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(tag = "type", rename_all = "snake_case")]
104pub enum ToolChoice {
105    Auto,
106    Any,
107    Tool { name: String },
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct MessageResponse {
112    pub id: String,
113    #[serde(rename = "type")]
114    pub kind: String,
115    pub role: String,
116    pub content: Vec<OutputContentBlock>,
117    pub model: String,
118    #[serde(default)]
119    pub stop_reason: Option<String>,
120    #[serde(default)]
121    pub stop_sequence: Option<String>,
122    pub usage: Usage,
123    #[serde(default)]
124    pub request_id: Option<String>,
125}
126
127impl MessageResponse {
128    #[must_use]
129    pub fn total_tokens(&self) -> u32 {
130        self.usage.total_tokens()
131    }
132}
133
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135#[serde(tag = "type", rename_all = "snake_case")]
136pub enum OutputContentBlock {
137    Text {
138        text: String,
139    },
140    ToolUse {
141        id: String,
142        name: String,
143        input: Value,
144    },
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Usage {
149    pub input_tokens: u32,
150    #[serde(default)]
151    pub cache_creation_input_tokens: u32,
152    #[serde(default)]
153    pub cache_read_input_tokens: u32,
154    pub output_tokens: u32,
155}
156
157impl Usage {
158    #[must_use]
159    pub const fn total_tokens(&self) -> u32 {
160        self.input_tokens + self.output_tokens
161    }
162}
163
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165pub struct MessageStartEvent {
166    pub message: MessageResponse,
167}
168
169#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
170pub struct MessageDeltaEvent {
171    pub delta: MessageDelta,
172    pub usage: Usage,
173}
174
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct MessageDelta {
177    #[serde(default)]
178    pub stop_reason: Option<String>,
179    #[serde(default)]
180    pub stop_sequence: Option<String>,
181}
182
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184pub struct ContentBlockStartEvent {
185    pub index: u32,
186    pub content_block: OutputContentBlock,
187}
188
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190pub struct ContentBlockDeltaEvent {
191    pub index: u32,
192    pub delta: ContentBlockDelta,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(tag = "type", rename_all = "snake_case")]
197pub enum ContentBlockDelta {
198    TextDelta { text: String },
199    InputJsonDelta { partial_json: String },
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct ContentBlockStopEvent {
204    pub index: u32,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208pub struct MessageStopEvent {}
209
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211#[serde(tag = "type", rename_all = "snake_case")]
212pub enum StreamEvent {
213    MessageStart(MessageStartEvent),
214    MessageDelta(MessageDeltaEvent),
215    ContentBlockStart(ContentBlockStartEvent),
216    ContentBlockDelta(ContentBlockDeltaEvent),
217    ContentBlockStop(ContentBlockStopEvent),
218    MessageStop(MessageStopEvent),
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222#[serde(tag = "type", rename_all = "snake_case")]
223pub enum AuthSource {
224    None,
225    ApiKey(String),
226    BearerToken(String),
227    ApiKeyAndBearer { api_key: String, bearer_token: String },
228}
229
230impl AuthSource {
231    pub fn from_env_or_saved() -> Result<Self, crate::error::ApiError> {
232        if let Some(api_key) = crate::client::read_env_non_empty("TERNLANG_API_KEY")? {
233            return match crate::client::read_env_non_empty("TERNLANG_AUTH_TOKEN")? {
234                Some(bearer_token) => Ok(Self::ApiKeyAndBearer {
235                    api_key,
236                    bearer_token,
237                }),
238                None => Ok(Self::ApiKey(api_key)),
239            };
240        }
241        Ok(Self::None)
242    }
243
244    pub fn apply(&self, provider: crate::client::LlmProvider, rb: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
245        use crate::client::LlmProvider;
246        match (provider, self) {
247            // Google auth is added to the URL as ?key=, not a header.
248            (LlmProvider::Google, _) => rb,
249            // Anthropic uses x-api-key header.
250            (LlmProvider::Anthropic, Self::ApiKey(key)) => rb.header("x-api-key", key),
251            // All OpenAI-compatible providers use Bearer auth.
252            (p, Self::ApiKey(key)) if p.is_openai_compat() => rb.bearer_auth(key),
253            (_, Self::BearerToken(token)) => rb.bearer_auth(token),
254            (_, Self::ApiKeyAndBearer { api_key, bearer_token }) => {
255                rb.header("x-api-key", api_key).bearer_auth(bearer_token)
256            }
257            _ => rb,
258        }
259    }
260
261    pub fn api_key(&self) -> Option<&str> {
262        match self {
263            Self::ApiKey(key) => Some(key),
264            Self::ApiKeyAndBearer { api_key, .. } => Some(api_key),
265            _ => None,
266        }
267    }
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct OAuthTokenSet {
272    pub access_token: String,
273    pub refresh_token: Option<String>,
274    pub expires_at: Option<u64>,
275}
276
277#[derive(Debug, Clone, Serialize, Deserialize)]
278pub struct RuntimeTokenSet {
279    pub access_token: String,
280    pub refresh_token: Option<String>,
281    pub expires_at: Option<u64>,
282    pub scopes: Vec<String>,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize)]
286pub struct OAuthTokenExchangeRequest {
287    pub code: String,
288    pub redirect_uri: String,
289}
290
291#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct EmbeddingRequest {
293    pub model: String,
294    pub input: Vec<String>,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct EmbeddingResponse {
299    pub data: Vec<EmbeddingData>,
300    pub model: String,
301    pub usage: EmbeddingUsage,
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct EmbeddingData {
306    pub embedding: Vec<f32>,
307    pub index: usize,
308}
309
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct EmbeddingUsage {
312    pub prompt_tokens: u32,
313    pub total_tokens: u32,
314}