Skip to content

Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.

Custom langchain rust (#7887)

Nathan.fooof7b556677f4c
diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart
index 2a058c6f37..20ec0f9fa4 100644
--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart
+++ b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart
@@ -150,14 +150,16 @@ class SettingItem extends Equatable {
required this.content,
required this.hintText,
required this.settingType,
+ this.editable = true,
});
final String content;
final String hintText;
final SettingType settingType;
+ final bool editable;
@override
- List<Object?> get props => [content, settingType];
+ List<Object?> get props => [content, settingType, editable];
}
/// Items pending submission
@@ -232,6 +234,7 @@ extension on LocalAISettingPB {
content: embeddingModelName,
hintText: kDefaultEmbeddingModel,
settingType: SettingType.embeddingModel,
+ editable: false, // embedding model is not editable
),
];
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart
index fee14d22a5..9f0931f8f1 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart
@@ -70,15 +70,26 @@ class _SettingItemWidget extends StatelessWidget {
const VSpace(4),
SizedBox(
height: 32,
- child: FlowyTextField(
- autoFocus: false,
- hintText: item.hintText,
- text: item.content,
- onChanged: (content) {
- context.read<OllamaSettingBloc>().add(
- OllamaSettingEvent.onEdit(content, item.settingType),
- );
- },
+ child: FlowyTooltip(
+ message: item.editable
+ ? null
+ : LocaleKeys.settings_aiPage_keys_readOnlyField.tr(),
+ child: FlowyTextField(
+ autoFocus: false,
+ hintText: item.hintText,
+ text: item.content,
+ readOnly: !item.editable,
+ onChanged: item.editable
+ ? (content) {
+ context.read<OllamaSettingBloc>().add(
+ OllamaSettingEvent.onEdit(
+ content,
+ item.settingType,
+ ),
+ );
+ }
+ : null,
+ ),
),
),
],
diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.json
index 9118e1c1f9..c603952443 100644
--- a/frontend/resources/translations/en.json
+++ b/frontend/resources/translations/en.json
@@ -892,6 +892,7 @@
"loginToEnableAIFeature": "AI features are only enabled after logging in with @:appName Cloud. If you don't have an @:appName account, go to 'My Account' to sign up",
"llmModel": "Language Model",
"globalLLMModel": "Global Language Model",
+ "readOnlyField": "This field is read-only",
"llmModelType": "Language Model Type",
"downloadLLMPrompt": "Download {}",
"downloadAppFlowyOfflineAI": "Downloading AI offline package will enable AI to run on your device. Do you want to continue?",
diff --git a/frontend/rust-lib/Cargo.lock b/frontend/rust-lib/Cargo.lock
index 11876b9076..bcad5767af 100644
--- a/frontend/rust-lib/Cargo.lock
+++ b/frontend/rust-lib/Cargo.lock
@@ -431,9 +431,9 @@ dependencies = [
[[package]]
name = "aho-corasick"
-version = "1.0.5"
+version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
@@ -1877,7 +1877,7 @@ dependencies = [
"cssparser-macros",
"dtoa-short",
"itoa",
- "phf 0.8.0",
+ "phf 0.11.2",
"smallvec",
]
@@ -2687,7 +2687,6 @@ dependencies = [
"lopdf",
"notify",
"ollama-rs",
- "once_cell",
"pin-project",
"protobuf",
"pulldown-cmark 0.13.0",
@@ -4569,7 +4568,7 @@ dependencies = [
[[package]]
name = "langchain-rust"
version = "4.6.0"
-source = "git+https://github.com/appflowy/langchain-rust?branch=bump_ollama_rs#f57eef4cbd124db06a40e757bc3cea68d73e169a"
+source = "git+https://github.com/appflowy/langchain-rust?branch=af#9a319193352331fa4e5ff1dd4de43a0fbc5d0cbd"
dependencies = [
"async-openai 0.28.1",
"async-recursion",
@@ -5851,9 +5850,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkg-config"
-version = "0.3.27"
+version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964"
+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "polyval"
@@ -6042,7 +6041,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9552f850d5f0964a4e4d0bf306459ac29323ddfbae05e35a7c0d35cb0803cc5"
dependencies = [
"anyhow",
- "itertools 0.12.1",
+ "itertools 0.13.0",
"proc-macro2",
"quote",
"syn 2.0.94",
@@ -7944,9 +7943,9 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]]
name = "tantivy"
-version = "0.24.0"
+version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b21ad8b222d71c57aa979353ed702f0bc6d97e66d368962cbded57fbd19eedd7"
+checksum = "ca2374a21157427c5faff2d90930f035b6c22a5d7b0e5b0b7f522e988ef33c06"
dependencies = [
"aho-corasick",
"arc-swap",
diff --git a/frontend/rust-lib/Cargo.toml b/frontend/rust-lib/Cargo.toml
index 88270beab7..197aa4481d 100644
--- a/frontend/rust-lib/Cargo.toml
+++ b/frontend/rust-lib/Cargo.toml
@@ -100,7 +100,7 @@ tokio-util = "0.7.11"
zip = "2.2.0"
dashmap = "6.0.1"
derive_builder = "0.20.2"
-tantivy = { version = "0.24.0" }
+tantivy = { version = "0.24.1" }
af-plugin = { version = "0.1" }
af-local-ai = { version = "0.1" }
num_enum = "0.7.3"
@@ -165,4 +165,4 @@ af-local-ai = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-
af-plugin = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "093d3f4916a7b924ac66b4f0a9d81cc5fcc72eaa" }
af-mcp = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "093d3f4916a7b924ac66b4f0a9d81cc5fcc72eaa" }
-langchain-rust = { version = "4.6.0", git = "https://github.com/appflowy/langchain-rust", branch = "bump_ollama_rs" }
\ No newline at end of file
+langchain-rust = { version = "4.6.0", git = "https://github.com/appflowy/langchain-rust", branch = "af" }
\ No newline at end of file
diff --git a/frontend/rust-lib/flowy-ai-pub/src/persistence/chat_sql.rs b/frontend/rust-lib/flowy-ai-pub/src/persistence/chat_sql.rs
index f5398c48c0..56f0149f06 100644
--- a/frontend/rust-lib/flowy-ai-pub/src/persistence/chat_sql.rs
+++ b/frontend/rust-lib/flowy-ai-pub/src/persistence/chat_sql.rs
@@ -18,10 +18,10 @@ use uuid::Uuid;
pub struct ChatTable {
pub chat_id: String,
pub created_at: i64,
- pub name: String,
pub metadata: String,
pub rag_ids: Option<String>,
pub is_sync: bool,
+ pub summary: String,
}
impl ChatTable {
@@ -32,10 +32,10 @@ impl ChatTable {
Self {
chat_id,
created_at: timestamp(),
- name: "".to_string(),
metadata,
rag_ids,
is_sync,
+ summary: "".to_string(),
}
}
}
@@ -66,10 +66,33 @@ pub struct ChatTableFile {
#[diesel(primary_key(chat_id))]
pub struct ChatTableChangeset {
pub chat_id: String,
- pub name: Option<String>,
pub metadata: Option<String>,
pub rag_ids: Option<String>,
pub is_sync: Option<bool>,
+ pub summary: Option<String>,
+}
+
+impl ChatTableChangeset {
+ pub fn summary(chat_id: String, summary: String) -> Self {
+ Self {
+ chat_id,
+ metadata: None,
+ rag_ids: None,
+ is_sync: None,
+ summary: Some(summary),
+ }
+ }
+
+ pub fn rag_ids(chat_id: String, rag_ids: Vec<String>) -> Self {
+ let rag_ids = Some(serialize_rag_ids(&rag_ids));
+ Self {
+ chat_id,
+ metadata: None,
+ rag_ids,
+ is_sync: None,
+ summary: None,
+ }
+ }
}
pub fn serialize_rag_ids(rag_ids: &[String]) -> String {
@@ -104,7 +127,6 @@ pub fn upsert_chat(mut conn: DBConnection, new_chat: &ChatTable) -> QueryResult<
.do_update()
.set((
chat_table::created_at.eq(excluded(chat_table::created_at)),
- chat_table::name.eq(excluded(chat_table::name)),
chat_table::metadata.eq(excluded(chat_table::metadata)),
chat_table::rag_ids.eq(excluded(chat_table::rag_ids)),
chat_table::is_sync.eq(excluded(chat_table::is_sync)),
@@ -112,13 +134,33 @@ pub fn upsert_chat(mut conn: DBConnection, new_chat: &ChatTable) -> QueryResult<
.execute(&mut *conn)
}
-pub fn update_chat(
- conn: &mut SqliteConnection,
- changeset: ChatTableChangeset,
-) -> QueryResult<usize> {
- let filter = dsl::chat_table.filter(chat_table::chat_id.eq(changeset.chat_id.clone()));
- let affected_row = diesel::update(filter).set(changeset).execute(conn)?;
- Ok(affected_row)
+pub fn update_chat(mut conn: DBConnection, changeset: ChatTableChangeset) -> QueryResult<usize> {
+ // Check if the chat exists
+ let chat_exists = dsl::chat_table
+ .filter(chat_table::chat_id.eq(&changeset.chat_id))
+ .first::<ChatTable>(&mut *conn)
+ .is_ok();
+
+ if chat_exists {
+ // Update existing chat
+ let filter = dsl::chat_table.filter(chat_table::chat_id.eq(changeset.chat_id.clone()));
+ diesel::update(filter).set(changeset).execute(&mut *conn)
+ } else {
+ // Create a new chat row with default values
+ let chat = ChatTable {
+ chat_id: changeset.chat_id.clone(),
+ created_at: timestamp(),
+ metadata: changeset.metadata.unwrap_or_else(|| "{}".to_string()),
+ rag_ids: changeset.rag_ids,
+ is_sync: changeset.is_sync.unwrap_or(false),
+ summary: changeset.summary.unwrap_or_default(),
+ };
+
+ // Insert the new row
+ diesel::insert_into(chat_table::table)
+ .values(&chat)
+ .execute(&mut *conn)
+ }
}
pub fn update_chat_is_sync(
@@ -131,14 +173,22 @@ pub fn update_chat_is_sync(
.execute(&mut *conn)
}
-pub fn read_chat(mut conn: DBConnection, chat_id_val: &str) -> QueryResult<ChatTable> {
+pub fn select_chat(mut conn: DBConnection, chat_id_val: &str) -> QueryResult<ChatTable> {
let row = dsl::chat_table
.filter(chat_table::chat_id.eq(chat_id_val))
.first::<ChatTable>(&mut *conn)?;
Ok(row)
}
-pub fn read_chat_rag_ids(
+pub fn select_chat_summary(conn: &mut DBConnection, chat_id_val: &Uuid) -> QueryResult<String> {
+ let summary = dsl::chat_table
+ .select(chat_table::summary)
+ .filter(chat_table::chat_id.eq(chat_id_val.to_string()))
+ .first::<String>(conn)?;
+ Ok(summary)
+}
+
+pub fn select_chat_rag_ids(
conn: &mut SqliteConnection,
chat_id_val: &str,
) -> FlowyResult<Vec<String>> {
@@ -149,7 +199,7 @@ pub fn read_chat_rag_ids(
Ok(deserialize_rag_ids(&chat.rag_ids))
}
-pub fn read_chat_metadata(
+pub fn select_chat_metadata(
conn: &mut SqliteConnection,
chat_id_val: &str,
) -> FlowyResult<ChatTableMetadata> {
@@ -160,17 +210,6 @@ pub fn read_chat_metadata(
Ok(deserialize_chat_metadata(&metadata_str))
}
-#[allow(dead_code)]
-pub fn update_chat_name(
- mut conn: DBConnection,
- chat_id_val: &str,
- new_name: &str,
-) -> QueryResult<usize> {
- diesel::update(dsl::chat_table.filter(chat_table::chat_id.eq(chat_id_val)))
- .set(chat_table::name.eq(new_name))
- .execute(&mut *conn)
-}
-
#[allow(dead_code)]
pub fn delete_chat(mut conn: DBConnection, chat_id_val: &str) -> QueryResult<usize> {
diesel::delete(dsl::chat_table.filter(chat_table::chat_id.eq(chat_id_val))).execute(&mut *conn)
diff --git a/frontend/rust-lib/flowy-ai/Cargo.toml b/frontend/rust-lib/flowy-ai/Cargo.toml
index ab385553bc..2080b56985 100644
--- a/frontend/rust-lib/flowy-ai/Cargo.toml
+++ b/frontend/rust-lib/flowy-ai/Cargo.toml
@@ -49,7 +49,6 @@ twox-hash = { version = "2.1.0", features = ["xxhash64"] }
async-trait.workspace = true
async-stream = "0.3.6"
flowy-database-pub = { workspace = true }
-once_cell = "1.21.3"
langchain-rust = { version = "4.6.0", features = ["ollama"] }
[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]
diff --git a/frontend/rust-lib/flowy-ai/src/ai_manager.rs b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
index 6c391ff5ed..cf1c500ea7 100644
--- a/frontend/rust-lib/flowy-ai/src/ai_manager.rs
+++ b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
@@ -5,7 +5,9 @@ use crate::entities::{
};
use crate::local_ai::controller::{LocalAIController, LocalAISetting};
use crate::middleware::chat_service_mw::ChatServiceMiddleware;
-use flowy_ai_pub::persistence::read_chat_metadata;
+use flowy_ai_pub::persistence::{
+ select_chat_metadata, select_chat_rag_ids, select_chat_summary, update_chat, ChatTableChangeset,
+};
use std::collections::HashMap;
use dashmap::DashMap;
@@ -22,6 +24,7 @@ use flowy_ai_pub::persistence::{
batch_insert_collab_metadata, batch_select_collab_metadata, AFCollabMetadata,
};
use flowy_ai_pub::user_service::AIUserService;
+use flowy_sqlite::DBConnection;
use flowy_storage_pub::storage::StorageService;
use lib_infra::async_trait::async_trait;
use serde_json::json;
@@ -29,7 +32,7 @@ use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, Weak};
use tokio::sync::Mutex;
-use tracing::{error, info, instrument, trace};
+use tracing::{error, info, instrument, trace, warn};
use uuid::Uuid;
/// AIExternalService is an interface for external services that AI plugin can interact with.
@@ -209,18 +212,16 @@ impl AIManager {
if self.local_ai.is_enabled() {
let workspace_id = self.user_service.workspace_id()?;
+ let uid = self.user_service.user_id()?;
+ let mut conn = self.user_service.sqlite_connection(uid)?;
+ let rag_ids = self.get_rag_ids(chat_id, &mut conn).await?;
+ let summary = select_chat_summary(&mut conn, chat_id).unwrap_or_default();
+
let model = self.get_active_model(&chat_id.to_string()).await;
trace!("[AI Plugin] notify open chat: {}", chat_id);
- let mut rag_ids = vec![];
- if let Some(settings) = self
- .store_preferences
- .get_object::<ChatSettings>(&setting_store_key(chat_id))
- {
- rag_ids = settings.rag_ids;
- }
self
.local_ai
- .open_chat(&workspace_id, chat_id, &model.name, rag_ids)
+ .open_chat(&workspace_id, chat_id, &model.name, rag_ids, summary)
.await?;
}
@@ -274,7 +275,7 @@ impl AIManager {
pub async fn get_chat_info(&self, chat_id: &str) -> FlowyResult<ChatInfoPB> {
let uid = self.user_service.user_id()?;
let mut conn = self.user_service.sqlite_connection(uid)?;
- let metadata = read_chat_metadata(&mut conn, chat_id)?;
+ let metadata = select_chat_metadata(&mut conn, chat_id)?;
let files = metadata
.files
.into_iter()
@@ -659,12 +660,25 @@ impl AIManager {
Ok(())
}
- pub async fn get_rag_ids(&self, chat_id: &Uuid) -> FlowyResult<Vec<String>> {
- if let Some(settings) = self
- .store_preferences
- .get_object::<ChatSettings>(&setting_store_key(chat_id))
- {
- return Ok(settings.rag_ids);
+ pub async fn get_rag_ids(
+ &self,
+ chat_id: &Uuid,
+ conn: &mut DBConnection,
+ ) -> FlowyResult<Vec<String>> {
+ match select_chat_rag_ids(&mut *conn, &chat_id.to_string()) {
+ Ok(ids) => {
+ return Ok(ids);
+ },
+ Err(_) => {
+ // we no long use store_preferences to store chat settings
+ warn!("[Chat] failed to get chat rag ids from sqlite, try to get from store_preferences");
+ if let Some(settings) = self
+ .store_preferences
+ .get_object::<ChatSettings>(&setting_store_key(chat_id))
+ {
+ return Ok(settings.rag_ids);
+ }
+ },
}
let settings = refresh_chat_setting(
@@ -690,21 +704,12 @@ impl AIManager {
.update_chat_settings(&workspace_id, chat_id, update_setting)
.await?;
- let chat_setting_store_key = setting_store_key(chat_id);
- if let Some(settings) = self
- .store_preferences
- .get_object::<ChatSettings>(&chat_setting_store_key)
- {
- if let Err(err) = self.store_preferences.set_object(
- &chat_setting_store_key,
- &ChatSettings {
- rag_ids: rag_ids.clone(),
- ..settings
- },
- ) {
- error!("failed to set chat settings: {}", err);
- }
- }
+ let uid = self.user_service.user_id()?;
+ let conn = self.user_service.sqlite_connection(uid)?;
+ update_chat(
+ conn,
+ ChatTableChangeset::rag_ids(chat_id.to_string(), rag_ids.clone()),
+ )?;
let user_service = self.user_service.clone();
let external_service = self.external_service.clone();
diff --git a/frontend/rust-lib/flowy-ai/src/event_handler.rs b/frontend/rust-lib/flowy-ai/src/event_handler.rs
index 1f4d35bc33..2de5ad96f1 100644
--- a/frontend/rust-lib/flowy-ai/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_handler.rs
@@ -313,7 +313,9 @@ pub(crate) async fn get_chat_settings_handler(
let chat_id = data.try_into_inner()?.value;
let chat_id = Uuid::from_str(&chat_id)?;
let ai_manager = upgrade_ai_manager(ai_manager)?;
- let rag_ids = ai_manager.get_rag_ids(&chat_id).await?;
+ let uid = ai_manager.user_service.user_id()?;
+ let mut conn = ai_manager.user_service.sqlite_connection(uid)?;
+ let rag_ids = ai_manager.get_rag_ids(&chat_id, &mut conn).await?;
let pb = ChatSettingsPB { rag_ids };
data_result_ok(pb)
}
diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/chat/conversation_chain.rs b/frontend/rust-lib/flowy-ai/src/local_ai/chat/conversation_chain.rs
index 95232aada8..9191f16fba 100644
--- a/frontend/rust-lib/flowy-ai/src/local_ai/chat/conversation_chain.rs
+++ b/frontend/rust-lib/flowy-ai/src/local_ai/chat/conversation_chain.rs
@@ -120,7 +120,7 @@ impl Chain for ConversationalRetrieverChain {
let human_message = Message::new_human_message(input_variable);
let history = {
let memory = self.memory.lock().await;
- memory.messages()
+ memory.messages().await
};
let (question, token) = self.get_question(&history, &human_message.content).await?;
@@ -132,8 +132,10 @@ impl Chain for ConversationalRetrieverChain {
Either::Left(docs) => docs,
Either::Right(result) => {
let mut memory = self.memory.lock().await;
- memory.add_message(human_message);
- memory.add_message(Message::new_ai_message(&result.generation));
+ memory.add_message(human_message).await;
+ memory
+ .add_message(Message::new_ai_message(&result.generation))
+ .await;
let mut output = HashMap::new();
output.insert(self.output_key.clone(), json!(result.generation));
@@ -161,8 +163,10 @@ impl Chain for ConversationalRetrieverChain {
{
let mut memory = self.memory.lock().await;
- memory.add_message(human_message);
- memory.add_message(Message::new_ai_message(&output.generation));
+ memory.add_message(human_message).await;
+ memory
+ .add_message(Message::new_ai_message(&output.generation))
+ .await;
}
let mut result = HashMap::new();
@@ -197,7 +201,7 @@ impl Chain for ConversationalRetrieverChain {
let human_message = Message::new_human_message(input_variable);
let history = {
let memory = self.memory.lock().await;
- memory.messages()
+ memory.messages().await
};
let (question, _) = self.get_question(&history, &human_message.content).await?;
@@ -206,8 +210,10 @@ impl Chain for ConversationalRetrieverChain {
Either::Left(docs) => docs,
Either::Right(result) => {
let mut memory = self.memory.lock().await;
- memory.add_message(human_message);
- memory.add_message(Message::new_ai_message(&result.generation));
+ memory.add_message(human_message).await;
+ memory
+ .add_message(Message::new_ai_message(&result.generation))
+ .await;
return Ok(Box::pin(stream! {
yield Ok(StreamData::new(
@@ -259,8 +265,8 @@ impl Chain for ConversationalRetrieverChain {
}
let mut memory = memory.lock().await;
- memory.add_message(human_message);
- memory.add_message(Message::new_ai_message(&complete_ai_message.lock().await));
+ memory.add_message(human_message).await;
+ memory.add_message(Message::new_ai_message(&complete_ai_message.lock().await)).await;
};
Ok(Box::pin(output_stream))
diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/chat/llm_chat.rs b/frontend/rust-lib/flowy-ai/src/local_ai/chat/llm_chat.rs
index a60efa651f..542b620567 100644
--- a/frontend/rust-lib/flowy-ai/src/local_ai/chat/llm_chat.rs
+++ b/frontend/rust-lib/flowy-ai/src/local_ai/chat/llm_chat.rs
@@ -3,10 +3,12 @@ use crate::local_ai::chat::conversation_chain::{
};
use crate::local_ai::chat::format_prompt::AFMessageFormatter;
use crate::local_ai::chat::llm::LLMOllama;
-use crate::local_ai::chat::OllamaClientRef;
+use crate::local_ai::chat::summary_memory::SummaryMemory;
+use crate::local_ai::chat::{LLMChatInfo, OllamaClientRef};
use crate::SqliteVectorStore;
use flowy_ai_pub::cloud::{QuestionStreamValue, ResponseFormat, StreamAnswer};
use flowy_ai_pub::entities::{RAG_IDS, SOURCE_ID};
+use flowy_ai_pub::user_service::AIUserService;
use flowy_error::{FlowyError, FlowyResult};
use futures::StreamExt;
use langchain_rust::chain::{Chain, ChainError};
@@ -16,49 +18,56 @@ use langchain_rust::schemas::{Document, Message};
use langchain_rust::vectorstore::{VecStoreOptions, VectorStore};
use serde_json::json;
use std::collections::HashMap;
+use std::sync::Weak;
use tracing::{info, trace};
use uuid::Uuid;
pub struct LLMChat {
- workspace_id: Uuid,
- chat_id: Uuid,
store: Option<SqliteVectorStore>,
chain: ConversationalRetrieverChain,
#[allow(dead_code)]
client: OllamaClientRef,
- rag_ids: Vec<String>,
- dynamic_formatter: AFMessageFormatter,
+ formatter: AFMessageFormatter,
+ info: LLMChatInfo,
}
impl LLMChat {
pub async fn new(
- workspace_id: Uuid,
- chat_id: Uuid,
- model: &str,
+ info: LLMChatInfo,
client: OllamaClientRef,
store: Option<SqliteVectorStore>,
- rag_ids: Vec<String>,
+ user_service: Option<Weak<dyn AIUserService>>,
) -> FlowyResult<Self> {
- let initial_format = ResponseFormat::default();
- let formatter = create_dynamic_prompt_with_format(&initial_format);
- let (chain, dynamic_formatter) = create_chain(
- &workspace_id,
- model,
- &client,
- rag_ids.clone(),
- formatter,
- store.clone(),
- )
- .await?;
+ let response_format = ResponseFormat::default();
+ let formatter = create_formatter_prompt_with_format(&response_format);
+ let llm = create_llm(&client, &info.model).await?;
+ let summary_llm = create_llm(&client, &info.model).await?;
+ let memory = SummaryMemory::new(summary_llm, info.summary.clone(), user_service)
+ .await
+ .map(|v| v.into())
+ .unwrap_or(SimpleMemory::new().into());
+
+ let mut builder = ConversationalRetrieverChainBuilder::new()
+ .llm(llm)
+ .rephrase_question(false)
+ .memory(memory);
+
+ if let Some(store) = store.clone() {
+ let retriever = create_retriever(&info.workspace_id, info.rag_ids.clone(), store);
+ builder = builder.retriever(retriever);
+ }
+
+ let chain = builder
+ .prompt(formatter.clone())
+ .build()
+ .map_err(|err| FlowyError::local_ai().with_context(err))?;
Ok(Self {
- workspace_id,
- chat_id,
store,
chain,
client,
- rag_ids,
- dynamic_formatter,
+ formatter,
+ info,
})
}
@@ -67,7 +76,10 @@ impl LLMChat {
}
pub async fn set_rag_ids(&mut self, rag_ids: Vec<String>) {
- info!("[VectorStore]: {} set rag ids: {:?}", self.chat_id, rag_ids);
+ info!(
+ "[VectorStore]: {} set rag ids: {:?}",
+ self.info.chat_id, rag_ids
+ );
self.chain.retriever.set_rag_ids(rag_ids);
}
@@ -82,8 +94,8 @@ impl LLMChat {
.as_ref()
.ok_or_else(|| FlowyError::local_ai().with_context("VectorStore is not initialized"))?;
- let options =
- RetrieverOption::new().with_filters(json!({RAG_IDS: ids, "workspace_id": self.workspace_id}));
+ let options = RetrieverOption::new()
+ .with_filters(json!({RAG_IDS: ids, "workspace_id": self.info.workspace_id}));
let result = store
.similarity_search(query, limit, &options)
.await
@@ -101,7 +113,7 @@ impl LLMChat {
.ok_or_else(|| FlowyError::local_ai().with_context("VectorStore is not initialized"))?;
store
- .select_all_embedded_documents(&self.workspace_id.to_string(), &self.rag_ids)
+ .select_all_embedded_documents(&self.info.workspace_id.to_string(), &self.info.rag_ids)
.await
.map_err(|err| {
FlowyError::local_ai().with_context(format!("Failed to select embedded documents: {}", err))
@@ -114,7 +126,7 @@ impl LLMChat {
paragraphs: Vec<String>,
) -> FlowyResult<()> {
let mut metadata = HashMap::new();
- metadata.insert("workspace_id".to_string(), json!(self.workspace_id));
+ metadata.insert("workspace_id".to_string(), json!(self.info.workspace_id));
metadata.insert(SOURCE_ID.to_string(), json!(object_id));
let document = Document::new(paragraphs.join("\n\n")).with_metadata(metadata);
if let Some(store) = &self.store {
@@ -145,7 +157,7 @@ impl LLMChat {
message: &str,
format: ResponseFormat,
) -> Result<StreamAnswer, FlowyError> {
- self.dynamic_formatter.update_format(&format)?;
+ self.formatter.update_format(&format)?;
let input_variables = prompt_args! {
"question" => message,
};
@@ -172,7 +184,7 @@ impl LLMChat {
}
}
-fn create_dynamic_prompt_with_format(format: &ResponseFormat) -> AFMessageFormatter {
+fn create_formatter_prompt_with_format(format: &ResponseFormat) -> AFMessageFormatter {
let system_message =
Message::new_system_message("You are an assistant for question-answering tasks");
@@ -196,34 +208,6 @@ fn create_retriever(
AFRetriever::new(store, 5, options)
}
-async fn create_chain(
- workspace_id: &Uuid,
- model: &str,
- client: &OllamaClientRef,
- rag_ids: Vec<String>,
- formatter: AFMessageFormatter,
- store: Option<SqliteVectorStore>,
-) -> FlowyResult<(ConversationalRetrieverChain, AFMessageFormatter)> {
- let llm = create_llm(client, model).await?;
-
- let mut builder = ConversationalRetrieverChainBuilder::new()
- .llm(llm)
- .rephrase_question(false)
- .memory(SimpleMemory::new().into());
-
- if let Some(store) = store {
- let retriever = create_retriever(workspace_id, rag_ids, store);
- builder = builder.retriever(retriever);
- }
-
- let chain = builder
- .prompt(formatter.clone())
- .build()
- .map_err(|err| FlowyError::local_ai().with_context(err))?;
-
- Ok((chain, formatter))
-}
-
async fn create_llm(client: &OllamaClientRef, model: &str) -> FlowyResult<LLMOllama> {
let read_guard = client.read().await;
let client = read_guard
diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/chat/mod.rs b/frontend/rust-lib/flowy-ai/src/local_ai/chat/mod.rs
index 5d233bcac6..a7844b980c 100644
--- a/frontend/rust-lib/flowy-ai/src/local_ai/chat/mod.rs
+++ b/frontend/rust-lib/flowy-ai/src/local_ai/chat/mod.rs
@@ -3,6 +3,7 @@ mod format_prompt;
pub mod llm;
pub mod llm_chat;
pub mod related_question_chain;
+mod summary_memory;
use crate::local_ai::chat::llm::LLMOllama;
use crate::local_ai::chat::llm_chat::LLMChat;
@@ -28,11 +29,19 @@ use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use tokio::sync::RwLock;
-use tracing::{info, trace};
+use tracing::trace;
use uuid::Uuid;
type OllamaClientRef = Arc<RwLock<Option<Weak<Ollama>>>>;
+pub struct LLMChatInfo {
+ pub chat_id: Uuid,
+ pub workspace_id: Uuid,
+ pub model: String,
+ pub rag_ids: Vec<String>,
+ pub summary: String,
+}
+
pub struct LLMChatController {
chat_by_id: DashMap<Uuid, LLMChat>,
store: RwLock<Option<SqliteVectorStore>>,
@@ -70,25 +79,17 @@ impl LLMChatController {
}
}
- pub async fn open_chat(
- &self,
- workspace_id: &Uuid,
- chat_id: &Uuid,
- model: &str,
- rag_ids: Vec<String>,
- ) -> FlowyResult<()> {
+ pub async fn open_chat(&self, info: LLMChatInfo) -> FlowyResult<()> {
let store = self.store.read().await.clone();
- info!("[VectorStore]: {} open chat: {:?}", chat_id, model);
+ let chat_id = info.chat_id;
let chat = LLMChat::new(
- *workspace_id,
- *chat_id,
- model,
+ info,
self.client.clone(),
store,
- rag_ids,
+ Some(self.user_service.clone()),
)
.await?;
- self.chat_by_id.insert(*chat_id, chat);
+ self.chat_by_id.insert(chat_id, chat);
Ok(())
}
diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/chat/summary_memory.rs b/frontend/rust-lib/flowy-ai/src/local_ai/chat/summary_memory.rs
new file mode 100644
index 0000000000..b2d2a9403f
--- /dev/null
+++ b/frontend/rust-lib/flowy-ai/src/local_ai/chat/summary_memory.rs
@@ -0,0 +1,124 @@
+use crate::local_ai::chat::llm::LLMOllama;
+use async_trait::async_trait;
+use flowy_ai_pub::user_service::AIUserService;
+use flowy_error::{FlowyError, FlowyResult};
+use langchain_rust::chain::{Chain, LLMChain, LLMChainBuilder};
+use langchain_rust::schemas::{BaseMemory, Message};
+use langchain_rust::{fmt_message, fmt_placeholder, message_formatter, prompt_args};
+use std::sync::{Arc, Weak};
+use tokio::sync::{Mutex, RwLock};
+
+pub struct SummaryMemory {
+ messages: RwLock<Vec<Message>>,
+ chain: SummaryMessageChain,
+ current_summary: String,
+ #[allow(dead_code)]
+ user_service: Option<Weak<dyn AIUserService>>,
+}
+
+impl SummaryMemory {
+ pub async fn new(
+ llm: LLMOllama,
+ summary: String,
+ user_service: Option<Weak<dyn AIUserService>>,
+ ) -> FlowyResult<Self> {
+ let chain = SummaryMessageChain::new(llm)?;
+ Ok(Self {
+ chain,
+ messages: RwLock::new(Vec::new()),
+ current_summary: summary,
+ user_service,
+ })
+ }
+
+ #[allow(dead_code)]
+ pub async fn generate_summary(&mut self) -> FlowyResult<String> {
+ let summary = self
+ .chain
+ .generate_summary(self.messages.read().await.as_ref(), &self.current_summary)
+ .await?;
+
+ self.current_summary = summary.clone();
+ Ok(summary)
+ }
+}
+
+impl From<SummaryMemory> for Arc<dyn BaseMemory> {
+ fn from(memory: SummaryMemory) -> Self {
+ Arc::new(memory)
+ }
+}
+
+impl From<SummaryMemory> for Arc<Mutex<dyn BaseMemory>> {
+ fn from(memory: SummaryMemory) -> Self {
+ Arc::new(Mutex::new(memory))
+ }
+}
+
+#[async_trait]
+impl BaseMemory for SummaryMemory {
+ async fn messages(&self) -> Vec<Message> {
+ self.messages.read().await.clone()
+ }
+ async fn add_message(&mut self, message: Message) {
+ self.messages.write().await.push(message);
+ }
+ async fn clear(&mut self) {
+ self.messages.write().await.clear();
+ }
+}
+
+fn message_to_string_with_role(messages: &[Message]) -> Vec<String> {
+ messages
+ .iter()
+ .map(|msg| format!("{}: {}", msg.message_type.to_string(), msg.content))
+ .collect()
+}
+
+const SUMMARY_SYSTEM_PROMPT: &str = r#"
+You are AppFlowy AI, tasked with progressively summarizing the lines of conversation provided. With each new line, you add to the previous summary and return an updated summary.
+Current summary:
+{current_summary}
+
+New lines of conversation:
+{new_lines}
+
+New summary:
+"#;
+struct SummaryMessageChain {
+ chain: LLMChain,
+}
+
+impl SummaryMessageChain {
+ pub fn new(llm: LLMOllama) -> FlowyResult<Self> {
+ let prompt = message_formatter![
+ fmt_message!(Message::new_system_message(SUMMARY_SYSTEM_PROMPT)),
+ fmt_placeholder!("current_summary"),
+ fmt_placeholder!("new_lines"),
+ ];
+ let chain = LLMChainBuilder::new()
+ .prompt(prompt)
+ .llm(llm)
+ .build()
+ .map_err(|err| FlowyError::internal().with_context(err))?;
+
+ Ok(Self { chain })
+ }
+
+ pub async fn generate_summary(
+ &self,
+ messages: &[Message],
+ current_summary: &str,
+ ) -> FlowyResult<String> {
+ let new_lines = message_to_string_with_role(messages);
+ let resp = self
+ .chain
+ .invoke(prompt_args! {
+ "current_summary" => current_summary,
+ "new_lines" => new_lines,
+ })
+ .await
+ .map_err(|err| FlowyError::internal().with_context(err))?;
+ Ok(resp)
+ }
+}
diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs
index 738207f2c7..9aae9ae4c8 100644
--- a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs
+++ b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs
@@ -10,7 +10,7 @@ use futures::Sink;
use lib_infra::async_trait::async_trait;
use std::collections::HashMap;
-use crate::local_ai::chat::LLMChatController;
+use crate::local_ai::chat::{LLMChatController, LLMChatInfo};
use crate::stream_message::StreamMessage;
use arc_swap::ArcSwapOption;
use flowy_ai_pub::cloud::AIModel;
@@ -191,6 +191,7 @@ impl LocalAIController {
chat_id: &Uuid,
model: &str,
rag_ids: Vec<String>,
+ summary: String,
) -> FlowyResult<()> {
if !self.is_enabled() {
return Ok(());
@@ -203,11 +204,15 @@ impl LocalAIController {
self.close_chat(current_chat_id);
}
+ let info = LLMChatInfo {
+ chat_id: *chat_id,
+ workspace_id: *workspace_id,
+ model: model.to_string(),
+ rag_ids,
+ summary,
+ };
self.current_chat_id.store(Some(Arc::new(*chat_id)));
- self
- .llm_controller
- .open_chat(workspace_id, chat_id, model, rag_ids)
- .await?;
+ self.llm_controller.open_chat(info).await?;
Ok(())
}
diff --git a/frontend/rust-lib/flowy-ai/tests/chat_test/mod.rs b/frontend/rust-lib/flowy-ai/tests/chat_test/mod.rs
index ad02b10033..5a21360781 100644
--- a/frontend/rust-lib/flowy-ai/tests/chat_test/mod.rs
+++ b/frontend/rust-lib/flowy-ai/tests/chat_test/mod.rs
@@ -1,190 +1 @@
-use crate::setup_log;
-use flowy_ai::embeddings::store::SqliteVectorStore;
-use flowy_ai::local_ai::chat::llm::LLMOllama;
-use flowy_ai::local_ai::chat::llm_chat::LLMChat;
-use flowy_ai::local_ai::chat::related_question_chain::RelatedQuestionChain;
-use flowy_ai_pub::cloud::{OutputLayout, QuestionStreamValue, ResponseFormat, StreamAnswer};
-use flowy_ai_pub::entities::{SOURCE, SOURCE_ID, SOURCE_NAME};
-use flowy_sqlite_vec::db::VectorSqliteDB;
-use ollama_rs::Ollama;
-use reqwest::Url;
-use serde_json::Value;
-use std::sync::Arc;
-use tempfile::tempdir;
-use tokio::sync::RwLock;
-use tokio_stream::StreamExt;
-use uuid::Uuid;
-
-pub struct TestContext {
- ollama: Arc<Ollama>,
- store: SqliteVectorStore,
- #[allow(dead_code)]
- db: Arc<VectorSqliteDB>,
- #[allow(dead_code)]
- vector_store: SqliteVectorStore,
-}
-
-impl TestContext {
- pub fn new() -> anyhow::Result<Self> {
- setup_log();
-
- let ollama_url = "http://localhost:11434";
- let url = Url::parse(ollama_url)?;
- let ollama = Arc::new(Ollama::from_url(url.clone()));
-
- let temp_dir = tempdir()?;
- let db = Arc::new(VectorSqliteDB::new(temp_dir.into_path())?);
- let vector_store = SqliteVectorStore::new(Arc::downgrade(&ollama), Arc::downgrade(&db));
-
- Ok(Self {
- ollama,
- store: vector_store.clone(),
- db,
- vector_store,
- })
- }
-
- pub async fn create_chat(&self, rag_ids: Vec<String>) -> LLMChat {
- let workspace_id = Uuid::new_v4();
- let chat_id = Uuid::new_v4();
- let model = "llama3.1";
- let ollama_client = Arc::new(RwLock::new(Some(Arc::downgrade(&self.ollama))));
-
- LLMChat::new(
- workspace_id,
- chat_id,
- model,
- ollama_client,
- Some(self.store.clone()),
- rag_ids,
- )
- .await
- .unwrap()
- }
-}
-
-#[tokio::test]
-async fn local_ollama_test_simple_question() {
- let context = TestContext::new().unwrap();
- let mut chat = context.create_chat(vec![]).await;
- let stream = chat
- .stream_question("hello world", Default::default())
- .await
- .unwrap();
- let result = collect_stream(stream).await;
- dbg!(result);
-}
-
-#[tokio::test]
-async fn local_ollama_test_chat_with_multiple_docs_retrieve() {
- let context = TestContext::new().unwrap();
- let mut chat = context.create_chat(vec![]).await;
- let mut ids = vec![];
-
- for (doc, id) in [("Rust is a multiplayer survival game developed by Facepunch Studios, first released in early access in December 2013 and fully launched in February 2018. It has since become one of the most popular games in the survival genre, known for its harsh environment, intricate crafting system, and player-driven dynamics. The game is available on Windows, macOS, and PlayStation, with a community-driven approach to updates and content additions.", uuid::Uuid::new_v4()),
- ("Rust is a modern, system-level programming language designed with a focus on performance, safety, and concurrency. It was created by Mozilla and first released in 2010, with its 1.0 version launched in 2015. Rust is known for providing the control and performance of languages like C and C++, but with built-in safety features that prevent common programming errors, such as memory leaks, data races, and buffer overflows.", uuid::Uuid::new_v4()),
- ("Rust as a Natural Process (Oxidation) refers to the chemical reaction that occurs when metals, primarily iron, come into contact with oxygen and moisture (water) over time, leading to the formation of iron oxide, commonly known as rust. This process is a form of oxidation, where a substance reacts with oxygen in the air or water, resulting in the degradation of the metal.", uuid::Uuid::new_v4())] {
- ids.push(id.to_string());
- chat.embed_paragraphs(&id.to_string(), vec![doc.to_string()]).await.unwrap();
- }
- chat.set_rag_ids(ids.clone()).await;
-
- let all_docs = chat.get_all_embedded_documents().await.unwrap();
- assert_eq!(all_docs.len(), 3);
- assert_eq!(all_docs[0].fragments.len(), 1);
- assert_eq!(all_docs[1].fragments.len(), 1);
- assert_eq!(all_docs[2].fragments.len(), 1);
-
- let docs = chat
- .search("Rust is a multiplayer survival game", 5, ids.clone())
- .await
- .unwrap();
- assert_eq!(docs.len(), 1);
-
- let docs = chat
- .search(
- "chemical process of rust formation on metal",
- 5,
- ids.clone(),
- )
- .await
- .unwrap();
- assert_eq!(docs.len(), 1);
-
- let stream = chat
- .stream_question("Rust is a multiplayer survival game", Default::default())
- .await
- .unwrap();
- let (answer, sources) = collect_stream(stream).await;
- dbg!(&answer);
- dbg!(&sources);
-
- assert!(!answer.is_empty());
- assert!(!sources.is_empty());
- assert!(sources[0].get(SOURCE_ID).unwrap().as_str().is_some());
- assert!(sources[0].get(SOURCE).unwrap().as_str().is_some());
- assert!(sources[0].get(SOURCE_NAME).unwrap().as_str().is_some());
-
- let stream = chat
- .stream_question("Japan ski resort", Default::default())
- .await
- .unwrap();
- let (answer, _) = collect_stream(stream).await;
- dbg!(&answer);
-}
-
-#[tokio::test]
-async fn local_ollama_test_chat_format() {
- let context = TestContext::new().unwrap();
- let mut chat = context.create_chat(vec![]).await;
- let mut format = ResponseFormat::new();
- format.output_layout = OutputLayout::SimpleTable;
-
- let stream = chat
- .stream_question("Compare rust and js", format)
- .await
- .unwrap();
- let (answer, _) = collect_stream(stream).await;
- dbg!(&answer);
- assert!(!answer.is_empty());
-}
-
-async fn collect_stream(stream: StreamAnswer) -> (String, Vec<Value>) {
- let mut result = String::new();
- let mut sources = vec![];
- let mut stream = stream;
- while let Some(chunk) = stream.next().await {
- match chunk {
- Ok(value) => match value {
- QuestionStreamValue::Answer { value } => {
- result.push_str(&value);
- },
- QuestionStreamValue::Metadata { value } => {
- dbg!("metadata", &value);
- sources.push(value);
- },
- QuestionStreamValue::KeepAlive => {},
- },
- Err(e) => {
- eprintln!("Error: {}", e);
- },
- }
- }
-
- (result, sources)
-}
-
-#[tokio::test]
-async fn local_ollama_test_chat_related_question() {
- setup_log();
-
- let ollama = LLMOllama::default().with_model("llama3.1");
- let chain = RelatedQuestionChain::new(ollama);
- let resp = chain
- .related_question("Compare rust with JS")
- .await
- .unwrap();
-
- dbg!(&resp);
- assert_eq!(resp.len(), 3);
-}
+mod qa_test;
diff --git a/frontend/rust-lib/flowy-ai/tests/chat_test/qa_test.rs b/frontend/rust-lib/flowy-ai/tests/chat_test/qa_test.rs
new file mode 100644
index 0000000000..ec32237faf
--- /dev/null
+++ b/frontend/rust-lib/flowy-ai/tests/chat_test/qa_test.rs
@@ -0,0 +1,133 @@
+use crate::{setup_log, TestContext};
+use flowy_ai::local_ai::chat::llm::LLMOllama;
+use flowy_ai::local_ai::chat::related_question_chain::RelatedQuestionChain;
+use flowy_ai_pub::cloud::{OutputLayout, QuestionStreamValue, ResponseFormat, StreamAnswer};
+use flowy_ai_pub::entities::{SOURCE, SOURCE_ID, SOURCE_NAME};
+use serde_json::Value;
+use tokio_stream::StreamExt;
+
+#[tokio::test]
+async fn local_ollama_test_simple_question() {
+ let context = TestContext::new().unwrap();
+ let mut chat = context.create_chat(vec![]).await;
+ let stream = chat
+ .stream_question("hello world", Default::default())
+ .await
+ .unwrap();
+ let result = collect_stream(stream).await;
+ dbg!(result);
+}
+
+#[tokio::test]
+async fn local_ollama_test_chat_with_multiple_docs_retrieve() {
+ let context = TestContext::new().unwrap();
+ let mut chat = context.create_chat(vec![]).await;
+ let mut ids = vec![];
+
+ for (doc, id) in [("Rust is a multiplayer survival game developed by Facepunch Studios, first released in early access in December 2013 and fully launched in February 2018. It has since become one of the most popular games in the survival genre, known for its harsh environment, intricate crafting system, and player-driven dynamics. The game is available on Windows, macOS, and PlayStation, with a community-driven approach to updates and content additions.", uuid::Uuid::new_v4()),
+ ("Rust is a modern, system-level programming language designed with a focus on performance, safety, and concurrency. It was created by Mozilla and first released in 2010, with its 1.0 version launched in 2015. Rust is known for providing the control and performance of languages like C and C++, but with built-in safety features that prevent common programming errors, such as memory leaks, data races, and buffer overflows.", uuid::Uuid::new_v4()),
+ ("Rust as a Natural Process (Oxidation) refers to the chemical reaction that occurs when metals, primarily iron, come into contact with oxygen and moisture (water) over time, leading to the formation of iron oxide, commonly known as rust. This process is a form of oxidation, where a substance reacts with oxygen in the air or water, resulting in the degradation of the metal.", uuid::Uuid::new_v4())] {
+ ids.push(id.to_string());
+ chat.embed_paragraphs(&id.to_string(), vec![doc.to_string()]).await.unwrap();
+ }
+ chat.set_rag_ids(ids.clone()).await;
+
+ let all_docs = chat.get_all_embedded_documents().await.unwrap();
+ assert_eq!(all_docs.len(), 3);
+ assert_eq!(all_docs[0].fragments.len(), 1);
+ assert_eq!(all_docs[1].fragments.len(), 1);
+ assert_eq!(all_docs[2].fragments.len(), 1);
+
+ let docs = chat
+ .search("Rust is a multiplayer survival game", 5, ids.clone())
+ .await
+ .unwrap();
+ assert_eq!(docs.len(), 1);
+
+ let docs = chat
+ .search(
+ "chemical process of rust formation on metal",
+ 5,
+ ids.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(docs.len(), 1);
+
+ let stream = chat
+ .stream_question("Rust is a multiplayer survival game", Default::default())
+ .await
+ .unwrap();
+ let (answer, sources) = collect_stream(stream).await;
+ dbg!(&answer);
+ dbg!(&sources);
+
+ assert!(!answer.is_empty());
+ assert!(!sources.is_empty());
+ assert!(sources[0].get(SOURCE_ID).unwrap().as_str().is_some());
+ assert!(sources[0].get(SOURCE).unwrap().as_str().is_some());
+ assert!(sources[0].get(SOURCE_NAME).unwrap().as_str().is_some());
+
+ let stream = chat
+ .stream_question("Japan ski resort", Default::default())
+ .await
+ .unwrap();
+ let (answer, _) = collect_stream(stream).await;
+ dbg!(&answer);
+}
+
+#[tokio::test]
+async fn local_ollama_test_chat_format() {
+ let context = TestContext::new().unwrap();
+ let mut chat = context.create_chat(vec![]).await;
+ let mut format = ResponseFormat::new();
+ format.output_layout = OutputLayout::SimpleTable;
+
+ let stream = chat
+ .stream_question("Compare rust and js", format)
+ .await
+ .unwrap();
+ let (answer, _) = collect_stream(stream).await;
+ dbg!(&answer);
+ assert!(!answer.is_empty());
+}
+
+async fn collect_stream(stream: StreamAnswer) -> (String, Vec<Value>) {
+ let mut result = String::new();
+ let mut sources = vec![];
+ let mut stream = stream;
+ while let Some(chunk) = stream.next().await {
+ match chunk {
+ Ok(value) => match value {
+ QuestionStreamValue::Answer { value } => {
+ result.push_str(&value);
+ },
+ QuestionStreamValue::Metadata { value } => {
+ dbg!("metadata", &value);
+ sources.push(value);
+ },
+ QuestionStreamValue::KeepAlive => {},
+ },
+ Err(e) => {
+ eprintln!("Error: {}", e);
+ },
+ }
+ }
+
+ (result, sources)
+}
+
+#[tokio::test]
+async fn local_ollama_test_chat_related_question() {
+ setup_log();
+
+ let ollama = LLMOllama::default().with_model("llama3.1");
+ let chain = RelatedQuestionChain::new(ollama);
+ let resp = chain
+ .related_question("Compare rust with JS")
+ .await
+ .unwrap();
+
+ dbg!(&resp);
+ assert_eq!(resp.len(), 3);
+}
diff --git a/frontend/rust-lib/flowy-ai/tests/main.rs b/frontend/rust-lib/flowy-ai/tests/main.rs
index 00f7ad2d3e..565148a0dd 100644
--- a/frontend/rust-lib/flowy-ai/tests/main.rs
+++ b/frontend/rust-lib/flowy-ai/tests/main.rs
@@ -3,10 +3,19 @@ mod complete_test;
mod summary_test;
mod translate_test;
-use std::sync::Once;
+use flowy_ai::local_ai::chat::llm_chat::LLMChat;
+use flowy_ai::local_ai::chat::LLMChatInfo;
+use flowy_ai::SqliteVectorStore;
+use flowy_sqlite_vec::db::VectorSqliteDB;
+use langchain_rust::url::Url;
+use ollama_rs::Ollama;
+use std::sync::{Arc, Once};
+use tempfile::tempdir;
+use tokio::sync::RwLock;
use tracing_subscriber::fmt::Subscriber;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
+use uuid::Uuid;
pub fn setup_log() {
static START: Once = Once::new();
@@ -23,3 +32,51 @@ pub fn setup_log() {
subscriber.try_init().unwrap();
});
}
+
+pub struct TestContext {
+ ollama: Arc<Ollama>,
+ store: SqliteVectorStore,
+ #[allow(dead_code)]
+ db: Arc<VectorSqliteDB>,
+ #[allow(dead_code)]
+ vector_store: SqliteVectorStore,
+}
+
+impl TestContext {
+ pub fn new() -> anyhow::Result<Self> {
+ setup_log();
+
+ let ollama_url = "http://localhost:11434";
+ let url = Url::parse(ollama_url)?;
+ let ollama = Arc::new(Ollama::from_url(url.clone()));
+
+ let temp_dir = tempdir()?;
+ let db = Arc::new(VectorSqliteDB::new(temp_dir.into_path())?);
+ let vector_store = SqliteVectorStore::new(Arc::downgrade(&ollama), Arc::downgrade(&db));
+
+ Ok(Self {
+ ollama,
+ store: vector_store.clone(),
+ db,
+ vector_store,
+ })
+ }
+
+ pub async fn create_chat(&self, rag_ids: Vec<String>) -> LLMChat {
+ let workspace_id = Uuid::new_v4();
+ let chat_id = Uuid::new_v4();
+ let model = "llama3.1";
+ let ollama_client = Arc::new(RwLock::new(Some(Arc::downgrade(&self.ollama))));
+ let info = LLMChatInfo {
+ chat_id,
+ workspace_id,
+ model: model.to_string(),
+ rag_ids: rag_ids.clone(),
+ summary: "".to_string(),
+ };
+
+ LLMChat::new(info, ollama_client, Some(self.store.clone()), None)
+ .await
+ .unwrap()
+ }
+}
diff --git a/frontend/rust-lib/flowy-server/src/local_server/impls/chat.rs b/frontend/rust-lib/flowy-server/src/local_server/impls/chat.rs
index da5e603c9a..dcf4a3836b 100644
--- a/frontend/rust-lib/flowy-server/src/local_server/impls/chat.rs
+++ b/frontend/rust-lib/flowy-server/src/local_server/impls/chat.rs
@@ -10,10 +10,10 @@ use flowy_ai_pub::cloud::{
StreamComplete, UpdateChatParams, DEFAULT_AI_MODEL_NAME,
};
use flowy_ai_pub::persistence::{
- deserialize_chat_metadata, deserialize_rag_ids, read_chat,
- select_answer_where_match_reply_message_id, select_chat_messages, select_message_content,
- serialize_chat_metadata, serialize_rag_ids, update_chat, upsert_chat, upsert_chat_messages,
- ChatMessageTable, ChatTable, ChatTableChangeset,
+ deserialize_chat_metadata, deserialize_rag_ids, select_answer_where_match_reply_message_id,
+ select_chat, select_chat_messages, select_message_content, serialize_chat_metadata,
+ serialize_rag_ids, update_chat, upsert_chat, upsert_chat_messages, ChatMessageTable, ChatTable,
+ ChatTableChangeset,
};
use flowy_error::{FlowyError, FlowyResult};
use lazy_static::lazy_static;
@@ -252,11 +252,11 @@ impl ChatCloudService for LocalChatServiceImpl {
let chat_id = chat_id.to_string();
let uid = self.logged_user.user_id()?;
let db = self.logged_user.get_sqlite_db(uid)?;
- let row = read_chat(db, &chat_id)?;
+ let row = select_chat(db, &chat_id)?;
let rag_ids = deserialize_rag_ids(&row.rag_ids);
let metadata = deserialize_chat_metadata::<Value>(&row.metadata);
let setting = ChatSettings {
- name: row.name,
+ name: "".to_string(),
rag_ids,
metadata,
};
@@ -271,16 +271,16 @@ impl ChatCloudService for LocalChatServiceImpl {
s: UpdateChatParams,
) -> Result<(), FlowyError> {
let uid = self.logged_user.user_id()?;
- let mut db = self.logged_user.get_sqlite_db(uid)?;
+ let db = self.logged_user.get_sqlite_db(uid)?;
let changeset = ChatTableChangeset {
chat_id: id.to_string(),
- name: s.name,
metadata: s.metadata.map(|s| serialize_chat_metadata(&s)),
rag_ids: s.rag_ids.map(|s| serialize_rag_ids(&s)),
is_sync: None,
+ summary: None,
};
- update_chat(&mut db, changeset)?;
+ update_chat(db, changeset)?;
Ok(())
}
diff --git a/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/down.sql b/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/down.sql
new file mode 100644
index 0000000000..cf41802d04
--- /dev/null
+++ b/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE chat_table
+ ADD COLUMN summary TEXT;
diff --git a/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/up.sql b/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/up.sql
new file mode 100644
index 0000000000..6c550af544
--- /dev/null
+++ b/frontend/rust-lib/flowy-sqlite/migrations/2025-05-06-131915_chat_summary/up.sql
@@ -0,0 +1,5 @@
+-- Your SQL goes here
+ALTER TABLE chat_table
+ ADD COLUMN summary TEXT NOT NULL DEFAULT '';
+
+ALTER TABLE chat_table DROP COLUMN name;
\ No newline at end of file
diff --git a/frontend/rust-lib/flowy-sqlite/src/schema.rs b/frontend/rust-lib/flowy-sqlite/src/schema.rs
index 290f66730b..c5fb956d9e 100644
--- a/frontend/rust-lib/flowy-sqlite/src/schema.rs
+++ b/frontend/rust-lib/flowy-sqlite/src/schema.rs
@@ -35,10 +35,10 @@ diesel::table! {
chat_table (chat_id) {
chat_id -> Text,
created_at -> BigInt,
- name -> Text,
metadata -> Text,
rag_ids -> Nullable<Text>,
is_sync -> Bool,
+ summary -> Text,
}
}