2024-06-03 06:27:28 +00:00
|
|
|
use crate::chat::Chat;
|
|
|
|
use crate::entities::{ChatMessageListPB, ChatMessagePB, RepeatedRelatedQuestionPB};
|
2024-07-15 07:23:23 +00:00
|
|
|
use crate::local_ai::local_llm_chat::LocalAIController;
|
2024-08-01 15:13:35 +00:00
|
|
|
use crate::middleware::chat_service_mw::AICloudServiceMiddleware;
|
2024-06-03 06:27:28 +00:00
|
|
|
use crate::persistence::{insert_chat, ChatTable};
|
2024-07-15 07:23:23 +00:00
|
|
|
|
2024-07-08 05:19:13 +00:00
|
|
|
use appflowy_plugin::manager::PluginManager;
|
2024-06-03 06:27:28 +00:00
|
|
|
use dashmap::DashMap;
|
2024-08-01 15:13:35 +00:00
|
|
|
use flowy_ai_pub::cloud::{ChatCloudService, ChatMessageType};
|
2024-06-03 06:27:28 +00:00
|
|
|
use flowy_error::{FlowyError, FlowyResult};
|
2024-06-30 09:38:39 +00:00
|
|
|
use flowy_sqlite::kv::KVStorePreferences;
|
2024-06-03 06:27:28 +00:00
|
|
|
use flowy_sqlite::DBConnection;
|
2024-07-15 07:23:23 +00:00
|
|
|
|
2024-06-03 06:27:28 +00:00
|
|
|
use lib_infra::util::timestamp;
|
2024-07-15 07:23:23 +00:00
|
|
|
use std::path::PathBuf;
|
2024-06-03 06:27:28 +00:00
|
|
|
use std::sync::Arc;
|
2024-07-31 03:47:09 +00:00
|
|
|
use tracing::{info, trace};
|
2024-06-03 06:27:28 +00:00
|
|
|
|
2024-08-01 15:13:35 +00:00
|
|
|
pub trait AIUserService: Send + Sync + 'static {
|
2024-06-03 06:27:28 +00:00
|
|
|
fn user_id(&self) -> Result<i64, FlowyError>;
|
|
|
|
fn device_id(&self) -> Result<String, FlowyError>;
|
|
|
|
fn workspace_id(&self) -> Result<String, FlowyError>;
|
|
|
|
fn sqlite_connection(&self, uid: i64) -> Result<DBConnection, FlowyError>;
|
2024-07-30 09:32:30 +00:00
|
|
|
fn data_root_dir(&self) -> Result<PathBuf, FlowyError>;
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
|
2024-08-01 15:13:35 +00:00
|
|
|
pub struct AIManager {
|
|
|
|
pub cloud_service_wm: Arc<AICloudServiceMiddleware>,
|
|
|
|
pub user_service: Arc<dyn AIUserService>,
|
2024-06-03 06:27:28 +00:00
|
|
|
chats: Arc<DashMap<String, Arc<Chat>>>,
|
2024-07-15 07:23:23 +00:00
|
|
|
pub local_ai_controller: Arc<LocalAIController>,
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
|
2024-08-01 15:13:35 +00:00
|
|
|
impl AIManager {
|
2024-06-03 06:27:28 +00:00
|
|
|
pub fn new(
|
2024-08-01 15:13:35 +00:00
|
|
|
chat_cloud_service: Arc<dyn ChatCloudService>,
|
|
|
|
user_service: impl AIUserService,
|
2024-06-30 09:38:39 +00:00
|
|
|
store_preferences: Arc<KVStorePreferences>,
|
2024-08-01 15:13:35 +00:00
|
|
|
) -> AIManager {
|
2024-06-03 06:27:28 +00:00
|
|
|
let user_service = Arc::new(user_service);
|
2024-07-08 05:19:13 +00:00
|
|
|
let plugin_manager = Arc::new(PluginManager::new());
|
2024-07-15 07:23:23 +00:00
|
|
|
let local_ai_controller = Arc::new(LocalAIController::new(
|
|
|
|
plugin_manager.clone(),
|
|
|
|
store_preferences.clone(),
|
|
|
|
user_service.clone(),
|
2024-08-01 15:13:35 +00:00
|
|
|
chat_cloud_service.clone(),
|
2024-07-15 07:23:23 +00:00
|
|
|
));
|
|
|
|
|
2024-06-30 09:38:39 +00:00
|
|
|
// setup local chat service
|
2024-08-01 15:13:35 +00:00
|
|
|
let cloud_service_wm = Arc::new(AICloudServiceMiddleware::new(
|
2024-06-30 09:38:39 +00:00
|
|
|
user_service.clone(),
|
2024-08-01 15:13:35 +00:00
|
|
|
chat_cloud_service,
|
2024-07-15 07:23:23 +00:00
|
|
|
local_ai_controller.clone(),
|
2024-06-30 09:38:39 +00:00
|
|
|
));
|
2024-06-03 06:27:28 +00:00
|
|
|
|
|
|
|
Self {
|
2024-07-25 11:41:16 +00:00
|
|
|
cloud_service_wm,
|
2024-06-03 06:27:28 +00:00
|
|
|
user_service,
|
|
|
|
chats: Arc::new(DashMap::new()),
|
2024-07-15 07:23:23 +00:00
|
|
|
local_ai_controller,
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn open_chat(&self, chat_id: &str) -> Result<(), FlowyError> {
|
|
|
|
trace!("open chat: {}", chat_id);
|
|
|
|
self.chats.entry(chat_id.to_string()).or_insert_with(|| {
|
|
|
|
Arc::new(Chat::new(
|
|
|
|
self.user_service.user_id().unwrap(),
|
|
|
|
chat_id.to_string(),
|
|
|
|
self.user_service.clone(),
|
2024-07-25 11:41:16 +00:00
|
|
|
self.cloud_service_wm.clone(),
|
2024-06-03 06:27:28 +00:00
|
|
|
))
|
|
|
|
});
|
|
|
|
|
2024-07-15 07:23:23 +00:00
|
|
|
trace!("[AI Plugin] notify open chat: {}", chat_id);
|
2024-07-25 11:41:16 +00:00
|
|
|
if self.local_ai_controller.is_running() {
|
|
|
|
self.local_ai_controller.open_chat(chat_id);
|
|
|
|
}
|
2024-06-03 06:27:28 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-06-30 09:38:39 +00:00
|
|
|
pub async fn close_chat(&self, chat_id: &str) -> Result<(), FlowyError> {
|
|
|
|
trace!("close chat: {}", chat_id);
|
2024-07-15 07:23:23 +00:00
|
|
|
|
2024-07-18 12:54:35 +00:00
|
|
|
if self.local_ai_controller.is_running() {
|
2024-07-15 07:23:23 +00:00
|
|
|
info!("[AI Plugin] notify close chat: {}", chat_id);
|
|
|
|
self.local_ai_controller.close_chat(chat_id);
|
|
|
|
}
|
2024-06-03 06:27:28 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn delete_chat(&self, chat_id: &str) -> Result<(), FlowyError> {
|
|
|
|
if let Some((_, chat)) = self.chats.remove(chat_id) {
|
|
|
|
chat.close();
|
2024-07-15 07:23:23 +00:00
|
|
|
|
2024-07-18 12:54:35 +00:00
|
|
|
if self.local_ai_controller.is_running() {
|
2024-07-15 07:23:23 +00:00
|
|
|
info!("[AI Plugin] notify close chat: {}", chat_id);
|
|
|
|
self.local_ai_controller.close_chat(chat_id);
|
|
|
|
}
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn create_chat(&self, uid: &i64, chat_id: &str) -> Result<Arc<Chat>, FlowyError> {
|
|
|
|
let workspace_id = self.user_service.workspace_id()?;
|
|
|
|
self
|
2024-07-25 11:41:16 +00:00
|
|
|
.cloud_service_wm
|
2024-06-03 06:27:28 +00:00
|
|
|
.create_chat(uid, &workspace_id, chat_id)
|
|
|
|
.await?;
|
|
|
|
save_chat(self.user_service.sqlite_connection(*uid)?, chat_id)?;
|
|
|
|
|
|
|
|
let chat = Arc::new(Chat::new(
|
|
|
|
self.user_service.user_id().unwrap(),
|
|
|
|
chat_id.to_string(),
|
|
|
|
self.user_service.clone(),
|
2024-07-25 11:41:16 +00:00
|
|
|
self.cloud_service_wm.clone(),
|
2024-06-03 06:27:28 +00:00
|
|
|
));
|
|
|
|
self.chats.insert(chat_id.to_string(), chat.clone());
|
|
|
|
Ok(chat)
|
|
|
|
}
|
|
|
|
|
2024-06-09 06:02:32 +00:00
|
|
|
pub async fn stream_chat_message(
|
2024-06-03 06:27:28 +00:00
|
|
|
&self,
|
|
|
|
chat_id: &str,
|
|
|
|
message: &str,
|
|
|
|
message_type: ChatMessageType,
|
2024-06-09 06:02:32 +00:00
|
|
|
text_stream_port: i64,
|
|
|
|
) -> Result<ChatMessagePB, FlowyError> {
|
2024-06-03 06:27:28 +00:00
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
2024-06-09 06:02:32 +00:00
|
|
|
let question = chat
|
|
|
|
.stream_chat_message(message, message_type, text_stream_port)
|
|
|
|
.await?;
|
|
|
|
Ok(question)
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_or_create_chat_instance(&self, chat_id: &str) -> Result<Arc<Chat>, FlowyError> {
|
|
|
|
let chat = self.chats.get(chat_id).as_deref().cloned();
|
|
|
|
match chat {
|
|
|
|
None => {
|
|
|
|
let chat = Arc::new(Chat::new(
|
|
|
|
self.user_service.user_id().unwrap(),
|
|
|
|
chat_id.to_string(),
|
|
|
|
self.user_service.clone(),
|
2024-07-25 11:41:16 +00:00
|
|
|
self.cloud_service_wm.clone(),
|
2024-06-03 06:27:28 +00:00
|
|
|
));
|
|
|
|
self.chats.insert(chat_id.to_string(), chat.clone());
|
|
|
|
Ok(chat)
|
|
|
|
},
|
|
|
|
Some(chat) => Ok(chat),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Load chat messages for a given `chat_id`.
|
|
|
|
///
|
|
|
|
/// 1. When opening a chat:
|
|
|
|
/// - Loads local chat messages.
|
|
|
|
/// - `after_message_id` and `before_message_id` are `None`.
|
|
|
|
/// - Spawns a task to load messages from the remote server, notifying the user when the remote messages are loaded.
|
|
|
|
///
|
|
|
|
/// 2. Loading more messages in an existing chat with `after_message_id`:
|
|
|
|
/// - `after_message_id` is the last message ID in the current chat messages.
|
|
|
|
///
|
|
|
|
/// 3. Loading more messages in an existing chat with `before_message_id`:
|
|
|
|
/// - `before_message_id` is the first message ID in the current chat messages.
|
|
|
|
///
|
|
|
|
/// 4. `after_message_id` and `before_message_id` cannot be specified at the same time.
|
|
|
|
|
|
|
|
pub async fn load_prev_chat_messages(
|
|
|
|
&self,
|
|
|
|
chat_id: &str,
|
|
|
|
limit: i64,
|
|
|
|
before_message_id: Option<i64>,
|
|
|
|
) -> Result<ChatMessageListPB, FlowyError> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
let list = chat
|
|
|
|
.load_prev_chat_messages(limit, before_message_id)
|
|
|
|
.await?;
|
|
|
|
Ok(list)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn load_latest_chat_messages(
|
|
|
|
&self,
|
|
|
|
chat_id: &str,
|
|
|
|
limit: i64,
|
|
|
|
after_message_id: Option<i64>,
|
|
|
|
) -> Result<ChatMessageListPB, FlowyError> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
let list = chat
|
|
|
|
.load_latest_chat_messages(limit, after_message_id)
|
|
|
|
.await?;
|
|
|
|
Ok(list)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_related_questions(
|
|
|
|
&self,
|
|
|
|
chat_id: &str,
|
|
|
|
message_id: i64,
|
|
|
|
) -> Result<RepeatedRelatedQuestionPB, FlowyError> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
let resp = chat.get_related_question(message_id).await?;
|
|
|
|
Ok(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn generate_answer(
|
|
|
|
&self,
|
|
|
|
chat_id: &str,
|
|
|
|
question_message_id: i64,
|
|
|
|
) -> Result<ChatMessagePB, FlowyError> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
let resp = chat.generate_answer(question_message_id).await?;
|
|
|
|
Ok(resp)
|
|
|
|
}
|
2024-06-09 06:02:32 +00:00
|
|
|
|
|
|
|
pub async fn stop_stream(&self, chat_id: &str) -> Result<(), FlowyError> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
chat.stop_stream_message().await;
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-07-15 07:23:23 +00:00
|
|
|
|
|
|
|
pub async fn chat_with_file(&self, chat_id: &str, file_path: PathBuf) -> FlowyResult<()> {
|
|
|
|
let chat = self.get_or_create_chat_instance(chat_id).await?;
|
|
|
|
chat.index_file(file_path).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-07-22 07:43:48 +00:00
|
|
|
|
|
|
|
pub fn local_ai_purchased(&self) {
|
|
|
|
// TODO(nathan): enable local ai
|
|
|
|
}
|
2024-06-03 06:27:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn save_chat(conn: DBConnection, chat_id: &str) -> FlowyResult<()> {
|
|
|
|
let row = ChatTable {
|
|
|
|
chat_id: chat_id.to_string(),
|
|
|
|
created_at: timestamp(),
|
|
|
|
name: "".to_string(),
|
2024-06-30 09:38:39 +00:00
|
|
|
local_model_path: "".to_string(),
|
|
|
|
local_model_name: "".to_string(),
|
|
|
|
local_enabled: false,
|
|
|
|
sync_to_cloud: true,
|
2024-06-03 06:27:28 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
insert_chat(conn, &row)?;
|
|
|
|
Ok(())
|
|
|
|
}
|