Skip to main content

fauna_api/parrot/
chat.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::authentification::{CredentialsOrApiKey, Profile};
6use crate::error::Result;
7use crate::groups::Group;
8use crate::http::{client, ok};
9
10/// The `options` argument of `create_chat`.
11#[derive(Debug, Clone, Default)]
12pub struct CreateChatOptions {
13    /// People only for good: sends never start a model reply.
14    pub human: Option<bool>,
15    /// Instructs every model reply in the chat.
16    pub system_prompt: Option<String>,
17    /// Only you can delete it or move it to another group; it still goes away
18    /// with its group.
19    pub locked: Option<bool>,
20    /// The Termite repository Parrot works in during replies, by id: yours for
21    /// a personal chat, the group's for a group chat.
22    pub repository: Option<u64>,
23}
24
25/// Create a chat, owned by the caller or by `group`. `human` makes it a people
26/// only chat for good: sends never start a model reply. `system_prompt`
27/// instructs every model reply in the chat. `locked` lets only you delete it or
28/// move it to another group. `repository` is a Termite repository Parrot works
29/// in during replies. `name` defaults to `New Chat`.
30pub async fn create_chat(
31    authorization: &CredentialsOrApiKey,
32    name: Option<&str>,
33    group: Option<&Group>,
34    options: CreateChatOptions,
35) -> Result<String> {
36    let mut request = client()
37        .post(format!("{}/chat/create", super::get_url()))
38        .header(
39            "Authorization",
40            match authorization {
41                CredentialsOrApiKey::Credentials(credentials) => {
42                    format!("Token {}", credentials.token)
43                }
44                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
45            },
46        );
47    if let Some(group) = group {
48        request = request.header("Group", &group.id);
49    }
50    let response = request
51        .json(&json!({
52            "name": name.unwrap_or("New Chat"),
53            "human": options.human == Some(true),
54            "systemPrompt": options.system_prompt,
55            "locked": options.locked == Some(true),
56            "repository": options.repository,
57        }))
58        .send()
59        .await?;
60    let json: serde_json::Value = ok(response).await?.json().await?;
61    Ok(json["id"].as_str().unwrap_or_default().to_string())
62}
63
64pub async fn delete_chat(
65    authorization: &CredentialsOrApiKey,
66    id: &str,
67    group: Option<&Group>,
68) -> Result<()> {
69    let mut request = client()
70        .post(format!("{}/chat/delete", super::get_url()))
71        .header(
72            "Authorization",
73            match authorization {
74                CredentialsOrApiKey::Credentials(credentials) => {
75                    format!("Token {}", credentials.token)
76                }
77                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
78            },
79        );
80    if let Some(group) = group {
81        request = request.header("Group", &group.id);
82    }
83    let response = request.json(&json!({ "id": id })).send().await?;
84    ok(response).await?;
85    Ok(())
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct LastMessage {
91    #[serde(default)]
92    pub parts: Vec<serde_json::Value>,
93    pub role: String,
94    pub created_at: DateTime<Utc>,
95    pub position: u32,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub author: Option<Profile>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub model: Option<String>,
100}
101
102impl LastMessage {
103    pub fn from_json(json: &Value) -> Option<LastMessage> {
104        if !json.is_object() {
105            return None;
106        }
107        let created_at = crate::tickets::parse_date(&json["createdAt"])?;
108        let position = json["position"].as_f64()?;
109        Some(LastMessage {
110            parts: json["parts"].as_array().cloned().unwrap_or_default(),
111            role: match &json["role"] {
112                Value::Null => String::new(),
113                Value::String(role) => role.clone(),
114                role => role.to_string(),
115            },
116            created_at,
117            position: position as u32,
118            author: Profile::from_json(&json["author"]),
119            model: json["model"]
120                .as_str()
121                .filter(|model| !model.is_empty())
122                .map(str::to_string),
123        })
124    }
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub struct ChatSummary {
130    pub id: String,
131    pub name: String,
132    pub principal_id: String,
133    /// People only: sends never start a model reply.
134    #[serde(default)]
135    pub human: bool,
136    /// Only whoever made it can delete it or move it.
137    #[serde(default)]
138    pub locked: bool,
139    /// The repository Parrot works in, by id.
140    #[serde(default)]
141    pub repository: Option<u64>,
142    /// Milliseconds since the epoch.
143    pub created: i64,
144    /// Milliseconds since the epoch.
145    pub updated: i64,
146    #[serde(default)]
147    pub last: Option<LastMessage>,
148    /// Messages the caller hasn't read. A person and each of their API keys keep
149    /// their own place; one that never marked the chat sees only its newest 20.
150    #[serde(default)]
151    pub unread: u32,
152}
153
154pub async fn list_chats(
155    authorization: &CredentialsOrApiKey,
156    group: Option<&Group>,
157) -> Result<Vec<ChatSummary>> {
158    let mut request = client()
159        .get(format!("{}/chat/all", super::get_url()))
160        .header(
161            "Authorization",
162            match authorization {
163                CredentialsOrApiKey::Credentials(credentials) => {
164                    format!("Token {}", credentials.token)
165                }
166                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
167            },
168        );
169    if let Some(group) = group {
170        request = request.header("Group", &group.id);
171    }
172    let response = request.send().await?;
173    let rows: Vec<Value> = ok(response).await?.json().await?;
174    rows.into_iter()
175        .map(|mut row| {
176            let last = LastMessage::from_json(&row["last"]);
177            row["last"] = Value::Null;
178            let mut summary: ChatSummary = serde_json::from_value(row)?;
179            summary.last = last;
180            Ok(summary)
181        })
182        .collect()
183}
184
185pub async fn rename_chat(
186    authorization: &CredentialsOrApiKey,
187    id: &str,
188    name: &str,
189    group: Option<&Group>,
190) -> Result<()> {
191    let mut request = client()
192        .post(format!("{}/chat/rename", super::get_url()))
193        .header(
194            "Authorization",
195            match authorization {
196                CredentialsOrApiKey::Credentials(credentials) => {
197                    format!("Token {}", credentials.token)
198                }
199                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
200            },
201        );
202    if let Some(group) = group {
203        request = request.header("Group", &group.id);
204    }
205    let response = request
206        .json(&json!({ "id": id, "name": name }))
207        .send()
208        .await?;
209    ok(response).await?;
210    Ok(())
211}
212
213/// Mark a chat read for the caller, up to `position` (the next unread one) or
214/// all of it. Signed in with an API key, the key keeps its own place, apart from
215/// its person. Sending a message reads the chat for its sender. Returns what's
216/// left unread.
217pub async fn mark_read(
218    authorization: &CredentialsOrApiKey,
219    id: &str,
220    position: Option<u32>,
221    group: Option<&Group>,
222) -> Result<u32> {
223    let mut request = client()
224        .post(format!("{}/chat/mark-read", super::get_url()))
225        .header(
226            "Authorization",
227            match authorization {
228                CredentialsOrApiKey::Credentials(credentials) => {
229                    format!("Token {}", credentials.token)
230                }
231                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
232            },
233        );
234    if let Some(group) = group {
235        request = request.header("Group", &group.id);
236    }
237    let response = request
238        .json(&json!({ "id": id, "position": position }))
239        .send()
240        .await?;
241    let json: Value = ok(response).await?.json().await?;
242    Ok(json["unread"].as_u64().unwrap_or_default() as u32)
243}