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.

chore: completion stream v2

Nathan6e4206a8e2a5
diff --git a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
index 3c1d5c5a9d..723e11a17f 100644
--- a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
@@ -49,6 +49,9 @@ class AppFlowyAIService implements AIRepository {
onProcess: onProcess,
onEnd: onEnd,
onError: onError,
+ onComment: (String text) async {
+ Log.info('Comment: $text');
+ },
);
final records = history.map((record) => record.toPB()).toList();
@@ -80,12 +83,14 @@ abstract class CompletionStream {
CompletionStream({
required this.onStart,
required this.onProcess,
+ required this.onComment,
required this.onEnd,
required this.onError,
});
final Future<void> Function() onStart;
final Future<void> Function(String text) onProcess;
+ final Future<void> Function(String text) onComment;
final Future<void> Function() onEnd;
final void Function(AIError error) onError;
}
@@ -94,6 +99,7 @@ class AppFlowyCompletionStream extends CompletionStream {
AppFlowyCompletionStream({
required super.onStart,
required super.onProcess,
+ required super.onComment,
required super.onEnd,
required super.onError,
}) {
diff --git a/frontend/rust-lib/Cargo.lock b/frontend/rust-lib/Cargo.lock
index bd95fd24c2..6ec630d09d 100644
--- a/frontend/rust-lib/Cargo.lock
+++ b/frontend/rust-lib/Cargo.lock
@@ -163,7 +163,7 @@ checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7"
[[package]]
name = "app-error"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"bincode",
@@ -183,7 +183,7 @@ dependencies = [
[[package]]
name = "appflowy-ai-client"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"bytes",
@@ -198,7 +198,7 @@ dependencies = [
[[package]]
name = "appflowy-local-ai"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=0136d80eeb4366913203db221b6a4aeae99dccd0#0136d80eeb4366913203db221b6a4aeae99dccd0"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=76d7e7dc885b4d0bd9752aea7ff835de1d48de4e#76d7e7dc885b4d0bd9752aea7ff835de1d48de4e"
dependencies = [
"anyhow",
"appflowy-plugin",
@@ -218,7 +218,7 @@ dependencies = [
[[package]]
name = "appflowy-plugin"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=0136d80eeb4366913203db221b6a4aeae99dccd0#0136d80eeb4366913203db221b6a4aeae99dccd0"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=76d7e7dc885b4d0bd9752aea7ff835de1d48de4e#76d7e7dc885b4d0bd9752aea7ff835de1d48de4e"
dependencies = [
"anyhow",
"cfg-if",
@@ -788,7 +788,7 @@ dependencies = [
[[package]]
name = "client-api"
version = "0.2.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"again",
"anyhow",
@@ -843,7 +843,7 @@ dependencies = [
[[package]]
name = "client-api-entity"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"collab-entity",
"collab-rt-entity",
@@ -856,7 +856,7 @@ dependencies = [
[[package]]
name = "client-websocket"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"futures-channel",
"futures-util",
@@ -1129,7 +1129,7 @@ dependencies = [
[[package]]
name = "collab-rt-entity"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"bincode",
@@ -1151,7 +1151,7 @@ dependencies = [
[[package]]
name = "collab-rt-protocol"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"async-trait",
@@ -1546,7 +1546,7 @@ checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308"
[[package]]
name = "database-entity"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"bincode",
"bytes",
@@ -2979,7 +2979,7 @@ dependencies = [
[[package]]
name = "gotrue"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"getrandom 0.2.10",
@@ -2994,7 +2994,7 @@ dependencies = [
[[package]]
name = "gotrue-entity"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"app-error",
"jsonwebtoken",
@@ -3609,7 +3609,7 @@ dependencies = [
[[package]]
name = "infra"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"bytes",
@@ -6176,7 +6176,7 @@ dependencies = [
[[package]]
name = "shared-entity"
version = "0.1.0"
-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=1634d17dd48488f6b55a7e0b874390343f18ebbf#1634d17dd48488f6b55a7e0b874390343f18ebbf"
+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=9587c0680f70a58d45c9bb012811bc702df5d213#9587c0680f70a58d45c9bb012811bc702df5d213"
dependencies = [
"anyhow",
"app-error",
diff --git a/frontend/rust-lib/Cargo.toml b/frontend/rust-lib/Cargo.toml
index eb94443c09..fd4b19f6ec 100644
--- a/frontend/rust-lib/Cargo.toml
+++ b/frontend/rust-lib/Cargo.toml
@@ -103,8 +103,8 @@ dashmap = "6.0.1"
# Run the script.add_workspace_members:
# scripts/tool/update_client_api_rev.sh new_rev_id
# ⚠️⚠️⚠️️
-client-api = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "1634d17dd48488f6b55a7e0b874390343f18ebbf" }
-client-api-entity = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "1634d17dd48488f6b55a7e0b874390343f18ebbf" }
+client-api = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "9587c0680f70a58d45c9bb012811bc702df5d213" }
+client-api-entity = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "9587c0680f70a58d45c9bb012811bc702df5d213" }
[profile.dev]
opt-level = 0
@@ -152,5 +152,5 @@ collab-importer = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFl
# To update the commit ID, run:
# scripts/tool/update_local_ai_rev.sh new_rev_id
# ⚠️⚠️⚠️️
-appflowy-local-ai = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "0136d80eeb4366913203db221b6a4aeae99dccd0" }
-appflowy-plugin = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "0136d80eeb4366913203db221b6a4aeae99dccd0" }
+appflowy-local-ai = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "76d7e7dc885b4d0bd9752aea7ff835de1d48de4e" }
+appflowy-plugin = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "76d7e7dc885b4d0bd9752aea7ff835de1d48de4e" }
diff --git a/frontend/rust-lib/flowy-ai-pub/src/cloud.rs b/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
index 2043c123c0..d0107831ee 100644
--- a/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
+++ b/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
@@ -1,8 +1,7 @@
-use bytes::Bytes;
pub use client_api::entity::ai_dto::{
- AppFlowyOfflineAI, CompleteTextParams, CompletionMetadata, CompletionRecord, CompletionType,
- CreateChatContext, LLMModel, LocalAIConfig, ModelInfo, ModelList, OutputContent, OutputLayout,
- RelatedQuestion, RepeatedRelatedQuestion, ResponseFormat, StringOrMessage,
+ AppFlowyOfflineAI, CompleteTextParams, CompletionMessage, CompletionMetadata, CompletionType,
+ CreateChatContext, CustomPrompt, LLMModel, LocalAIConfig, ModelInfo, ModelList, OutputContent,
+ OutputLayout, RelatedQuestion, RepeatedRelatedQuestion, ResponseFormat, StringOrMessage,
};
pub use client_api::entity::billing_dto::SubscriptionPlan;
pub use client_api::entity::chat_dto::{
@@ -10,7 +9,8 @@ pub use client_api::entity::chat_dto::{
MessageCursor, RepeatedChatMessage, UpdateChatParams,
};
pub use client_api::entity::QuestionStreamValue;
-use client_api::error::AppResponseError;
+pub use client_api::entity::*;
+pub use client_api::error::{AppResponseError, ErrorCode as AppErrorCode};
use flowy_error::FlowyError;
use futures::stream::BoxStream;
use lib_infra::async_trait::async_trait;
@@ -20,7 +20,7 @@ use std::path::Path;
pub type ChatMessageStream = BoxStream<'static, Result<ChatMessage, AppResponseError>>;
pub type StreamAnswer = BoxStream<'static, Result<QuestionStreamValue, FlowyError>>;
-pub type StreamComplete = BoxStream<'static, Result<Bytes, FlowyError>>;
+pub type StreamComplete = BoxStream<'static, Result<CompletionStreamValue, FlowyError>>;
#[async_trait]
pub trait ChatCloudService: Send + Sync + 'static {
async fn create_chat(
diff --git a/frontend/rust-lib/flowy-ai/src/completion.rs b/frontend/rust-lib/flowy-ai/src/completion.rs
index 4ed073f0ca..fa79308b4f 100644
--- a/frontend/rust-lib/flowy-ai/src/completion.rs
+++ b/frontend/rust-lib/flowy-ai/src/completion.rs
@@ -4,7 +4,8 @@ use allo_isolate::Isolate;
use dashmap::DashMap;
use flowy_ai_pub::cloud::{
- ChatCloudService, CompleteTextParams, CompletionMetadata, CompletionType,
+ ChatCloudService, CompleteTextParams, CompletionMetadata, CompletionStreamValue, CompletionType,
+ CustomPrompt,
};
use flowy_error::{FlowyError, FlowyResult};
@@ -37,6 +38,15 @@ impl AICompletion {
&self,
complete: CompleteTextPB,
) -> FlowyResult<CompleteTextTaskPB> {
+ if matches!(complete.completion_type, CompletionTypePB::CustomPrompt)
+ && complete.custom_prompt.is_none()
+ {
+ return Err(
+ FlowyError::invalid_data()
+ .with_context("custom_prompt is required when completion_type is CustomPrompt"),
+ );
+ }
+
let workspace_id = self
.user_service
.upgrade()
@@ -95,6 +105,7 @@ impl CompletionTask {
CompletionTypePB::ContinueWriting => CompletionType::ContinueWriting,
CompletionTypePB::ExplainSelected => CompletionType::Explain,
CompletionTypePB::UserQuestion => CompletionType::UserQuestion,
+ CompletionTypePB::CustomPrompt => CompletionType::CustomPrompt,
};
let _ = sink.send("start:".to_string()).await;
@@ -103,12 +114,15 @@ impl CompletionTask {
let params = CompleteTextParams {
text: self.context.text,
completion_type: Some(complete_type),
- custom_prompt: None,
metadata: Some(CompletionMetadata {
object_id: self.context.object_id,
workspace_id: Some(self.workspace_id.clone()),
rag_ids: Some(self.context.rag_ids),
completion_history,
+ custom_prompt: self
+ .context
+ .custom_prompt
+ .map(|v| CustomPrompt { system: v }),
}),
format,
};
@@ -124,20 +138,26 @@ impl CompletionTask {
return;
},
result = stream.next() => {
- match result {
- Some(Ok(data)) => {
- let s = String::from_utf8(data.to_vec()).unwrap_or_default();
- let _ = sink.send(format!("data:{}", s)).await;
- },
- Some(Err(error)) => {
- handle_error(&mut sink, error).await;
- return;
- },
- None => {
- let _ = sink.send(format!("finish:{}", self.task_id)).await;
- return;
- },
- }
+ match result {
+ Some(Ok(data)) => {
+ match data {
+ CompletionStreamValue::Answer{ value } => {
+ let _ = sink.send(format!("data:{}", value)).await;
+ }
+ CompletionStreamValue::Comment{ value } => {
+ let _ = sink.send(format!("comment:{}", value)).await;
+ }
+ }
+ },
+ Some(Err(error)) => {
+ handle_error(&mut sink, error).await;
+ return;
+ },
+ None => {
+ let _ = sink.send(format!("finish:{}", self.task_id)).await;
+ return;
+ },
+ }
}
}
},
diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rs
index 4b5e91db11..70a8b5ff58 100644
--- a/frontend/rust-lib/flowy-ai/src/entities.rs
+++ b/frontend/rust-lib/flowy-ai/src/entities.rs
@@ -4,7 +4,7 @@ use std::collections::HashMap;
use crate::local_ai::controller::LocalAISetting;
use crate::local_ai::resource::PendingResource;
use flowy_ai_pub::cloud::{
- ChatMessage, ChatMessageMetadata, ChatMessageType, CompletionRecord, LLMModel, OutputContent,
+ ChatMessage, ChatMessageMetadata, ChatMessageType, CompletionMessage, LLMModel, OutputContent,
OutputLayout, RelatedQuestion, RepeatedChatMessage, RepeatedRelatedQuestion, ResponseFormat,
};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
@@ -361,6 +361,9 @@ pub struct CompleteTextPB {
#[pb(index = 7)]
pub history: Vec<CompletionRecordPB>,
+
+ #[pb(index = 8, one_of)]
+ pub custom_prompt: Option<String>,
}
#[derive(Default, ProtoBuf, Clone, Debug)]
@@ -379,6 +382,7 @@ pub enum CompletionTypePB {
ImproveWriting = 4,
MakeShorter = 5,
MakeLonger = 6,
+ CustomPrompt = 7,
}
#[derive(Default, ProtoBuf, Clone, Debug)]
@@ -390,9 +394,9 @@ pub struct CompletionRecordPB {
pub content: String,
}
-impl From<&CompletionRecordPB> for CompletionRecord {
+impl From<&CompletionRecordPB> for CompletionMessage {
fn from(value: &CompletionRecordPB) -> Self {
- CompletionRecord {
+ CompletionMessage {
role: match value.role {
// Coerce ChatMessageTypePB::System to AI
ChatMessageTypePB::System => "ai".to_string(),
diff --git a/frontend/rust-lib/flowy-ai/src/middleware/chat_service_mw.rs b/frontend/rust-lib/flowy-ai/src/middleware/chat_service_mw.rs
index d03b1d88c2..8e69f14d20 100644
--- a/frontend/rust-lib/flowy-ai/src/middleware/chat_service_mw.rs
+++ b/frontend/rust-lib/flowy-ai/src/middleware/chat_service_mw.rs
@@ -9,10 +9,10 @@ use appflowy_plugin::error::PluginError;
use std::collections::HashMap;
use flowy_ai_pub::cloud::{
- ChatCloudService, ChatMessage, ChatMessageMetadata, ChatMessageType, ChatSettings,
- CompleteTextParams, LocalAIConfig, MessageCursor, ModelList, RelatedQuestion,
- RepeatedChatMessage, RepeatedRelatedQuestion, ResponseFormat, StreamAnswer, StreamComplete,
- SubscriptionPlan, UpdateChatParams,
+ AppErrorCode, AppResponseError, ChatCloudService, ChatMessage, ChatMessageMetadata,
+ ChatMessageType, ChatSettings, CompleteTextParams, CompletionStream, LocalAIConfig,
+ MessageCursor, ModelList, RelatedQuestion, RepeatedChatMessage, RepeatedRelatedQuestion,
+ ResponseFormat, StreamAnswer, StreamComplete, SubscriptionPlan, UpdateChatParams,
};
use flowy_error::{FlowyError, FlowyResult};
use futures::{stream, Sink, StreamExt, TryStreamExt};
@@ -194,7 +194,6 @@ impl ChatCloudService for AICloudServiceMiddleware {
let content = self.get_message_record(question_message_id)?.content;
match self.local_ai.ask_question(chat_id, &content).await {
Ok(answer) => {
- // TODO(nathan): metadata
let message = self
.cloud_service
.create_answer(workspace_id, chat_id, &answer, question_message_id, None)
@@ -278,17 +277,20 @@ impl ChatCloudService for AICloudServiceMiddleware {
if self.local_ai.is_running() {
match self
.local_ai
- .complete_text(
+ .complete_text_v2(
&params.text,
params.completion_type.unwrap() as u8,
Some(json!(params.format)),
+ Some(json!(params.metadata)),
)
.await
{
Ok(stream) => Ok(
- stream
- .map_err(|err| FlowyError::local_ai().with_context(err))
- .boxed(),
+ CompletionStream::new(
+ stream.map_err(|err| AppResponseError::new(AppErrorCode::Internal, err.to_string())),
+ )
+ .map_err(FlowyError::from)
+ .boxed(),
),
Err(err) => {
self.handle_plugin_error(err);
diff --git a/frontend/rust-lib/flowy-server/src/af_cloud/impls/chat.rs b/frontend/rust-lib/flowy-server/src/af_cloud/impls/chat.rs
index c7077dc061..5417f06a65 100644
--- a/frontend/rust-lib/flowy-server/src/af_cloud/impls/chat.rs
+++ b/frontend/rust-lib/flowy-server/src/af_cloud/impls/chat.rs
@@ -193,7 +193,7 @@ where
let stream = self
.inner
.try_get_client()?
- .stream_completion_text(workspace_id, params)
+ .stream_completion_v2(workspace_id, params)
.await
.map_err(FlowyError::from)?
.map_err(FlowyError::from);