Skip to main content

fauna_api/parrot/
chat.rs

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