Skip to main content

fauna_api/parrot/
chat.rs

1use std::sync::Arc;
2
3use chrono::{DateTime, SecondsFormat, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value, json};
6
7use super::generative::{Content, File as FilePart, Part, Role, file_ref};
8use super::room::{ChatRoom, RoomHooks, connect_room};
9use super::share::{ChatTarget, OpenRoomOptions, open_room};
10use crate::authentification::{CredentialsOrApiKey, Profile};
11use crate::billing::PageQuery;
12use crate::drive::{self, DriveAuthorization, FileDates};
13use crate::error::Result;
14use crate::groups::Group;
15use crate::http::{client, ok};
16use crate::shared::server::Presence;
17use crate::termite::versioning::Repository;
18
19/// The `options` argument of `open_chat`.
20#[derive(Default)]
21pub struct OpenChatOptions {
22    pub chat_id: Option<String>,
23    pub messages: Option<Vec<Content>>,
24    pub share: Option<bool>,
25    pub hooks: Option<Arc<dyn RoomHooks>>,
26}
27
28/// What `open_chat` resolves to: `{ room, self, reference, code? }` in the
29/// TypeScript SDK, with `self` as `me`.
30#[derive(Clone)]
31pub struct OpenedChat {
32    pub room: ChatRoom,
33    pub me: Presence,
34    pub reference: String,
35    pub code: Option<String>,
36}
37
38/// Open a chat as a live room: host it server-side, seed the newest window from
39/// durable, then connect. Pass a durable `chat_id` to bind the room
40/// (`parrot:chat:{chatId}`, persisted + billed to the chat's balance-holder);
41/// omit it for an unbound ephemeral room. `share: true` also mints an access code
42/// others can redeem. Every chat, solo or group, opens through this single
43/// always-host path. Returns the connected `ChatRoom`, the caller's `Presence`,
44/// the room `reference`, and the access `code` when shared.
45pub async fn open_chat(
46    authorization: &CredentialsOrApiKey,
47    options: OpenChatOptions,
48) -> Result<OpenedChat> {
49    let opened = open_room(
50        authorization,
51        OpenRoomOptions {
52            chat_id: options.chat_id,
53            messages: options.messages,
54            share: options.share,
55            write: None,
56        },
57    )
58    .await?;
59    let target = match &opened.code {
60        Some(code) if !code.is_empty() => ChatTarget::Code { code: code.clone() },
61        _ => ChatTarget::Reference {
62            reference: opened.reference.clone(),
63        },
64    };
65    let (room, me) = connect_room(authorization, &target, options.hooks).await?;
66    Ok(OpenedChat {
67        room,
68        me,
69        reference: opened.reference,
70        code: opened.code,
71    })
72}
73
74/// The `options` argument of `create_chat`.
75#[derive(Debug, Clone, Default)]
76pub struct CreateChatOptions {
77    /// People only for good: sends never start a model reply.
78    pub human: Option<bool>,
79    /// Instructs every model reply in the chat.
80    pub system_prompt: Option<String>,
81    /// Only you can delete it or move it to another group; it still goes away
82    /// with its group.
83    pub locked: Option<bool>,
84    /// The Termite repository Parrot works in during replies: yours for a
85    /// personal chat, the group's for a group chat.
86    pub repository: Option<Repository>,
87}
88
89/// Create a chat, owned by the caller or by `group`. `human` makes it a people
90/// only chat for good: sends never start a model reply. `system_prompt`
91/// instructs every model reply in the chat. `locked` lets only you delete it or
92/// move it to another group. `repository` is a Termite repository Parrot works
93/// in during replies. `name` defaults to `New Chat`.
94pub async fn create_chat(
95    authorization: &CredentialsOrApiKey,
96    name: Option<&str>,
97    group: Option<&Group>,
98    options: CreateChatOptions,
99) -> Result<String> {
100    let mut request = client()
101        .post(format!("{}/chat/create", super::get_url()))
102        .header(
103            "Authorization",
104            match authorization {
105                CredentialsOrApiKey::Credentials(credentials) => {
106                    format!("Token {}", credentials.token)
107                }
108                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
109            },
110        );
111    if let Some(group) = group {
112        request = request.header("Group", &group.id);
113    }
114    let response = request
115        .json(&json!({
116            "name": name.unwrap_or("New Chat"),
117            "human": options.human == Some(true),
118            "systemPrompt": options.system_prompt,
119            "locked": options.locked == Some(true),
120            "repository": options.repository.as_ref().map(|repository| repository.id),
121        }))
122        .send()
123        .await?;
124    let json: serde_json::Value = ok(response).await?.json().await?;
125    Ok(json["id"].as_str().unwrap_or_default().to_string())
126}
127
128pub async fn delete_chat(
129    authorization: &CredentialsOrApiKey,
130    id: &str,
131    group: Option<&Group>,
132) -> Result<()> {
133    let mut request = client()
134        .post(format!("{}/chat/delete", super::get_url()))
135        .header(
136            "Authorization",
137            match authorization {
138                CredentialsOrApiKey::Credentials(credentials) => {
139                    format!("Token {}", credentials.token)
140                }
141                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
142            },
143        );
144    if let Some(group) = group {
145        request = request.header("Group", &group.id);
146    }
147    let response = request.json(&json!({ "id": id })).send().await?;
148    ok(response).await?;
149    Ok(())
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase")]
154pub struct LastMessage {
155    #[serde(default)]
156    pub parts: Vec<serde_json::Value>,
157    pub role: String,
158    pub created_at: DateTime<Utc>,
159    pub position: u32,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub author: Option<Profile>,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub model: Option<String>,
164}
165
166impl LastMessage {
167    pub fn from_json(json: &Value) -> Option<LastMessage> {
168        if !json.is_object() {
169            return None;
170        }
171        let created_at = crate::tickets::parse_date(&json["createdAt"])?;
172        let position = json["position"].as_f64()?;
173        Some(LastMessage {
174            parts: json["parts"].as_array().cloned().unwrap_or_default(),
175            role: match &json["role"] {
176                Value::Null => String::new(),
177                Value::String(role) => role.clone(),
178                role => role.to_string(),
179            },
180            created_at,
181            position: position as u32,
182            author: Profile::from_json(&json["author"]),
183            model: json["model"]
184                .as_str()
185                .filter(|model| !model.is_empty())
186                .map(str::to_string),
187        })
188    }
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
192#[serde(rename_all = "camelCase")]
193pub struct ChatSummary {
194    pub id: String,
195    pub name: String,
196    pub principal_id: String,
197    /// People only: sends never start a model reply.
198    #[serde(default)]
199    pub human: bool,
200    /// Only whoever made it can delete it or move it.
201    #[serde(default)]
202    pub locked: bool,
203    /// The repository Parrot works in, by id.
204    #[serde(default)]
205    pub repository: Option<u64>,
206    /// Milliseconds since the epoch.
207    pub created: i64,
208    /// Milliseconds since the epoch.
209    pub updated: i64,
210    #[serde(default)]
211    pub last: Option<LastMessage>,
212    /// Messages the caller hasn't read. A person and each of their API keys keep
213    /// their own place; one that never marked the chat sees only its newest 20.
214    #[serde(default)]
215    pub unread: u32,
216}
217
218pub async fn list_chats(
219    authorization: &CredentialsOrApiKey,
220    group: Option<&Group>,
221) -> Result<Vec<ChatSummary>> {
222    let mut request = client()
223        .get(format!("{}/chat/all", super::get_url()))
224        .header(
225            "Authorization",
226            match authorization {
227                CredentialsOrApiKey::Credentials(credentials) => {
228                    format!("Token {}", credentials.token)
229                }
230                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
231            },
232        );
233    if let Some(group) = group {
234        request = request.header("Group", &group.id);
235    }
236    let response = request.send().await?;
237    let rows: Vec<Value> = ok(response).await?.json().await?;
238    rows.into_iter()
239        .map(|mut row| {
240            let last = LastMessage::from_json(&row["last"]);
241            row["last"] = Value::Null;
242            let mut summary: ChatSummary = serde_json::from_value(row)?;
243            summary.last = last;
244            Ok(summary)
245        })
246        .collect()
247}
248
249pub async fn rename_chat(
250    authorization: &CredentialsOrApiKey,
251    id: &str,
252    name: &str,
253    group: Option<&Group>,
254) -> Result<()> {
255    let mut request = client()
256        .post(format!("{}/chat/rename", super::get_url()))
257        .header(
258            "Authorization",
259            match authorization {
260                CredentialsOrApiKey::Credentials(credentials) => {
261                    format!("Token {}", credentials.token)
262                }
263                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
264            },
265        );
266    if let Some(group) = group {
267        request = request.header("Group", &group.id);
268    }
269    let response = request
270        .json(&json!({ "id": id, "name": name }))
271        .send()
272        .await?;
273    ok(response).await?;
274    Ok(())
275}
276
277/// Mark a chat read for the caller, up to `position` (the next unread one) or
278/// all of it. Signed in with an API key, the key keeps its own place, apart from
279/// its person. Sending a message reads the chat for its sender. Returns what's
280/// left unread.
281pub async fn mark_read(
282    authorization: &CredentialsOrApiKey,
283    id: &str,
284    position: Option<u32>,
285    group: Option<&Group>,
286) -> Result<u32> {
287    let mut request = client()
288        .post(format!("{}/chat/mark-read", super::get_url()))
289        .header(
290            "Authorization",
291            match authorization {
292                CredentialsOrApiKey::Credentials(credentials) => {
293                    format!("Token {}", credentials.token)
294                }
295                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
296            },
297        );
298    if let Some(group) = group {
299        request = request.header("Group", &group.id);
300    }
301    let response = request
302        .json(&json!({ "id": id, "position": position }))
303        .send()
304        .await?;
305    let json: Value = ok(response).await?.json().await?;
306    Ok(json["unread"].as_u64().unwrap_or_default() as u32)
307}
308
309fn hydrate_file_part(
310    authorization: &CredentialsOrApiKey,
311    part: &Value,
312    group: Option<&Group>,
313) -> Part {
314    let name = part["name"].as_str().unwrap_or("file");
315    let content_type = part["contentType"]
316        .as_str()
317        .unwrap_or("application/octet-stream");
318    let mut meta = part.clone();
319    meta["name"] = Value::from(name);
320    meta["contentType"] = Value::from(content_type);
321    if let Some(access_code) = part["accessCode"].as_str().filter(|code| !code.is_empty()) {
322        return Part::File(FilePart {
323            file: drive::File::from_json(
324                &meta,
325                DriveAuthorization::AccessCode {
326                    authorization: authorization.clone(),
327                    access_code: access_code.to_string(),
328                },
329            ),
330        });
331    }
332    if let Some(path) = part["path"].as_str().filter(|path| !path.is_empty()) {
333        return Part::File(FilePart {
334            file: drive::File::from_json(
335                &meta,
336                DriveAuthorization::Path {
337                    authorization: authorization.clone(),
338                    path: path.to_string(),
339                    group: part["group"]
340                        .as_str()
341                        .map(str::to_string)
342                        .or_else(|| group.map(|group| group.id.clone())),
343                },
344            ),
345        });
346    }
347    Part::File(FilePart {
348        file: drive::from_bytes(
349            authorization.clone(),
350            name,
351            content_type,
352            Vec::new(),
353            FileDates::default(),
354        ),
355    })
356}
357
358/// One page of a chat, newest first.
359pub async fn read_chat(
360    authorization: &CredentialsOrApiKey,
361    id: &str,
362    group: Option<&Group>,
363    query: PageQuery,
364) -> Result<Vec<Content>> {
365    let mut request = client()
366        .post(format!("{}/chat/read", super::get_url()))
367        .header(
368            "Authorization",
369            match authorization {
370                CredentialsOrApiKey::Credentials(credentials) => {
371                    format!("Token {}", credentials.token)
372                }
373                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
374            },
375        );
376    if let Some(group) = group {
377        request = request.header("Group", &group.id);
378    }
379    let response = request
380        .json(&json!({ "id": id, "cursor": query.cursor, "max": query.max }))
381        .send()
382        .await?;
383    let json: Value = ok(response).await?.json().await?;
384
385    let mut messages = Vec::new();
386    for message in json.as_array().into_iter().flatten() {
387        let parts = message["parts"]
388            .as_array()
389            .into_iter()
390            .flatten()
391            .filter_map(|part| {
392                if part["type"] == "FILE" {
393                    Some(hydrate_file_part(authorization, part, group))
394                } else {
395                    Part::from_json(part)
396                }
397            })
398            .collect();
399        messages.push(Content {
400            parts,
401            role: serde_json::from_value(message["role"].clone()).unwrap_or(Role::User),
402            author: Profile::from_json(&message["author"]),
403            model: message["model"].as_str().map(str::to_string),
404            created_at: crate::tickets::parse_date(&message["createdAt"]).unwrap_or_default(),
405            via: match &message["via"] {
406                Value::Null => None,
407                Value::String(via) if via.is_empty() => None,
408                Value::String(via) => Some(via.clone()),
409                via => Some(via.to_string()),
410            },
411        });
412    }
413
414    Ok(messages)
415}
416
417pub async fn write_chat(
418    authorization: &CredentialsOrApiKey,
419    id: &str,
420    messages: &[Content],
421    group: Option<&Group>,
422) -> Result<()> {
423    let mut serialized_messages = Vec::with_capacity(messages.len());
424    for message in messages {
425        let mut serialized_parts = Vec::with_capacity(message.parts.len());
426
427        for part in &message.parts {
428            match part {
429                Part::File(part) if !part.file.online() => {
430                    let file = &part.file;
431                    let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
432                    let bytes = file.clone().download(false, None).await?;
433                    let mut ready = drive::from_bytes(
434                        authorization.clone(),
435                        &dest,
436                        &file.content_type,
437                        bytes,
438                        FileDates::default(),
439                    );
440                    ready.upload(None).await?;
441                    serialized_parts.push(file_ref(&ready));
442                }
443                part => serialized_parts.push(part.wire()),
444            }
445        }
446
447        let mut wire = Map::new();
448        wire.insert("parts".to_string(), Value::Array(serialized_parts));
449        wire.insert("role".to_string(), serde_json::to_value(message.role)?);
450        if let Some(author) = &message.author {
451            wire.insert("author".to_string(), serde_json::to_value(author)?);
452        }
453        if let Some(model) = &message.model {
454            wire.insert("model".to_string(), Value::from(model.as_str()));
455        }
456        wire.insert(
457            "createdAt".to_string(),
458            Value::from(
459                message
460                    .created_at
461                    .to_rfc3339_opts(SecondsFormat::Millis, true),
462            ),
463        );
464        serialized_messages.push(Value::Object(wire));
465    }
466
467    let mut request = client()
468        .post(format!("{}/chat/write", super::get_url()))
469        .header(
470            "Authorization",
471            match authorization {
472                CredentialsOrApiKey::Credentials(credentials) => {
473                    format!("Token {}", credentials.token)
474                }
475                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
476            },
477        );
478    if let Some(group) = group {
479        request = request.header("Group", &group.id);
480    }
481    let response = request
482        .json(&json!({ "id": id, "messages": serialized_messages }))
483        .send()
484        .await?;
485    ok(response).await?;
486    Ok(())
487}