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 Image {
82 media_type: String,
83 data: String,
84 },
85 Thinking {
87 text: String,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 thought_signature: Option<String>,
90 },
91}
92
93#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
94#[serde(tag = "type", rename_all = "snake_case")]
95pub enum ToolResultContentBlock {
96 Text { text: String },
97 Json { value: Value },
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct ToolDefinition {
102 pub name: String,
103 #[serde(skip_serializing_if = "Option::is_none")]
104 pub description: Option<String>,
105 pub input_schema: Value,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(tag = "type", rename_all = "snake_case")]
110pub enum ToolChoice {
111 Auto,
112 Any,
113 Tool { name: String },
114}
115
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117pub struct MessageResponse {
118 pub id: String,
119 #[serde(rename = "type")]
120 pub kind: String,
121 pub role: String,
122 pub content: Vec<OutputContentBlock>,
123 pub model: String,
124 #[serde(default)]
125 pub stop_reason: Option<String>,
126 #[serde(default)]
127 pub stop_sequence: Option<String>,
128 pub usage: Usage,
129 #[serde(default)]
130 pub request_id: Option<String>,
131}
132
133impl MessageResponse {
134 #[must_use]
135 pub fn total_tokens(&self) -> u32 {
136 self.usage.total_tokens()
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(tag = "type", rename_all = "snake_case")]
142pub enum OutputContentBlock {
143 Text {
144 text: String,
145 },
146 ToolUse {
147 id: String,
148 name: String,
149 input: Value,
150 },
151 Thinking {
153 text: String,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 thought_signature: Option<String>,
156 },
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct Usage {
161 pub input_tokens: u32,
162 #[serde(default)]
163 pub cache_creation_input_tokens: u32,
164 #[serde(default)]
165 pub cache_read_input_tokens: u32,
166 pub output_tokens: u32,
167}
168
169impl Usage {
170 #[must_use]
171 pub const fn total_tokens(&self) -> u32 {
172 self.input_tokens + self.output_tokens
173 }
174}
175
176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
177pub struct MessageStartEvent {
178 pub message: MessageResponse,
179}
180
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182pub struct MessageDeltaEvent {
183 pub delta: MessageDelta,
184 pub usage: Usage,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188pub struct MessageDelta {
189 #[serde(default)]
190 pub stop_reason: Option<String>,
191 #[serde(default)]
192 pub stop_sequence: Option<String>,
193}
194
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196pub struct ContentBlockStartEvent {
197 pub index: u32,
198 pub content_block: OutputContentBlock,
199}
200
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub struct ContentBlockDeltaEvent {
203 pub index: u32,
204 pub delta: ContentBlockDelta,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(tag = "type", rename_all = "snake_case")]
209pub enum ContentBlockDelta {
210 TextDelta { text: String },
211 InputJsonDelta { partial_json: String },
212}
213
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215pub struct ContentBlockStopEvent {
216 pub index: u32,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220pub struct MessageStopEvent {}
221
222#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
223#[serde(tag = "type", rename_all = "snake_case")]
224pub enum StreamEvent {
225 MessageStart(MessageStartEvent),
226 MessageDelta(MessageDeltaEvent),
227 ContentBlockStart(ContentBlockStartEvent),
228 ContentBlockDelta(ContentBlockDeltaEvent),
229 ContentBlockStop(ContentBlockStopEvent),
230 MessageStop(MessageStopEvent),
231}
232
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234#[serde(tag = "type", rename_all = "snake_case")]
235pub enum AuthSource {
236 None,
237 ApiKey(String),
238 BearerToken(String),
239 ApiKeyAndBearer { api_key: String, bearer_token: String },
240}
241
242impl AuthSource {
243 pub fn from_env_or_saved() -> Result<Self, crate::error::ApiError> {
244 if let Some(api_key) = crate::client::read_env_non_empty("TERNLANG_API_KEY")? {
245 return match crate::client::read_env_non_empty("TERNLANG_AUTH_TOKEN")? {
246 Some(bearer_token) => Ok(Self::ApiKeyAndBearer {
247 api_key,
248 bearer_token,
249 }),
250 None => Ok(Self::ApiKey(api_key)),
251 };
252 }
253 Ok(Self::None)
254 }
255
256 pub fn apply(&self, provider: crate::client::LlmProvider, rb: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
257 use crate::client::LlmProvider;
258 match (provider, self) {
259 (LlmProvider::Google, _) => rb,
261 (LlmProvider::Anthropic, Self::ApiKey(key)) => rb.header("x-api-key", key),
263 (p, Self::ApiKey(key)) if p.is_openai_compat() => rb.bearer_auth(key),
265 (_, Self::BearerToken(token)) => rb.bearer_auth(token),
266 (_, Self::ApiKeyAndBearer { api_key, bearer_token }) => {
267 rb.header("x-api-key", api_key).bearer_auth(bearer_token)
268 }
269 (LlmProvider::Ternlang, Self::ApiKey(key)) => rb.header("x-api-key", key),
270 _ => rb,
271 }
272 }
273
274 pub fn api_key(&self) -> Option<&str> {
275 match self {
276 Self::ApiKey(key) => Some(key),
277 Self::ApiKeyAndBearer { api_key, .. } => Some(api_key),
278 _ => None,
279 }
280 }
281}
282
283#[derive(Debug, Clone, Serialize, Deserialize)]
284pub struct OAuthTokenSet {
285 pub access_token: String,
286 pub refresh_token: Option<String>,
287 pub expires_at: Option<u64>,
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct RuntimeTokenSet {
292 pub access_token: String,
293 pub refresh_token: Option<String>,
294 pub expires_at: Option<u64>,
295 pub scopes: Vec<String>,
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct OAuthTokenExchangeRequest {
300 pub code: String,
301 pub redirect_uri: String,
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct EmbeddingRequest {
306 pub model: String,
307 pub input: Vec<String>,
308}
309
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct EmbeddingResponse {
312 pub data: Vec<EmbeddingData>,
313 pub model: String,
314 pub usage: EmbeddingUsage,
315}
316
317#[derive(Debug, Clone, Serialize, Deserialize)]
318pub struct EmbeddingData {
319 pub embedding: Vec<f32>,
320 pub index: usize,
321}
322
323#[derive(Debug, Clone, Serialize, Deserialize)]
324pub struct EmbeddingUsage {
325 pub prompt_tokens: u32,
326 pub total_tokens: u32,
327}