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