jutella 0.8.1

Chatbot API client library and CLI interface.
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
// Copyright (c) 2024 Dmitry Markin
//
// SPDX-License-Identifier: MIT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! OpenAI API Message types.

use serde::{
    de::Error as _,
    ser::{SerializeMap, SerializeSeq},
    Deserialize, Deserializer, Serialize, Serializer,
};
use serde_json::value::Value;

/// Conversation message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Message {
    /// System message.
    System(SystemMessage),
    /// User message.
    User(UserMessage),
    /// Assistant message.
    Assistant(AssistantMessage),
    /// Tool message.
    Tool(ToolMessage),
}

/// System message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemMessage {
    /// The contents of the message.
    pub content: String,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    pub name: Option<String>,
}

impl SystemMessage {
    pub fn new(content: String) -> Self {
        Self {
            content,
            name: None,
        }
    }
}

/// User message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserMessage {
    /// The contents of the message.
    pub content: Content,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    pub name: Option<String>,
}

impl UserMessage {
    pub fn new(content: Content) -> Self {
        Self {
            content,
            name: None,
        }
    }

    #[cfg(test)]
    pub fn new_from_str(content: &str) -> Self {
        Self {
            content: Content::Text(content.to_string()),
            name: None,
        }
    }
}

/// Assistant message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssistantMessage {
    /// The contents of the message.
    pub content: Content,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    pub name: Option<String>,
    /// The refusal message by the assistant.
    pub refusal: Option<String>,
    /// The tool calls generated by the model, such as function calls.
    pub tool_calls: Option<Value>,
}

impl AssistantMessage {
    pub fn new(content: Content) -> Self {
        Self {
            content,
            name: None,
            refusal: None,
            tool_calls: None,
        }
    }

    #[cfg(test)]
    pub fn new_from_str(content: &str) -> Self {
        Self {
            content: Content::Text(content.to_string()),
            name: None,
            refusal: None,
            tool_calls: None,
        }
    }
}

/// Tool message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolMessage {
    /// The contents of the message.
    pub content: String,
    /// Tool call that this message is responding to.
    pub tool_call_id: String,
}

impl From<SystemMessage> for Message {
    fn from(message: SystemMessage) -> Self {
        Self::System(message)
    }
}

impl From<UserMessage> for Message {
    fn from(message: UserMessage) -> Self {
        Self::User(message)
    }
}

impl From<AssistantMessage> for Message {
    fn from(message: AssistantMessage) -> Self {
        Self::Assistant(message)
    }
}

impl From<ToolMessage> for Message {
    fn from(message: ToolMessage) -> Self {
        Self::Tool(message)
    }
}

/// The role of the message author.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// System message.
    System,
    /// User message.
    User,
    /// Assistant message.
    Assistant,
    /// Tool message.
    Tool,
}

/// Single-part generic message. Used to parse model responses.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ResponseGenericMessage {
    /// The role of the message author.
    role: Role,
    /// The contents of the message.
    content: Option<String>,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    name: Option<String>,
    /// The refusal message by the assistant.
    refusal: Option<String>,
    /// The tool calls generated by the model, such as function calls.
    tool_calls: Option<Value>,
    /// Tool call that this message is responding to.
    tool_call_id: Option<String>,

    // OpenRouter specific fields.
    /// Reasoning performaed by model.
    reasoning: Option<String>,
    /// Generated images.
    images: Option<Vec<ImagePart>>,
}

/// Multi-part generic message. Used to pass user messages.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RequestGenericMessage {
    /// The role of the message author.
    role: Role,
    /// The contents of the message.
    content: Content,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// Tool call that this message is responding to.
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_call_id: Option<String>,
}

impl From<Message> for RequestGenericMessage {
    fn from(message: Message) -> Self {
        match message {
            Message::System(m) => m.into(),
            Message::User(m) => m.into(),
            Message::Assistant(m) => m.into(),
            Message::Tool(m) => m.into(),
        }
    }
}

impl From<SystemMessage> for RequestGenericMessage {
    fn from(SystemMessage { content, name }: SystemMessage) -> Self {
        Self {
            role: Role::System,
            content: Content::Text(content),
            name,
            tool_call_id: None,
        }
    }
}

impl From<UserMessage> for RequestGenericMessage {
    fn from(UserMessage { content, name }: UserMessage) -> Self {
        Self {
            role: Role::User,
            content,
            name,
            tool_call_id: None,
        }
    }
}

impl From<AssistantMessage> for RequestGenericMessage {
    fn from(
        AssistantMessage {
            content,
            name,
            refusal: _,
            tool_calls: _,
        }: AssistantMessage,
    ) -> Self {
        Self {
            role: Role::Assistant,
            content,
            name,
            tool_call_id: None,
        }
    }
}

impl From<ToolMessage> for RequestGenericMessage {
    fn from(
        ToolMessage {
            content,
            tool_call_id,
        }: ToolMessage,
    ) -> Self {
        Self {
            role: Role::Tool,
            content: Content::Text(content),
            name: None,
            tool_call_id: Some(tool_call_id),
        }
    }
}

/// Image part in a multi-part user message.
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct ImagePart {
    /// Image URL or base64-encoded image data in the following format:
    /// `data:{mime_type};base64,{base64_image}`.
    pub url: String,
    /// Image detail level. Typically one of `auto`, `low`, `high`.
    pub detail: Option<String>,
}

/// File part in a multi-part user message.
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct FilePart {
    /// File URL (only supported by OpenRouter) or base64-encoded file data in the following
    /// format: `data:application/pdf;base64,{base64_pdf}`.
    pub file_data: String,
    /// File name to pass to the model.
    pub filename: Option<String>,
}

/// Content part of a multi-part user message.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ContentPart {
    /// Text content part.
    Text(String),
    /// Image content part.
    Image(ImagePart),
    /// File content part.
    File(FilePart),
}

impl Serialize for ContentPart {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            ContentPart::Text(text) => {
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("type", "text")?;
                map.serialize_entry("text", text)?;
                map.end()
            }
            ContentPart::Image(image) => {
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("type", "image_url")?;
                map.serialize_entry("image_url", image)?;
                map.end()
            }
            ContentPart::File(file) => {
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("type", "file")?;
                map.serialize_entry("file", file)?;
                map.end()
            }
        }
    }
}

/// Content of the message. Either a string or array of content parts.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Content {
    /// Text message content.
    Text(String),
    /// Multipart message content.
    ContentParts(Vec<ContentPart>),
}

impl Serialize for Content {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Content::Text(s) => serializer.serialize_str(s),
            Content::ContentParts(parts) => {
                let mut seq = serializer.serialize_seq(Some(parts.len()))?;
                for part in parts {
                    seq.serialize_element(part)?;
                }
                seq.end()
            }
        }
    }
}

/// Intermediate image content part. Used for `Deserialize` implementation only.
#[derive(Debug, Clone, Eq, PartialEq, serde_query::Deserialize)]
pub struct IntermediateImagePart {
    /// Type. Either `image_url` or `file`.
    #[query(".type")]
    ty: String,
    /// Image URL or base64 encoded data.
    #[query(".image_url.url")]
    url: String,
}

impl<'de> Deserialize<'de> for ImagePart {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let part = IntermediateImagePart::deserialize(deserializer)?;

        match part.ty.as_ref() {
            "image_url" => Ok(ImagePart {
                url: part.url,
                detail: None,
            }),
            ty => Err(D::Error::custom(format!("unsupported type `{}`", ty))),
        }
    }
}

/// Error when converting messages
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Missing mandatory field
    #[error("Missing mandatory field `{0}`")]
    MissingField(&'static str),
    /// Invalid role
    #[error("Expected role {0:?}, got {1:?}")]
    RoleMismatch(Role, Role),
}

/// Assistant message that can hold text content only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResponseAssistantMessage {
    /// The contents of the message.
    pub content: Option<String>,
    /// An optional name for the participant. Provides the model information
    /// to differentiate between participants of the same role.
    pub name: Option<String>,
    /// The refusal message by the assistant.
    pub refusal: Option<String>,
    /// The tool calls generated by the model, such as function calls.
    pub tool_calls: Option<Value>,
    /// Reasoning performaed by model.
    pub reasoning: Option<String>,
    /// Generated images.
    pub images: Option<Vec<ImagePart>>,
}

impl TryFrom<ResponseGenericMessage> for ResponseAssistantMessage {
    type Error = Error;

    fn try_from(
        ResponseGenericMessage {
            role,
            content,
            name,
            refusal,
            tool_calls,
            tool_call_id: _,
            reasoning,
            images,
        }: ResponseGenericMessage,
    ) -> Result<Self, Error> {
        if role == Role::Assistant {
            Ok(Self {
                content,
                name,
                refusal,
                tool_calls,
                reasoning,
                images,
            })
        } else {
            Err(Error::RoleMismatch(Role::Assistant, role))
        }
    }
}