openai-ergonomic 0.5.2

Ergonomic Rust wrapper for OpenAI API
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
//! Threads API builders.
//!
//! Provides ergonomic builders for creating assistant threads and messages with
//! attachments and metadata support.

use std::collections::HashMap;

use openai_client_base::models::create_message_request::Role as MessageRole;
use openai_client_base::models::{
    assistant_tools_code, assistant_tools_file_search_type_only, AssistantToolsCode,
    AssistantToolsFileSearchTypeOnly, CreateMessageRequest, CreateMessageRequestAttachmentsInner,
    CreateMessageRequestAttachmentsInnerToolsInner, CreateThreadRequest,
};
use serde_json::Value;

use crate::{Builder, Result};

/// Attachment tools that can be associated with a message file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachmentTool {
    /// Make the attachment available to the code interpreter tool.
    CodeInterpreter,
    /// Make the attachment available to the file search tool.
    FileSearch,
}

impl AttachmentTool {
    fn to_api(self) -> CreateMessageRequestAttachmentsInnerToolsInner {
        match self {
            Self::CodeInterpreter => {
                CreateMessageRequestAttachmentsInnerToolsInner::AssistantToolsCode(Box::new(
                    AssistantToolsCode::new(assistant_tools_code::Type::CodeInterpreter),
                ))
            }
            Self::FileSearch => {
                CreateMessageRequestAttachmentsInnerToolsInner::AssistantToolsFileSearchTypeOnly(
                    Box::new(AssistantToolsFileSearchTypeOnly::new(
                        assistant_tools_file_search_type_only::Type::FileSearch,
                    )),
                )
            }
        }
    }
}

/// Attachment to include with a thread message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageAttachment {
    file_id: String,
    tools: Vec<AttachmentTool>,
}

impl MessageAttachment {
    /// Attach a file for the code interpreter tool.
    #[must_use]
    pub fn for_code_interpreter(file_id: impl Into<String>) -> Self {
        Self {
            file_id: file_id.into(),
            tools: vec![AttachmentTool::CodeInterpreter],
        }
    }

    /// Attach a file for the file search tool.
    #[must_use]
    pub fn for_file_search(file_id: impl Into<String>) -> Self {
        Self {
            file_id: file_id.into(),
            tools: vec![AttachmentTool::FileSearch],
        }
    }

    /// Add an additional tool that should receive this attachment.
    #[must_use]
    pub fn with_tool(mut self, tool: AttachmentTool) -> Self {
        if !self.tools.contains(&tool) {
            self.tools.push(tool);
        }
        self
    }

    fn into_api(self) -> CreateMessageRequestAttachmentsInner {
        let mut inner = CreateMessageRequestAttachmentsInner::new();
        inner.file_id = Some(self.file_id);
        if !self.tools.is_empty() {
            let tools = self.tools.into_iter().map(AttachmentTool::to_api).collect();
            inner.tools = Some(tools);
        }
        inner
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
enum MetadataState {
    #[default]
    Unset,
    Present(HashMap<String, String>),
    ExplicitNull,
}

impl MetadataState {
    fn upsert(&mut self, key: String, value: String) {
        match self {
            MetadataState::Unset | MetadataState::ExplicitNull => {
                let mut map = HashMap::new();
                map.insert(key, value);
                *self = MetadataState::Present(map);
            }
            MetadataState::Present(map) => {
                map.insert(key, value);
            }
        }
    }

    fn replace(&mut self, metadata: HashMap<String, String>) {
        *self = MetadataState::Present(metadata);
    }

    fn clear(&mut self) {
        *self = MetadataState::ExplicitNull;
    }

    #[allow(clippy::option_option)]
    fn into_option(self) -> Option<Option<HashMap<String, String>>> {
        match self {
            MetadataState::Unset => None,
            MetadataState::Present(map) if map.is_empty() => None,
            MetadataState::Present(map) => Some(Some(map)),
            MetadataState::ExplicitNull => Some(None),
        }
    }
}

/// Builder for messages that seed a thread.
#[derive(Debug, Clone, Default)]
pub struct ThreadMessageBuilder {
    role: MessageRole,
    content: String,
    attachments: Vec<MessageAttachment>,
    metadata: MetadataState,
}

impl ThreadMessageBuilder {
    /// Create a user message with the provided text content.
    #[must_use]
    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: MessageRole::User,
            content: content.into(),
            attachments: Vec::new(),
            metadata: MetadataState::Unset,
        }
    }

    /// Create an assistant-authored message.
    #[must_use]
    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: MessageRole::Assistant,
            content: content.into(),
            attachments: Vec::new(),
            metadata: MetadataState::Unset,
        }
    }

    /// Set the message content explicitly.
    #[must_use]
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = content.into();
        self
    }

    /// Attach a file to the message.
    #[must_use]
    pub fn attachment(mut self, attachment: MessageAttachment) -> Self {
        self.attachments.push(attachment);
        self
    }

    /// Attach multiple files to the message.
    #[must_use]
    pub fn attachments<I>(mut self, attachments: I) -> Self
    where
        I: IntoIterator<Item = MessageAttachment>,
    {
        self.attachments.extend(attachments);
        self
    }

    /// Set metadata for the message.
    #[must_use]
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.upsert(key.into(), value.into());
        self
    }

    /// Replace metadata with a full map.
    #[must_use]
    pub fn metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
        self.metadata.replace(metadata);
        self
    }

    /// Remove metadata by sending an explicit null.
    #[must_use]
    pub fn clear_metadata(mut self) -> Self {
        self.metadata.clear();
        self
    }
}

impl Builder<CreateMessageRequest> for ThreadMessageBuilder {
    fn build(self) -> Result<CreateMessageRequest> {
        let mut request = CreateMessageRequest::new(self.role, Value::String(self.content));
        if !self.attachments.is_empty() {
            let attachments = self
                .attachments
                .into_iter()
                .map(MessageAttachment::into_api)
                .collect();
            request.attachments = Some(Some(attachments));
        }
        request.metadata = self.metadata.into_option();
        Ok(request)
    }
}

impl ThreadMessageBuilder {
    /// Build the message, panicking only if serialization fails (not expected).
    #[must_use]
    pub fn finish(self) -> CreateMessageRequest {
        self.build()
            .expect("thread message builder should be infallible")
    }
}

/// Builder for creating a thread with initial messages and metadata.
///
/// # Examples
///
/// ```rust
/// use openai_ergonomic::{Builder};
/// use openai_ergonomic::builders::threads::{
///     MessageAttachment, ThreadMessageBuilder, ThreadRequestBuilder,
/// };
///
/// let thread_request = ThreadRequestBuilder::new()
///     .user_message("Summarise the attached doc")
///     .message_builder(
///         ThreadMessageBuilder::assistant("Sure, I'll reference it.")
///             .attachment(MessageAttachment::for_file_search("file-xyz")),
///     )
///     .unwrap()
///     .build()
///     .unwrap();
///
/// assert!(thread_request.messages.is_some());
/// ```
#[derive(Debug, Clone, Default)]
pub struct ThreadRequestBuilder {
    messages: Vec<CreateMessageRequest>,
    metadata: MetadataState,
}

impl ThreadRequestBuilder {
    /// Create a new empty thread builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Seed the thread with an initial user message.
    #[must_use]
    pub fn user_message(mut self, content: impl Into<String>) -> Self {
        self.messages
            .push(ThreadMessageBuilder::user(content).finish());
        self
    }

    /// Seed the thread with an assistant message.
    #[must_use]
    pub fn assistant_message(mut self, content: impl Into<String>) -> Self {
        self.messages
            .push(ThreadMessageBuilder::assistant(content).finish());
        self
    }

    /// Add a fully configured message request.
    #[must_use]
    pub fn message_request(mut self, message: CreateMessageRequest) -> Self {
        self.messages.push(message);
        self
    }

    /// Add a thread message builder.
    pub fn message_builder(mut self, builder: ThreadMessageBuilder) -> Result<Self> {
        self.messages.push(builder.build()?);
        Ok(self)
    }

    /// Add metadata to the thread.
    #[must_use]
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.upsert(key.into(), value.into());
        self
    }

    /// Replace thread metadata with a full map.
    #[must_use]
    pub fn metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
        self.metadata.replace(metadata);
        self
    }

    /// Remove metadata by sending an explicit null.
    #[must_use]
    pub fn clear_metadata(mut self) -> Self {
        self.metadata.clear();
        self
    }

    /// Access the configured messages.
    #[must_use]
    pub fn messages(&self) -> &[CreateMessageRequest] {
        &self.messages
    }
}

impl Builder<CreateThreadRequest> for ThreadRequestBuilder {
    fn build(self) -> Result<CreateThreadRequest> {
        let mut request = CreateThreadRequest::new();
        if !self.messages.is_empty() {
            request.messages = Some(self.messages);
        }
        request.metadata = self.metadata.into_option();
        Ok(request)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builds_basic_user_message() {
        let builder = ThreadMessageBuilder::user("Hello");
        let message = builder.build().expect("builder should succeed");

        assert_eq!(message.role, MessageRole::User);
        assert_eq!(message.content, Value::String("Hello".to_string()));
        assert!(message.attachments.is_none());
        assert!(message.metadata.is_none());
    }

    #[test]
    fn builds_message_with_attachment() {
        let attachment = MessageAttachment::for_code_interpreter("file-123");
        let message = ThreadMessageBuilder::user("process this")
            .attachment(attachment)
            .build()
            .expect("builder should succeed");

        let attachments = message.attachments.unwrap().unwrap();
        assert_eq!(attachments.len(), 1);
        assert_eq!(attachments[0].file_id.as_deref(), Some("file-123"));
        assert!(attachments[0].tools.as_ref().is_some());
    }

    #[test]
    fn builds_thread_with_metadata() {
        let thread = ThreadRequestBuilder::new()
            .user_message("Hi there")
            .metadata("topic", "support")
            .build()
            .expect("builder should succeed");

        assert!(thread.messages.is_some());
        let metadata = thread.metadata.unwrap().unwrap();
        assert_eq!(metadata.get("topic"), Some(&"support".to_string()));
    }

    #[test]
    fn can_explicitly_clear_metadata() {
        let thread = ThreadRequestBuilder::new()
            .metadata("foo", "bar")
            .clear_metadata()
            .build()
            .expect("builder should succeed");

        assert!(thread.metadata.is_some());
        assert!(thread.metadata.unwrap().is_none());
    }

    #[test]
    fn accepts_custom_message_builder() {
        let message_builder = ThreadMessageBuilder::assistant("Hello").metadata("tone", "friendly");
        let thread = ThreadRequestBuilder::new()
            .message_builder(message_builder)
            .expect("builder should succeed")
            .build()
            .expect("thread build should succeed");

        let message = thread.messages.unwrap();
        assert_eq!(message.len(), 1);
        assert_eq!(message[0].role, MessageRole::Assistant);
        let metadata = message[0].metadata.clone().unwrap().unwrap();
        assert_eq!(metadata.get("tone"), Some(&"friendly".to_string()));
    }
}