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
use crate::ApiError;
use crate::error::ApiResult;
use crate::models::PaginatedResponse;
use crate::models::chat::{
ChatCollection, ChatDetail, CreateChatRequest, CreateMessageRequest, MessageResponse,
RetryResponse, UpdateChatRequest,
};
use bon::bon;
use reqwest::Method;
use std::collections::HashMap;
use uuid::Uuid;
use super::SureClient;
const MAX_PER_PAGE: u32 = 100;
#[bon]
impl SureClient {
/// List chats
///
/// Retrieves a paginated list of chats.
///
/// # Arguments
/// * `page` - Page number (default: 1)
/// * `per_page` - Items per page (default: 25, max: 100)
///
/// # Returns
/// A paginated response containing chats and pagination metadata.
///
/// # Errors
/// Returns `ApiError::Forbidden` if AI features are disabled.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// // Use defaults (page 1, per_page 25)
/// let response = client.get_chats().call().await?;
///
/// for chat in response.items.chats {
/// println!("Chat: {} ({} messages)", chat.title, chat.message_count);
/// }
///
/// // Or customize parameters using the builder
/// let response = client.get_chats().page(2).per_page(50).call().await?;
/// # Ok(())
/// # }
/// ```
#[builder]
pub async fn get_chats(
&self,
#[builder(default = 1)] page: u32,
#[builder(default = 25)] per_page: u32,
) -> ApiResult<PaginatedResponse<ChatCollection>> {
if per_page > MAX_PER_PAGE {
return Err(ApiError::InvalidParameter(format!(
"per_page cannot exceed {MAX_PER_PAGE}",
)));
}
let mut query_params = HashMap::new();
query_params.insert("page", page.to_string());
query_params.insert("per_page", per_page.to_string());
self.execute_request(Method::GET, "/api/v1/chats", Some(&query_params), None)
.await
}
/// Create a new chat
///
/// Creates a new chat with an optional initial message.
///
/// # Arguments
/// * `title` - Chat title (required)
/// * `message` - Optional initial message
/// * `model` - Optional OpenAI model identifier
///
/// # Returns
/// Detailed information about the created chat.
///
/// # Errors
/// Returns `ApiError::ValidationError` if validation fails.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat = client.create_chat()
/// .title("Monthly budget review".to_string())
/// .message("Help me analyze my spending".to_string())
/// .call()
/// .await?;
///
/// println!("Created chat: {}", chat.title);
/// # Ok(())
/// # }
/// ```
///
#[builder]
pub async fn create_chat(
&self,
title: String,
message: Option<String>,
model: Option<String>,
) -> ApiResult<ChatDetail> {
let request = CreateChatRequest {
title,
message,
model,
};
self.execute_request(
Method::POST,
"/api/v1/chats",
None,
Some(serde_json::to_string(&request)?),
)
.await
}
/// Get a specific chat
///
/// Retrieves detailed information about a chat including its messages.
///
/// # Arguments
/// * `id` - The chat ID to retrieve
///
/// # Returns
/// Detailed chat information including messages.
///
/// # Errors
/// Returns `ApiError::NotFound` if the chat doesn't exist.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
/// use uuid::Uuid;
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
/// let chat = client.get_chat(&chat_id).await?;
///
/// println!("Chat: {} with {} messages", chat.title, chat.messages.len());
/// # Ok(())
/// # }
/// ```
///
pub async fn get_chat(&self, id: &Uuid) -> ApiResult<ChatDetail> {
self.execute_request(Method::GET, &format!("/api/v1/chats/{}", id), None, None)
.await
}
/// Update a chat
///
/// Updates the title of an existing chat.
///
/// # Arguments
/// * `id` - The chat ID to update
/// * `title` - Updated chat title
///
/// # Returns
/// Updated chat information.
///
/// # Errors
/// Returns `ApiError::NotFound` if the chat doesn't exist.
/// Returns `ApiError::ValidationError` if validation fails.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
/// use uuid::Uuid;
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
///
/// let chat = client.update_chat()
/// .id(&chat_id)
/// .title("Updated chat title".to_string())
/// .call()
/// .await?;
///
/// println!("Updated chat: {}", chat.title);
/// # Ok(())
/// # }
/// ```
///
#[builder]
pub async fn update_chat(&self, id: &Uuid, title: String) -> ApiResult<ChatDetail> {
let request = UpdateChatRequest { title };
self.execute_request(
Method::PATCH,
&format!("/api/v1/chats/{}", id),
None,
Some(serde_json::to_string(&request)?),
)
.await
}
/// Delete a chat
///
/// Permanently deletes a chat and all its messages.
///
/// # Arguments
/// * `id` - The chat ID to delete
///
/// # Returns
/// Unit type on successful deletion.
///
/// # Errors
/// Returns `ApiError::NotFound` if the chat doesn't exist.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
/// use uuid::Uuid;
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
/// client.delete_chat(&chat_id).await?;
/// println!("Chat deleted");
/// # Ok(())
/// # }
/// ```
///
pub async fn delete_chat(&self, id: &Uuid) -> ApiResult<()> {
self.execute_request::<serde_json::Value>(
Method::DELETE,
&format!("/api/v1/chats/{}", id),
None,
None,
)
.await?;
Ok(())
}
/// Create a message in a chat
///
/// Sends a new message to a chat and triggers an AI response.
///
/// # Arguments
/// * `chat_id` - The chat ID to send the message to
/// * `content` - Message content
/// * `model` - Optional model identifier
///
/// # Returns
/// The created message with response status.
///
/// # Errors
/// Returns `ApiError::NotFound` if the chat doesn't exist.
/// Returns `ApiError::ValidationError` if validation fails.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
/// use uuid::Uuid;
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
///
/// let message = client.create_message()
/// .chat_id(&chat_id)
/// .content("What were my expenses last month?".to_string())
/// .call()
/// .await?;
///
/// println!("Message sent: {}", message.content);
/// # Ok(())
/// # }
/// ```
///
#[builder]
pub async fn create_message(
&self,
chat_id: &Uuid,
content: String,
model: Option<String>,
) -> ApiResult<MessageResponse> {
let request = CreateMessageRequest { content, model };
self.execute_request(
Method::POST,
&format!("/api/v1/chats/{}/messages", chat_id),
None,
Some(serde_json::to_string(&request)?),
)
.await
}
/// Retry the last assistant response
///
/// Retries generating the last assistant message in a chat.
///
/// # Arguments
/// * `chat_id` - The chat ID to retry the response for
///
/// # Returns
/// Retry response with the new message ID.
///
/// # Errors
/// Returns `ApiError::NotFound` if the chat doesn't exist.
/// Returns `ApiError::ValidationError` if no assistant message is available to retry.
/// Returns `ApiError::Unauthorized` if the API key is invalid.
/// Returns `ApiError::Network` if the request fails due to network issues.
///
/// # Example
/// ```no_run
/// use sure_client_rs::{SureClient, BearerToken};
/// use uuid::Uuid;
///
/// # async fn example(client: SureClient) -> Result<(), Box<dyn std::error::Error>> {
/// let chat_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
/// let response = client.retry_message(&chat_id).await?;
/// println!("Retry started: {}", response.message);
/// # Ok(())
/// # }
/// ```
///
pub async fn retry_message(&self, chat_id: &Uuid) -> ApiResult<RetryResponse> {
self.execute_request(
Method::POST,
&format!("/api/v1/chats/{}/messages/retry", chat_id),
None,
None,
)
.await
}
}