Skip to main content

fauna_api/parrot/
chat.rs

1use std::sync::Arc;
2
3use chrono::SecondsFormat;
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value, json};
6
7use super::generative::{Content, File as FilePart, Part, file_ref};
8use super::room::{ChatRoom, RoomHooks, connect_room};
9use super::share::{ChatTarget, OpenRoomOptions, open_room};
10use crate::authentification::CredentialsOrApiKey;
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)]
153#[serde(rename_all = "camelCase")]
154pub struct ChatSummary {
155    pub id: String,
156    pub name: String,
157    pub principal_id: String,
158    /// People only: sends never start a model reply.
159    pub human: bool,
160    /// Only whoever made it can delete it or move it.
161    pub locked: bool,
162    /// The repository Parrot works in, by id.
163    pub repository: Option<u64>,
164    /// Milliseconds since the epoch.
165    pub created: i64,
166    /// Milliseconds since the epoch.
167    pub updated: i64,
168    #[serde(skip_serializing)]
169    pub last: Option<Content>,
170    /// Messages the caller hasn't read. A person and each of their API keys keep
171    /// their own place; one that never marked the chat sees only its newest 20.
172    pub unread: u32,
173}
174
175impl ChatSummary {
176    pub fn from_json(json: &Value) -> ChatSummary {
177        let text = |value: &Value| match value {
178            Value::String(text) => text.clone(),
179            Value::Null => String::new(),
180            value => value.to_string(),
181        };
182        ChatSummary {
183            id: text(&json["id"]),
184            name: text(&json["name"]),
185            principal_id: text(&json["principalId"]),
186            human: json["human"] == true,
187            locked: json["locked"] == true,
188            repository: json["repository"].as_u64().filter(|id| *id > 0),
189            created: json["created"].as_f64().unwrap_or_default() as i64,
190            updated: json["updated"].as_f64().unwrap_or_default() as i64,
191            last: json["last"]
192                .is_object()
193                .then(|| Content::from_json(&json["last"], None)),
194            unread: json["unread"].as_u64().unwrap_or_default() as u32,
195        }
196    }
197}
198
199impl<'de> Deserialize<'de> for ChatSummary {
200    fn deserialize<D: serde::Deserializer<'de>>(
201        deserializer: D,
202    ) -> std::result::Result<Self, D::Error> {
203        Ok(ChatSummary::from_json(&Value::deserialize(deserializer)?))
204    }
205}
206
207pub async fn list_chats(
208    authorization: &CredentialsOrApiKey,
209    group: Option<&Group>,
210) -> Result<Vec<ChatSummary>> {
211    let mut request = client()
212        .get(format!("{}/chat/all", super::get_url()))
213        .header(
214            "Authorization",
215            match authorization {
216                CredentialsOrApiKey::Credentials(credentials) => {
217                    format!("Token {}", credentials.token)
218                }
219                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
220            },
221        );
222    if let Some(group) = group {
223        request = request.header("Group", &group.id);
224    }
225    let response = request.send().await?;
226    let rows: Vec<Value> = ok(response).await?.json().await?;
227    Ok(rows.iter().map(ChatSummary::from_json).collect())
228}
229
230pub async fn rename_chat(
231    authorization: &CredentialsOrApiKey,
232    id: &str,
233    name: &str,
234    group: Option<&Group>,
235) -> Result<()> {
236    let mut request = client()
237        .post(format!("{}/chat/rename", super::get_url()))
238        .header(
239            "Authorization",
240            match authorization {
241                CredentialsOrApiKey::Credentials(credentials) => {
242                    format!("Token {}", credentials.token)
243                }
244                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
245            },
246        );
247    if let Some(group) = group {
248        request = request.header("Group", &group.id);
249    }
250    let response = request
251        .json(&json!({ "id": id, "name": name }))
252        .send()
253        .await?;
254    ok(response).await?;
255    Ok(())
256}
257
258/// Mark a chat read for the caller, up to `position` (the next unread one) or
259/// all of it. Signed in with an API key, the key keeps its own place, apart from
260/// its person. Sending a message reads the chat for its sender. Returns what's
261/// left unread.
262pub async fn mark_read(
263    authorization: &CredentialsOrApiKey,
264    id: &str,
265    position: Option<u32>,
266    group: Option<&Group>,
267) -> Result<u32> {
268    let mut request = client()
269        .post(format!("{}/chat/mark-read", super::get_url()))
270        .header(
271            "Authorization",
272            match authorization {
273                CredentialsOrApiKey::Credentials(credentials) => {
274                    format!("Token {}", credentials.token)
275                }
276                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
277            },
278        );
279    if let Some(group) = group {
280        request = request.header("Group", &group.id);
281    }
282    let response = request
283        .json(&json!({ "id": id, "position": position }))
284        .send()
285        .await?;
286    let json: Value = ok(response).await?.json().await?;
287    Ok(json["unread"].as_u64().unwrap_or_default() as u32)
288}
289
290/// The rest of a draft reply in a chat, from its newest messages and how you write to the
291/// same people in its owner's other chats. Empty when the draft needs nothing more.
292pub async fn autocomplete(
293    authorization: &CredentialsOrApiKey,
294    id: &str,
295    text: &str,
296    group: Option<&Group>,
297) -> Result<String> {
298    let mut request = client()
299        .post(format!("{}/chat/autocomplete", super::get_url()))
300        .header(
301            "Authorization",
302            match authorization {
303                CredentialsOrApiKey::Credentials(credentials) => {
304                    format!("Token {}", credentials.token)
305                }
306                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
307            },
308        );
309    if let Some(group) = group {
310        request = request.header("Group", &group.id);
311    }
312    let response = request
313        .json(&json!({ "id": id, "text": text }))
314        .send()
315        .await?;
316    Ok(ok(response).await?.text().await?)
317}
318
319fn hydrate_file_part(
320    authorization: &CredentialsOrApiKey,
321    part: &Value,
322    group: Option<&Group>,
323) -> Part {
324    let name = part["name"].as_str().unwrap_or("file");
325    let content_type = part["contentType"]
326        .as_str()
327        .unwrap_or("application/octet-stream");
328    let mut meta = part.clone();
329    meta["name"] = Value::from(name);
330    meta["contentType"] = Value::from(content_type);
331    if let Some(access_code) = part["accessCode"].as_str().filter(|code| !code.is_empty()) {
332        return Part::File(FilePart {
333            file: drive::File::from_json(
334                &meta,
335                DriveAuthorization::AccessCode {
336                    authorization: authorization.clone(),
337                    access_code: access_code.to_string(),
338                },
339            ),
340        });
341    }
342    if let Some(path) = part["path"].as_str().filter(|path| !path.is_empty()) {
343        return Part::File(FilePart {
344            file: drive::File::from_json(
345                &meta,
346                DriveAuthorization::Path {
347                    authorization: authorization.clone(),
348                    path: path.to_string(),
349                    group: part["group"]
350                        .as_str()
351                        .map(str::to_string)
352                        .or_else(|| group.map(|group| group.id.clone())),
353                },
354            ),
355        });
356    }
357    Part::File(FilePart {
358        file: drive::from_bytes(
359            authorization.clone(),
360            name,
361            content_type,
362            Vec::new(),
363            FileDates::default(),
364        ),
365    })
366}
367
368/// One page of a chat, newest first.
369pub async fn read_chat(
370    authorization: &CredentialsOrApiKey,
371    id: &str,
372    group: Option<&Group>,
373    query: PageQuery,
374) -> Result<Vec<Content>> {
375    let mut request = client()
376        .post(format!("{}/chat/read", super::get_url()))
377        .header(
378            "Authorization",
379            match authorization {
380                CredentialsOrApiKey::Credentials(credentials) => {
381                    format!("Token {}", credentials.token)
382                }
383                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
384            },
385        );
386    if let Some(group) = group {
387        request = request.header("Group", &group.id);
388    }
389    let response = request
390        .json(&json!({ "id": id, "cursor": query.cursor, "max": query.max }))
391        .send()
392        .await?;
393    let json: Value = ok(response).await?.json().await?;
394
395    let file = |part: &Value| hydrate_file_part(authorization, part, group);
396    let messages = json
397        .as_array()
398        .into_iter()
399        .flatten()
400        .map(|message| Content::from_json(message, Some(&file)))
401        .collect();
402    Ok(messages)
403}
404
405pub async fn write_chat(
406    authorization: &CredentialsOrApiKey,
407    id: &str,
408    messages: &[Content],
409    group: Option<&Group>,
410) -> Result<()> {
411    let mut serialized_messages = Vec::with_capacity(messages.len());
412    for message in messages {
413        let mut serialized_parts = Vec::with_capacity(message.parts.len());
414
415        for part in &message.parts {
416            match part {
417                Part::File(part) if !part.file.online() => {
418                    let file = &part.file;
419                    let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
420                    let bytes = file.clone().download(false, None).await?;
421                    let mut ready = drive::from_bytes(
422                        authorization.clone(),
423                        &dest,
424                        &file.content_type,
425                        bytes,
426                        FileDates::default(),
427                    );
428                    ready.upload(None).await?;
429                    serialized_parts.push(file_ref(&ready));
430                }
431                part => serialized_parts.push(part.wire()),
432            }
433        }
434
435        let mut wire = Map::new();
436        wire.insert("parts".to_string(), Value::Array(serialized_parts));
437        wire.insert("role".to_string(), serde_json::to_value(message.role)?);
438        if let Some(author) = &message.author {
439            wire.insert("author".to_string(), serde_json::to_value(author)?);
440        }
441        if let Some(model) = &message.model {
442            wire.insert("model".to_string(), Value::from(model.as_str()));
443        }
444        wire.insert(
445            "createdAt".to_string(),
446            Value::from(
447                message
448                    .created_at
449                    .to_rfc3339_opts(SecondsFormat::Millis, true),
450            ),
451        );
452        serialized_messages.push(Value::Object(wire));
453    }
454
455    let mut request = client()
456        .post(format!("{}/chat/write", super::get_url()))
457        .header(
458            "Authorization",
459            match authorization {
460                CredentialsOrApiKey::Credentials(credentials) => {
461                    format!("Token {}", credentials.token)
462                }
463                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
464            },
465        );
466    if let Some(group) = group {
467        request = request.header("Group", &group.id);
468    }
469    let response = request
470        .json(&json!({ "id": id, "messages": serialized_messages }))
471        .send()
472        .await?;
473    ok(response).await?;
474    Ok(())
475}