use std::sync::Arc;
use chrono::SecondsFormat;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::generative::{Content, File as FilePart, Part, file_ref};
use super::room::{ChatRoom, RoomHooks, connect_room};
use super::share::{ChatTarget, OpenRoomOptions, open_room};
use crate::authentification::CredentialsOrApiKey;
use crate::billing::PageQuery;
use crate::drive::{self, DriveAuthorization, FileDates};
use crate::error::Result;
use crate::groups::Group;
use crate::http::{client, ok};
use crate::shared::server::Presence;
use crate::termite::versioning::Repository;
#[derive(Default)]
pub struct OpenChatOptions {
pub chat_id: Option<String>,
pub messages: Option<Vec<Content>>,
pub share: Option<bool>,
pub hooks: Option<Arc<dyn RoomHooks>>,
}
#[derive(Clone)]
pub struct OpenedChat {
pub room: ChatRoom,
pub me: Presence,
pub reference: String,
pub code: Option<String>,
}
pub async fn open_chat(
authorization: &CredentialsOrApiKey,
options: OpenChatOptions,
) -> Result<OpenedChat> {
let opened = open_room(
authorization,
OpenRoomOptions {
chat_id: options.chat_id,
messages: options.messages,
share: options.share,
write: None,
},
)
.await?;
let target = match &opened.code {
Some(code) if !code.is_empty() => ChatTarget::Code { code: code.clone() },
_ => ChatTarget::Reference {
reference: opened.reference.clone(),
},
};
let (room, me) = connect_room(authorization, &target, options.hooks).await?;
Ok(OpenedChat {
room,
me,
reference: opened.reference,
code: opened.code,
})
}
#[derive(Debug, Clone, Default)]
pub struct CreateChatOptions {
pub human: Option<bool>,
pub system_prompt: Option<String>,
pub locked: Option<bool>,
pub repository: Option<Repository>,
}
pub async fn create_chat(
authorization: &CredentialsOrApiKey,
name: Option<&str>,
group: Option<&Group>,
options: CreateChatOptions,
) -> Result<String> {
let mut request = client()
.post(format!("{}/chat/create", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({
"name": name.unwrap_or("New Chat"),
"human": options.human == Some(true),
"systemPrompt": options.system_prompt,
"locked": options.locked == Some(true),
"repository": options.repository.as_ref().map(|repository| repository.id),
}))
.send()
.await?;
let json: serde_json::Value = ok(response).await?.json().await?;
Ok(json["id"].as_str().unwrap_or_default().to_string())
}
pub async fn delete_chat(
authorization: &CredentialsOrApiKey,
id: &str,
group: Option<&Group>,
) -> Result<()> {
let mut request = client()
.post(format!("{}/chat/delete", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request.json(&json!({ "id": id })).send().await?;
ok(response).await?;
Ok(())
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSummary {
pub id: String,
pub name: String,
pub principal_id: String,
pub human: bool,
pub locked: bool,
pub repository: Option<u64>,
pub created: i64,
pub updated: i64,
#[serde(skip_serializing)]
pub last: Option<Content>,
pub unread: u32,
}
impl ChatSummary {
pub fn from_json(json: &Value) -> ChatSummary {
let text = |value: &Value| match value {
Value::String(text) => text.clone(),
Value::Null => String::new(),
value => value.to_string(),
};
ChatSummary {
id: text(&json["id"]),
name: text(&json["name"]),
principal_id: text(&json["principalId"]),
human: json["human"] == true,
locked: json["locked"] == true,
repository: json["repository"].as_u64().filter(|id| *id > 0),
created: json["created"].as_f64().unwrap_or_default() as i64,
updated: json["updated"].as_f64().unwrap_or_default() as i64,
last: json["last"]
.is_object()
.then(|| Content::from_json(&json["last"], None)),
unread: json["unread"].as_u64().unwrap_or_default() as u32,
}
}
}
impl<'de> Deserialize<'de> for ChatSummary {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
Ok(ChatSummary::from_json(&Value::deserialize(deserializer)?))
}
}
pub async fn list_chats(
authorization: &CredentialsOrApiKey,
group: Option<&Group>,
) -> Result<Vec<ChatSummary>> {
let mut request = client()
.get(format!("{}/chat/all", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request.send().await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(ChatSummary::from_json).collect())
}
pub async fn rename_chat(
authorization: &CredentialsOrApiKey,
id: &str,
name: &str,
group: Option<&Group>,
) -> Result<()> {
let mut request = client()
.post(format!("{}/chat/rename", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({ "id": id, "name": name }))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn mark_read(
authorization: &CredentialsOrApiKey,
id: &str,
position: Option<u32>,
group: Option<&Group>,
) -> Result<u32> {
let mut request = client()
.post(format!("{}/chat/mark-read", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({ "id": id, "position": position }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(json["unread"].as_u64().unwrap_or_default() as u32)
}
pub async fn autocomplete(
authorization: &CredentialsOrApiKey,
id: &str,
text: &str,
group: Option<&Group>,
on_text: Option<impl Fn(&str)>,
) -> Result<String> {
let mut request = client()
.post(format!("{}/chat/autocomplete", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({ "id": id, "text": text }))
.send()
.await?;
let response = ok(response).await?;
let mut pending = Vec::new();
let mut rest = String::new();
let mut body = response.bytes_stream();
while let Some(chunk) = body.next().await {
pending.extend_from_slice(&chunk?);
while let Some(end) = pending.windows(2).position(|pair| pair == b"\n\n") {
let event: Vec<u8> = pending.drain(..end + 2).collect();
for line in String::from_utf8_lossy(&event[..end]).lines() {
if let Some(data) = line.strip_prefix("data: ") {
rest.push_str(&serde_json::from_str::<String>(data)?);
}
}
if let Some(on_text) = &on_text {
on_text(&rest);
}
}
}
Ok(rest)
}
fn hydrate_file_part(
authorization: &CredentialsOrApiKey,
part: &Value,
group: Option<&Group>,
) -> Part {
let name = part["name"].as_str().unwrap_or("file");
let content_type = part["contentType"]
.as_str()
.unwrap_or("application/octet-stream");
let mut meta = part.clone();
meta["name"] = Value::from(name);
meta["contentType"] = Value::from(content_type);
if let Some(access_code) = part["accessCode"].as_str().filter(|code| !code.is_empty()) {
return Part::File(FilePart {
file: drive::File::from_json(
&meta,
DriveAuthorization::AccessCode {
authorization: authorization.clone(),
access_code: access_code.to_string(),
},
),
});
}
if let Some(path) = part["path"].as_str().filter(|path| !path.is_empty()) {
return Part::File(FilePart {
file: drive::File::from_json(
&meta,
DriveAuthorization::Path {
authorization: authorization.clone(),
path: path.to_string(),
group: part["group"]
.as_str()
.map(str::to_string)
.or_else(|| group.map(|group| group.id.clone())),
},
),
});
}
Part::File(FilePart {
file: drive::from_bytes(
authorization.clone(),
name,
content_type,
Vec::new(),
FileDates::default(),
),
})
}
pub async fn read_chat(
authorization: &CredentialsOrApiKey,
id: &str,
group: Option<&Group>,
query: PageQuery,
) -> Result<Vec<Content>> {
let mut request = client()
.post(format!("{}/chat/read", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({ "id": id, "cursor": query.cursor, "max": query.max }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
let file = |part: &Value| hydrate_file_part(authorization, part, group);
let messages = json
.as_array()
.into_iter()
.flatten()
.map(|message| Content::from_json(message, Some(&file)))
.collect();
Ok(messages)
}
pub async fn write_chat(
authorization: &CredentialsOrApiKey,
id: &str,
messages: &[Content],
group: Option<&Group>,
) -> Result<()> {
let mut serialized_messages = Vec::with_capacity(messages.len());
for message in messages {
let mut serialized_parts = Vec::with_capacity(message.parts.len());
for part in &message.parts {
match part {
Part::File(part) if !part.file.online() => {
let file = &part.file;
let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
let bytes = file.clone().download(false, None).await?;
let mut ready = drive::from_bytes(
authorization.clone(),
&dest,
&file.content_type,
bytes,
FileDates::default(),
);
ready.upload(None).await?;
serialized_parts.push(file_ref(&ready));
}
part => serialized_parts.push(part.wire()),
}
}
let mut wire = Map::new();
wire.insert("parts".to_string(), Value::Array(serialized_parts));
wire.insert("role".to_string(), serde_json::to_value(message.role)?);
if let Some(author) = &message.author {
wire.insert("author".to_string(), serde_json::to_value(author)?);
}
if let Some(model) = &message.model {
wire.insert("model".to_string(), Value::from(model.as_str()));
}
wire.insert(
"createdAt".to_string(),
Value::from(
message
.created_at
.to_rfc3339_opts(SecondsFormat::Millis, true),
),
);
serialized_messages.push(Value::Object(wire));
}
let mut request = client()
.post(format!("{}/chat/write", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
if let Some(group) = group {
request = request.header("Group", &group.id);
}
let response = request
.json(&json!({ "id": id, "messages": serialized_messages }))
.send()
.await?;
ok(response).await?;
Ok(())
}