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