From 85e39095f728fec9b5ffb88813fdbe3a01fb94be Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sat, 25 May 2024 09:01:55 +0800 Subject: [PATCH 01/16] refactor: chat --- lib/llm/ai_assistant_screen.dart | 15 ++++--- lib/llm/chatchat/chatchat_screen.dart | 16 ++++++-- lib/llm/chatchat/components/chat_ui.dart | 28 +++++++++---- .../chatchat/notifiers/history_notifier.dart | 15 ++++--- .../components/history_item_widget.dart | 17 ++++++-- lib/llm/global/components/history_list.dart | 9 ++++- .../components/suggestion_item_widget.dart | 9 ++++- lib/llm/langchain/components/chat_ui.dart | 39 ++++++++++++------- 8 files changed, 103 insertions(+), 45 deletions(-) diff --git a/lib/llm/ai_assistant_screen.dart b/lib/llm/ai_assistant_screen.dart index d710ad3..7a9a88d 100644 --- a/lib/llm/ai_assistant_screen.dart +++ b/lib/llm/ai_assistant_screen.dart @@ -32,18 +32,23 @@ class AIAssistantScreen extends ConsumerWidget { } } -class _UI extends StatelessWidget { +class _UI extends ConsumerWidget { const _UI(); @override - Widget build(BuildContext context) { - return const Row( + Widget build(BuildContext context, WidgetRef ref) { + final chatTag = ref.read(toolProvider)?.name; + return Row( children: [ HistoryList( llmType: LLMType.openai, - bottom: Buttons(), + bottom: const Buttons(), + chatTag: chatTag ?? "随便聊聊", ), - Expanded(child: ChatUI()) + Expanded( + child: ChatUI( + chatTag: chatTag ?? "随便聊聊", + )) ], ); } diff --git a/lib/llm/chatchat/chatchat_screen.dart b/lib/llm/chatchat/chatchat_screen.dart index 1ebac0e..8da5b42 100644 --- a/lib/llm/chatchat/chatchat_screen.dart +++ b/lib/llm/chatchat/chatchat_screen.dart @@ -1,22 +1,30 @@ import 'package:all_in_one/isar/llm_history.dart'; import 'package:all_in_one/llm/chatchat/chatchat_config.dart'; import 'package:all_in_one/llm/global/components/history_list.dart'; +import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'components/chat_ui.dart'; -class ChatChatScreen extends StatelessWidget { +class ChatChatScreen extends ConsumerWidget { const ChatChatScreen({super.key}); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final chatTag = ref.read(toolProvider)?.name; return Scaffold( body: Row( children: [ - const HistoryList( + HistoryList( llmType: LLMType.chatchat, + chatTag: chatTag ?? "随便聊聊", ), - Expanded(child: ChatUI(config: ChatchatConfig())) + Expanded( + child: ChatUI( + config: ChatchatConfig(), + chatTag: chatTag ?? "随便聊聊", + )) ], ), ); diff --git a/lib/llm/chatchat/components/chat_ui.dart b/lib/llm/chatchat/components/chat_ui.dart index 5f71d37..4cf55ab 100644 --- a/lib/llm/chatchat/components/chat_ui.dart +++ b/lib/llm/chatchat/components/chat_ui.dart @@ -18,8 +18,9 @@ import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'input_field.dart'; class ChatUI extends ConsumerStatefulWidget { - const ChatUI({super.key, required this.config}); + const ChatUI({super.key, required this.config, required this.chatTag}); final ChatchatConfig config; + final String chatTag; @override ConsumerState createState() => _ChatUIState(); @@ -44,11 +45,17 @@ class _ChatUIState extends ConsumerState { WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { if (mounted) { - while (ref.read(historyProvider(LLMType.chatchat)).value == null) { + while (ref + .read(historyProvider((LLMType.chatchat, widget.chatTag))) + .value == + null) { await Future.delayed(const Duration(milliseconds: 10)); } - id = ref.watch(historyProvider(LLMType.chatchat)).value!.current; + id = ref + .watch(historyProvider((LLMType.chatchat, widget.chatTag))) + .value! + .current; } }); @@ -125,13 +132,18 @@ class _ChatUIState extends ConsumerState { .addMessageBox(RequestMessageBox(content: s)); if (id == 0) { - await ref.read(historyProvider(LLMType.chatchat).notifier).newHistory(s); - - id = ref.read(historyProvider(LLMType.chatchat)).value!.current; + await ref + .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) + .newHistory(s); + + id = ref + .read(historyProvider((LLMType.chatchat, widget.chatTag))) + .value! + .current; } ref - .read(historyProvider(LLMType.chatchat).notifier) + .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) .updateHistory(id, s, MessageType.query); if (widget.config.stream) { @@ -160,7 +172,7 @@ class _ChatUIState extends ConsumerState { final last = ref.read(messageProvider).messageBox.last; ref - .read(historyProvider(LLMType.chatchat).notifier) + .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) .updateHistory(id, last.content, MessageType.response); }, onError: (e) { if (kDebugMode) { diff --git a/lib/llm/chatchat/notifiers/history_notifier.dart b/lib/llm/chatchat/notifiers/history_notifier.dart index d598259..db833c6 100644 --- a/lib/llm/chatchat/notifiers/history_notifier.dart +++ b/lib/llm/chatchat/notifiers/history_notifier.dart @@ -9,7 +9,7 @@ import 'history_state.dart'; import 'message_notifier.dart'; class HistoryNotifier - extends AutoDisposeFamilyAsyncNotifier { + extends AutoDisposeFamilyAsyncNotifier { final IsarDatabase database = IsarDatabase(); Future newHistory(String title, {String chatTag = "随便聊聊"}) async { @@ -24,7 +24,8 @@ class HistoryNotifier state = await AsyncValue.guard(() async { final total = await database.isar!.lLMHistorys .filter() - .llmTypeEqualTo(arg) + .llmTypeEqualTo(arg.$1) + .chatTagEqualTo(arg.$2) .offset(0) .limit(30) .findAll(); @@ -60,7 +61,8 @@ class HistoryNotifier state = await AsyncValue.guard(() async { final total = await database.isar!.lLMHistorys .filter() - .llmTypeEqualTo(arg) + .llmTypeEqualTo(arg.$1) + .chatTagEqualTo(arg.$2) .offset(0) .limit(30) .findAll(); @@ -90,10 +92,11 @@ class HistoryNotifier } @override - FutureOr build(LLMType arg) async { + FutureOr build((LLMType, String) arg) async { final history = await database.isar!.lLMHistorys .filter() - .llmTypeEqualTo(arg) + .llmTypeEqualTo(arg.$1) + .chatTagEqualTo(arg.$2) .offset(0) .limit(30) .findAll(); @@ -116,4 +119,4 @@ class HistoryNotifier } final historyProvider = AutoDisposeAsyncNotifierProvider.family(() => HistoryNotifier()); + HistoryState, (LLMType, String)>(() => HistoryNotifier()); diff --git a/lib/llm/global/components/history_item_widget.dart b/lib/llm/global/components/history_item_widget.dart index 3eb687a..d52a26d 100644 --- a/lib/llm/global/components/history_item_widget.dart +++ b/lib/llm/global/components/history_item_widget.dart @@ -7,9 +7,13 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; class HistoryListWidget extends ConsumerStatefulWidget { const HistoryListWidget( - {super.key, required this.history, required this.llmType}); + {super.key, + required this.history, + required this.llmType, + required this.chatTag}); final LLMHistory history; final LLMType llmType; + final String chatTag; @override ConsumerState createState() => _HistoryListWidgetState(); @@ -34,14 +38,18 @@ class _HistoryListWidgetState extends ConsumerState { child: InkWell( onTap: () { ref - .read(historyProvider(widget.llmType).notifier) + .read(historyProvider((widget.llmType, widget.chatTag)).notifier) .refresh(widget.history.id); }, child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), - color: ref.read(historyProvider(widget.llmType)).value?.current == + color: ref + .read( + historyProvider((widget.llmType, widget.chatTag))) + .value + ?.current == widget.history.id ? const Color.fromARGB(255, 197, 195, 227) : isHovering @@ -78,7 +86,8 @@ class _HistoryListWidgetState extends ConsumerState { onTap: () { // 删除数据 ref - .read(historyProvider(widget.llmType).notifier) + .read(historyProvider((widget.llmType, widget.chatTag)) + .notifier) .delete(widget.history.id); ref.read(messageProvider.notifier).refresh([]); diff --git a/lib/llm/global/components/history_list.dart b/lib/llm/global/components/history_list.dart index 1b607c3..abb2804 100644 --- a/lib/llm/global/components/history_list.dart +++ b/lib/llm/global/components/history_list.dart @@ -10,9 +10,11 @@ import 'history_item_widget.dart'; import 'suggestion_item_widget.dart'; class HistoryList extends ConsumerStatefulWidget { - const HistoryList({super.key, required this.llmType, this.bottom}); + const HistoryList( + {super.key, required this.llmType, this.bottom, required this.chatTag}); final LLMType llmType; final Widget? bottom; + final String chatTag; @override ConsumerState createState() => _HistoryListState(); @@ -27,7 +29,8 @@ class _HistoryListState extends ConsumerState { @override Widget build(BuildContext context) { - final notifier = ref.watch(historyProvider(llmType)); + final notifier = + ref.watch(historyProvider((widget.llmType, widget.chatTag))); return Container( width: 300, @@ -56,6 +59,7 @@ class _HistoryListState extends ConsumerState { history: value.history[index], llmType: llmType, boxController: boxController, + chatTag: widget.chatTag, ); }, // textController: textController, @@ -77,6 +81,7 @@ class _HistoryListState extends ConsumerState { return HistoryListWidget( history: value.history[i], llmType: llmType, + chatTag: widget.chatTag, ); })), bottom ?? const SizedBox() diff --git a/lib/llm/global/components/suggestion_item_widget.dart b/lib/llm/global/components/suggestion_item_widget.dart index f083cde..636ae66 100644 --- a/lib/llm/global/components/suggestion_item_widget.dart +++ b/lib/llm/global/components/suggestion_item_widget.dart @@ -10,9 +10,11 @@ class SuggestionItemWidget extends ConsumerStatefulWidget { {super.key, required this.history, required this.llmType, - required this.boxController}); + required this.boxController, + required this.chatTag}); final LLMHistory history; final LLMType llmType; + final String chatTag; final BoxController boxController; @override @@ -71,7 +73,10 @@ class _SuggestionItemWidgetState extends ConsumerState { ), ], )), - if (ref.read(historyProvider(widget.llmType)).value?.current == + if (ref + .read(historyProvider((widget.llmType, widget.chatTag))) + .value + ?.current == widget.history.id) const Icon( Icons.star, diff --git a/lib/llm/langchain/components/chat_ui.dart b/lib/llm/langchain/components/chat_ui.dart index 4784206..bc40c08 100644 --- a/lib/llm/langchain/components/chat_ui.dart +++ b/lib/llm/langchain/components/chat_ui.dart @@ -15,7 +15,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; class ChatUI extends ConsumerStatefulWidget { - const ChatUI({super.key}); + const ChatUI({super.key, required this.chatTag}); + final String chatTag; @override ConsumerState createState() => _ChatUIState(); @@ -28,14 +29,16 @@ class _ChatUIState extends ConsumerState { @override void initState() { super.initState(); + llmStream.listen((event) { // print(event.content); if (event.content == "!over!") { final last = ref.read(messageProvider).messageBox.last; - ref.read(historyProvider(LLMType.chatchat).notifier).updateHistory( - id, last.content, MessageType.response, - roleType: event.type); + ref + .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) + .updateHistory(id, last.content, MessageType.response, + roleType: event.type); } else { final res = LLMResponse(messageId: event.uuid, text: event.content); ref.read(messageProvider.notifier).updateMessageBox(res); @@ -47,15 +50,21 @@ class _ChatUIState extends ConsumerState { @override Widget build(BuildContext context) { + print(widget.chatTag); final state = ref.watch(messageProvider); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { if (mounted) { - while (ref.read(historyProvider(LLMType.openai)).value == null) { + while ( + ref.read(historyProvider((LLMType.openai, widget.chatTag))).value == + null) { await Future.delayed(const Duration(milliseconds: 10)); } - id = ref.watch(historyProvider(LLMType.openai)).value!.current; + id = ref + .watch(historyProvider((LLMType.openai, widget.chatTag))) + .value! + .current; } }); @@ -128,17 +137,19 @@ class _ChatUIState extends ConsumerState { .read(messageProvider.notifier) .addMessageBox(RequestMessageBox(content: s)); if (id == 0) { - await ref.read(historyProvider(LLMType.openai).notifier).newHistory(s, - chatTag: model == null || model.toMessage()!.content == "normal" - ? "随便聊聊" - : model.name); - - id = ref.read(historyProvider(LLMType.openai)).value!.current; + await ref + .read(historyProvider((LLMType.openai, widget.chatTag)).notifier) + .newHistory(s, chatTag: widget.chatTag); + + id = ref + .read(historyProvider((LLMType.openai, widget.chatTag))) + .value! + .current; } // 根据id获取 config中定义的history长度的message final messages = ref - .read(historyProvider(LLMType.openai).notifier) + .read(historyProvider((LLMType.openai, widget.chatTag)).notifier) .getMessages(config.historyLength, id); List history; @@ -160,7 +171,7 @@ class _ChatUIState extends ConsumerState { } ref - .read(historyProvider(LLMType.openai).notifier) + .read(historyProvider((LLMType.openai, widget.chatTag)).notifier) .updateHistory(id, s, MessageType.query); llm.chat(stream: true, query: s, history: history); } From 2099b22d0cfe57f125919e7dadd7bc2bb5904f5a Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sat, 25 May 2024 21:43:46 +0800 Subject: [PATCH 02/16] refactor: editor(WIP) move `article template` to editor (WIP) --- lib/isar/llm_template.dart | 1 + lib/isar/llm_template.g.dart | 203 ++++++++- lib/llm/editor/compose_screen.dart | 173 ++++++-- lib/llm/global/components/sidemenu.dart | 46 ++ .../global/components/sidemenu_widget.dart | 67 +++ lib/llm/global/models/sidemenu_item.dart | 9 + .../notifiers/chain_flow_notifier.dart | 37 ++ lib/llm/template_editor/template_editor.dart | 397 +++++++++++------- lib/tool_entry/routers/routers.dart | 4 +- pubspec.lock | 8 + pubspec.yaml | 1 + 11 files changed, 735 insertions(+), 211 deletions(-) create mode 100644 lib/llm/global/components/sidemenu.dart create mode 100644 lib/llm/global/components/sidemenu_widget.dart create mode 100644 lib/llm/global/models/sidemenu_item.dart diff --git a/lib/isar/llm_template.dart b/lib/isar/llm_template.dart index 89654ef..84b5bf5 100644 --- a/lib/isar/llm_template.dart +++ b/lib/isar/llm_template.dart @@ -8,4 +8,5 @@ class LlmTemplate { int createAt = DateTime.now().millisecondsSinceEpoch; late String name; late String template; + late String chains = ""; } diff --git a/lib/isar/llm_template.g.dart b/lib/isar/llm_template.g.dart index 26dda67..98c23f7 100644 --- a/lib/isar/llm_template.g.dart +++ b/lib/isar/llm_template.g.dart @@ -17,18 +17,23 @@ const LlmTemplateSchema = CollectionSchema( name: r'LlmTemplate', id: -7349507314354301866, properties: { - r'createAt': PropertySchema( + r'chains': PropertySchema( id: 0, + name: r'chains', + type: IsarType.string, + ), + r'createAt': PropertySchema( + id: 1, name: r'createAt', type: IsarType.long, ), r'name': PropertySchema( - id: 1, + id: 2, name: r'name', type: IsarType.string, ), r'template': PropertySchema( - id: 2, + id: 3, name: r'template', type: IsarType.string, ) @@ -53,6 +58,7 @@ int _llmTemplateEstimateSize( Map> allOffsets, ) { var bytesCount = offsets.last; + bytesCount += 3 + object.chains.length * 3; bytesCount += 3 + object.name.length * 3; bytesCount += 3 + object.template.length * 3; return bytesCount; @@ -64,9 +70,10 @@ void _llmTemplateSerialize( List offsets, Map> allOffsets, ) { - writer.writeLong(offsets[0], object.createAt); - writer.writeString(offsets[1], object.name); - writer.writeString(offsets[2], object.template); + writer.writeString(offsets[0], object.chains); + writer.writeLong(offsets[1], object.createAt); + writer.writeString(offsets[2], object.name); + writer.writeString(offsets[3], object.template); } LlmTemplate _llmTemplateDeserialize( @@ -76,10 +83,11 @@ LlmTemplate _llmTemplateDeserialize( Map> allOffsets, ) { final object = LlmTemplate(); - object.createAt = reader.readLong(offsets[0]); + object.chains = reader.readString(offsets[0]); + object.createAt = reader.readLong(offsets[1]); object.id = id; - object.name = reader.readString(offsets[1]); - object.template = reader.readString(offsets[2]); + object.name = reader.readString(offsets[2]); + object.template = reader.readString(offsets[3]); return object; } @@ -91,11 +99,13 @@ P _llmTemplateDeserializeProp

( ) { switch (propertyId) { case 0: - return (reader.readLong(offset)) as P; - case 1: return (reader.readString(offset)) as P; + case 1: + return (reader.readLong(offset)) as P; case 2: return (reader.readString(offset)) as P; + case 3: + return (reader.readString(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } @@ -194,6 +204,140 @@ extension LlmTemplateQueryWhere extension LlmTemplateQueryFilter on QueryBuilder { + QueryBuilder chainsEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chainsGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chainsLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chainsBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'chains', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chainsStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chainsEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chainsContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'chains', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chainsMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'chains', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chainsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chains', + value: '', + )); + }); + } + + QueryBuilder + chainsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'chains', + value: '', + )); + }); + } + QueryBuilder createAtEqualTo( int value) { return QueryBuilder.apply(this, (query) { @@ -577,6 +721,18 @@ extension LlmTemplateQueryLinks extension LlmTemplateQuerySortBy on QueryBuilder { + QueryBuilder sortByChains() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chains', Sort.asc); + }); + } + + QueryBuilder sortByChainsDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chains', Sort.desc); + }); + } + QueryBuilder sortByCreateAt() { return QueryBuilder.apply(this, (query) { return query.addSortBy(r'createAt', Sort.asc); @@ -616,6 +772,18 @@ extension LlmTemplateQuerySortBy extension LlmTemplateQuerySortThenBy on QueryBuilder { + QueryBuilder thenByChains() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chains', Sort.asc); + }); + } + + QueryBuilder thenByChainsDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chains', Sort.desc); + }); + } + QueryBuilder thenByCreateAt() { return QueryBuilder.apply(this, (query) { return query.addSortBy(r'createAt', Sort.asc); @@ -667,6 +835,13 @@ extension LlmTemplateQuerySortThenBy extension LlmTemplateQueryWhereDistinct on QueryBuilder { + QueryBuilder distinctByChains( + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'chains', caseSensitive: caseSensitive); + }); + } + QueryBuilder distinctByCreateAt() { return QueryBuilder.apply(this, (query) { return query.addDistinctBy(r'createAt'); @@ -696,6 +871,12 @@ extension LlmTemplateQueryProperty }); } + QueryBuilder chainsProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'chains'); + }); + } + QueryBuilder createAtProperty() { return QueryBuilder.apply(this, (query) { return query.addPropertyName(r'createAt'); diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 7c6e609..01bf06e 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -2,23 +2,31 @@ import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; +import 'package:all_in_one/isar/llm_history.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; +import 'package:all_in_one/llm/global/components/sidemenu.dart'; +import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:all_in_one/llm/plugins/mind_map.dart'; import 'package:all_in_one/llm/plugins/models/mind_map_model.dart'; +import 'package:all_in_one/llm/plugins/record/record_utils.dart'; +import 'package:all_in_one/llm/template_editor/components/loading_dialog.dart'; import 'package:all_in_one/llm/template_editor/extension.dart'; +import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; +import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_expandable_fab/flutter_expandable_fab.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icons_plus/icons_plus.dart'; import 'package:uuid/uuid.dart'; import 'editor.dart'; import 'notifiers/editor_notifier.dart'; class ComposeScreen extends ConsumerStatefulWidget { - const ComposeScreen({super.key}); + const ComposeScreen({super.key, this.enablePlugin = true}); + final bool enablePlugin; @override ConsumerState createState() => _ComposeScreenState(); @@ -30,6 +38,7 @@ class _ComposeScreenState extends ConsumerState { late WidgetBuilder _widgetBuilder; final uuid = const Uuid(); late String result = ""; + bool isTemplateLoaded = false; late Stream toMapStream = mindMapStream(); @@ -80,51 +89,131 @@ class _ComposeScreenState extends ConsumerState { @override Widget build(BuildContext context) { return Scaffold( - floatingActionButtonLocation: ExpandableFab.location, - floatingActionButton: ExpandableFab( - distance: 50, - type: ExpandableFabType.side, + extendBodyBehindAppBar: PlatformExtension.isDesktopOrWeb, + body: SafeArea( + child: Row( children: [ - FloatingActionButton.small( - tooltip: "save article", - heroTag: "save", - onPressed: () { - ref - .read(editorNotifierProvider.notifier) - .createArticle( - _editorState.toStr2().split("\n").firstOrNull ?? - "unknow-${uuid.v4()}", - jsonEncode(_editorState.document.toJson())) - .then((_) { - ToastUtils.sucess(context, title: "Insert success"); - }, onError: (_) { - ToastUtils.error(context, title: "Insert error"); - }); - }, - child: const Icon(Icons.save), - ), - FloatingActionButton.small( - tooltip: "mind-map", - heroTag: "", - onPressed: () { - final s = _editorState.toStr2(); + Sidemenu( + items: [ + SidemenuLabel(title: "Article"), + SidemenuButton( + icon: Icons.save, + title: "Save article", + onTap: () { + ref + .read(editorNotifierProvider.notifier) + .createArticle( + _editorState.toStr2().split("\n").firstOrNull ?? + "unknow-${uuid.v4()}", + jsonEncode(_editorState.document.toJson())) + .then((_) { + ToastUtils.sucess(context, title: "Insert success"); + }, onError: (_) { + ToastUtils.error(context, title: "Insert error"); + }); + }, + ), + SidemenuButton( + icon: Icons.file_open_outlined, + title: "Load last", + onTap: () {}, + ), + SidemenuButton( + icon: Icons.file_open, + title: "Load article...", + onTap: () {}, + ), + SidemenuDivider(), + SidemenuLabel(title: "Template"), + SidemenuButton( + icon: EvaIcons.file_text, + title: "Load Template", + onTap: () {}, + ), + if (isTemplateLoaded) + SidemenuButton( + icon: Bootstrap.file_word, + title: "Generate from Template", + onTap: () async { + if (widget.enablePlugin) { + // 存一份数据 + RecordUtils.putNewMessage( + MessageType.query, _editorState.toStr()); + } + ref.read(chainFlowProvider.notifier).changeContent( + jsonEncode(_editorState.document.toJson())); + // final l = await ref.read(chainFlowProvider.notifier).toRust(); + + // showGeneralDialog( + // barrierDismissible: false, + // barrierColor: Colors.transparent, + // // ignore: use_build_context_synchronously + // context: context, + // pageBuilder: (c, _, __) { + // return const LoadingDialog(); + // }).then((_) async { + // if (widget.enablePlugin) { + // // 存一份数据 + // RecordUtils.putNewMessage( + // MessageType.response, _editorState.toStr()); + // } + // }); - result = ""; - textToMindMap(s: s); + // generateFromTemplate(v: l, enablePlugin: true) + // .then((value) async { + // final md = await optimizeDoc(s: _editorState.toStr()); + // setState( + // () { + // _widgetBuilder = (context) => Editor( + // datasource: Datasource( + // type: DatasourceType.markdown, + // content: md, + // ), + // onEditorStateChange: (editorState) { + // _editorState = editorState; + // }, + // showTemplateFeatures: true, + // ); + // }, + // ); + // }); + }, + ), + SidemenuDivider(), + SidemenuLabel(title: "Plugins"), + SidemenuButton( + icon: Icons.map, + title: "Mind map", + onTap: () { + if (_editorState.selection == null) { + ToastUtils.error(context, title: "No selection"); + return; + } + final text = + _editorState.getTextInSelection(_editorState.selection!); + + if (text.isEmpty) { + ToastUtils.error(context, title: "No text selected"); + return; + } + result = ""; + + textToMindMap(s: text.join("\n")); + }, + ), + SidemenuDivider(), + ], + footer: SidemenuButton( + icon: Icons.chevron_left, + title: "Back", + onTap: () { + ref.read(toolProvider.notifier).jumpTo(0); }, - child: const Icon(Icons.map)), - FloatingActionButton.small( - tooltip: "back", - heroTag: "", - onPressed: () { - ref.read(toolProvider.notifier).jumpTo(0); - }, - child: const Icon(Icons.chevron_left), + ), ), + Expanded(child: _widgetBuilder(context)) ], - ), - extendBodyBehindAppBar: PlatformExtension.isDesktopOrWeb, - body: SafeArea(child: _widgetBuilder(context)), + )), ); } } diff --git a/lib/llm/global/components/sidemenu.dart b/lib/llm/global/components/sidemenu.dart new file mode 100644 index 0000000..52a87e7 --- /dev/null +++ b/lib/llm/global/components/sidemenu.dart @@ -0,0 +1,46 @@ +import 'package:all_in_one/llm/global/models/sidemenu_item.dart'; +import 'package:flutter/material.dart'; + +class Sidemenu extends StatefulWidget { + const Sidemenu( + {super.key, required this.items, this.width = 200, this.footer}); + final List items; + final double width; + final SidemenuItem? footer; + + @override + State createState() => _SidemenuState(); +} + +class _SidemenuState extends State { + @override + Widget build(BuildContext context) { + return Container( + width: widget.width, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color.fromARGB(255, 237, 232, 236), + Color.fromARGB(255, 221, 221, 245) + ])), + padding: const EdgeInsets.all(10), + child: Column( + children: [ + Expanded( + child: ListView.builder( + itemBuilder: (c, i) { + return widget.items[i].toWidget(); + }, + itemCount: widget.items.length, + )), + if (widget.footer != null) + widget.footer!.toWidget() + else + const SizedBox() + ], + ), + ); + } +} diff --git a/lib/llm/global/components/sidemenu_widget.dart b/lib/llm/global/components/sidemenu_widget.dart new file mode 100644 index 0000000..4e94817 --- /dev/null +++ b/lib/llm/global/components/sidemenu_widget.dart @@ -0,0 +1,67 @@ +import 'package:all_in_one/llm/global/models/sidemenu_item.dart'; +import 'package:auto_size_text/auto_size_text.dart'; +import 'package:flutter/material.dart'; + +class SidemenuButton extends SidemenuItem { + final IconData? icon; + SidemenuButton({required this.icon, super.title, super.onTap}); + + @override + Widget toWidget({BuildContext? context}) { + return Material( + color: Colors.transparent, + child: Tooltip( + showDuration: const Duration(milliseconds: 300), + message: title, + child: InkWell( + mouseCursor: SystemMouseCursors.click, + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(10), + child: Row( + children: [ + Icon( + icon, + size: 16, + ), + const SizedBox( + width: 10, + ), + Expanded( + child: AutoSizeText( + title ?? "Click me", + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis, + )) + ], + ), + ), + ), + ), + ); + } +} + +class SidemenuDivider extends SidemenuItem { + @override + Widget toWidget({BuildContext? context}) { + return const Divider(); + } +} + +class SidemenuLabel extends SidemenuItem { + SidemenuLabel({super.title}); + + @override + Widget toWidget({BuildContext? context}) { + return Padding( + padding: const EdgeInsets.all(10), + child: AutoSizeText( + title ?? "Click me", + maxLines: 1, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ); + } +} diff --git a/lib/llm/global/models/sidemenu_item.dart b/lib/llm/global/models/sidemenu_item.dart new file mode 100644 index 0000000..7c5535d --- /dev/null +++ b/lib/llm/global/models/sidemenu_item.dart @@ -0,0 +1,9 @@ +import 'package:flutter/material.dart'; + +abstract class SidemenuItem { + const SidemenuItem({this.title, this.onTap}); + final String? title; + final VoidCallback? onTap; + + Widget toWidget({BuildContext? context}); +} diff --git a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart index 1258899..a13d6e5 100644 --- a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart +++ b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart @@ -1,3 +1,4 @@ +import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'chain_flow_state.dart'; @@ -61,6 +62,42 @@ class ChainFlowNotifier extends Notifier { connections: connections, flowItems: state.items.flowItems), state.content); } + + Future> toRust() async { + List<(String, int, int?, AttributeType, String?)> result = []; + // final items = await templateToPrompts(template: state.content); + // final itemTuple = items + // .mapIndexed( + // (index, element) => ((index, element.$1, element.$2, element.$3))) + // .toList(); + + // List ids = []; + // for (final i in state.items) { + // ids.addAll(i.ids); + // for (int j = 0; j < i.ids.length; j++) { + // if (j < i.ids.length - 1) { + // result.add(( + // i.contents[j], + // i.ids[j], + // ids[j + 1], + // AttributeType.prompt, + // null + // )); + // } else { + // result + // .add((i.contents[j], i.ids[j], null, AttributeType.prompt, null)); + // } + // } + // } + + // itemTuple.retainWhere((element) => !ids.contains(element.$1)); + + // for (final t in itemTuple) { + // result.add((t.$2, t.$1, null, t.$3, t.$4)); + // } + + return result; + } } final chainFlowProvider = NotifierProvider( diff --git a/lib/llm/template_editor/template_editor.dart b/lib/llm/template_editor/template_editor.dart index 1ac2dde..475b52c 100644 --- a/lib/llm/template_editor/template_editor.dart +++ b/lib/llm/template_editor/template_editor.dart @@ -3,6 +3,8 @@ import 'dart:convert'; import 'package:all_in_one/isar/llm_template.dart'; +import 'package:all_in_one/llm/global/components/sidemenu.dart'; +import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:all_in_one/llm/template_editor/components/chain_flow.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; @@ -11,7 +13,6 @@ import 'package:all_in_one/llm/template_editor/notifiers/template_notifier.dart' import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_expandable_fab/flutter_expandable_fab.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icons_plus/icons_plus.dart'; @@ -111,169 +112,253 @@ class _TemplateEditorState extends ConsumerState { return Scaffold( key: key, endDrawer: const ChainFlow(), - floatingActionButtonLocation: ExpandableFab.location, - floatingActionButton: ExpandableFab( - distance: 50, - type: ExpandableFabType.side, - children: [ - FloatingActionButton.small( - tooltip: "chain viewer", - heroTag: "", - onPressed: () { - if (ref.read(chainFlowProvider).items.flowItems.isEmpty) { - return; - } + // floatingActionButtonLocation: ExpandableFab.location, + // floatingActionButton: ExpandableFab( + // distance: 50, + // type: ExpandableFabType.side, + // children: [ + // FloatingActionButton.small( + // tooltip: "chain viewer", + // heroTag: "", + // onPressed: () { + // if (ref.read(chainFlowProvider).items.flowItems.isEmpty) { + // return; + // } - if (key.currentState!.isEndDrawerOpen) { - key.currentState!.closeEndDrawer(); - } else { - key.currentState!.openEndDrawer(); - } - }, - child: const Icon(Bootstrap.view_list), - ), - FloatingActionButton.small( - tooltip: "chain designer", - heroTag: "", - onPressed: () { - ref - .read(chainFlowProvider.notifier) - .changeContent(jsonEncode(_editorState.document.toJson())); + // if (key.currentState!.isEndDrawerOpen) { + // key.currentState!.closeEndDrawer(); + // } else { + // key.currentState!.openEndDrawer(); + // } + // }, + // child: const Icon(Bootstrap.view_list), + // ), + // FloatingActionButton.small( + // tooltip: "chain designer", + // heroTag: "", + // onPressed: () { + // ref + // .read(chainFlowProvider.notifier) + // .changeContent(jsonEncode(_editorState.document.toJson())); - showGeneralDialog( - context: context, - barrierColor: Colors.transparent, - barrierLabel: "chain-flow", - barrierDismissible: true, - pageBuilder: (c, _, __) { - return const Center( - child: ChainFlowDesigner(), - ); - }); - }, - child: const Icon(Bootstrap.magic), - ), - FloatingActionButton.small( - tooltip: "save template", - heroTag: "", - onPressed: () async { - // print(_editorState.document.toJson()); - final String? r = await showGeneralDialog( - context: context, - barrierDismissible: true, - barrierColor: Colors.transparent, - barrierLabel: "new-template", - pageBuilder: (c, _, __) { - return const Center( - child: NewTemplateDialog(), - ); - }); + // showGeneralDialog( + // context: context, + // barrierColor: Colors.transparent, + // barrierLabel: "chain-flow", + // barrierDismissible: true, + // pageBuilder: (c, _, __) { + // return const Center( + // child: ChainFlowDesigner(), + // ); + // }); + // }, + // child: const Icon(Bootstrap.magic), + // ), + // FloatingActionButton.small( + // tooltip: "save template", + // heroTag: "", + // onPressed: () async { + // // print(_editorState.document.toJson()); + // final String? r = await showGeneralDialog( + // context: context, + // barrierDismissible: true, + // barrierColor: Colors.transparent, + // barrierLabel: "new-template", + // pageBuilder: (c, _, __) { + // return const Center( + // child: NewTemplateDialog(), + // ); + // }); - if (r != null) { - ref - .read(templateNotifierProvider.notifier) - .addTemplate(LlmTemplate() - ..template = jsonEncode(_editorState.document.toJson()) - ..name = r); - } - }, - child: const Icon(Bootstrap.download), - ), - FloatingActionButton.small( - tooltip: "load template", - heroTag: "", - onPressed: () async {}, - child: const Icon(Bootstrap.files), - ), - // FloatingActionButton.small( - // tooltip: "generate from template", - // heroTag: null, - // child: const Icon(Bootstrap.file_word), - // onPressed: () async { - // if (widget.enablePlugin) { - // // 存一份数据 - // RecordUtils.putNewMessage( - // MessageType.query, _editorState.toStr()); - // } - // ref - // .read(chainFlowProvider.notifier) - // .changeContent(jsonEncode(_editorState.document.toJson())); - // final l = await ref.read(chainFlowProvider.notifier).toRust(); + // if (r != null) { + // ref + // .read(templateNotifierProvider.notifier) + // .addTemplate(LlmTemplate() + // ..template = jsonEncode(_editorState.document.toJson()) + // ..name = r); + // } + // }, + // child: const Icon(Bootstrap.download), + // ), + // FloatingActionButton.small( + // tooltip: "load template", + // heroTag: "", + // onPressed: () async {}, + // child: const Icon(Bootstrap.files), + // ), + // // FloatingActionButton.small( + // // tooltip: "generate from template", + // // heroTag: null, + // // child: const Icon(Bootstrap.file_word), + // // onPressed: () async { + // // if (widget.enablePlugin) { + // // // 存一份数据 + // // RecordUtils.putNewMessage( + // // MessageType.query, _editorState.toStr()); + // // } + // // ref + // // .read(chainFlowProvider.notifier) + // // .changeContent(jsonEncode(_editorState.document.toJson())); + // // final l = await ref.read(chainFlowProvider.notifier).toRust(); + + // // showGeneralDialog( + // // barrierDismissible: false, + // // barrierColor: Colors.transparent, + // // // ignore: use_build_context_synchronously + // // context: context, + // // pageBuilder: (c, _, __) { + // // return const LoadingDialog(); + // // }).then((_) async { + // // if (widget.enablePlugin) { + // // // 存一份数据 + // // RecordUtils.putNewMessage( + // // MessageType.response, _editorState.toStr()); + // // } + // // }); + + // // generateFromTemplate(v: l, enablePlugin: true) + // // .then((value) async { + // // final md = await optimizeDoc(s: _editorState.toStr()); + // // setState( + // // () { + // // _widgetBuilder = (context) => Editor( + // // datasource: Datasource( + // // type: DatasourceType.markdown, + // // content: md, + // // ), + // // onEditorStateChange: (editorState) { + // // _editorState = editorState; + // // }, + // // showTemplateFeatures: true, + // // ); + // // }, + // // ); + // // }); + // // }, + // // ), + // // FloatingActionButton.small( + // // tooltip: "test-chain", + // // heroTag: null, + // // child: const Icon(Bootstrap.activity), + // // onPressed: () async { + // // String s = jsonEncode(_editorState.document.toJson()); + // // if (widget.enablePlugin) { + // // // 存一份数据 + // // RecordUtils.putNewMessage( + // // MessageType.query, _editorState.toStr()); + // // } + // // final res = await templateRenderer(template: s); + // // if (res != null) { + // // _jsonString = jsonEncode(jsonDecode(res)); - // showGeneralDialog( - // barrierDismissible: false, - // barrierColor: Colors.transparent, - // // ignore: use_build_context_synchronously - // context: context, - // pageBuilder: (c, _, __) { - // return const LoadingDialog(); - // }).then((_) async { - // if (widget.enablePlugin) { - // // 存一份数据 - // RecordUtils.putNewMessage( - // MessageType.response, _editorState.toStr()); - // } - // }); + // // setState(() { + // // _editorState = + // // EditorState(document: Document.fromJson(jsonDecode(res))); + // // }); + // // if (widget.enablePlugin) { + // // // 存一份数据 + // // RecordUtils.putNewMessage( + // // MessageType.response, _editorState.toStr()); + // // } + // // } + // // }, + // // ), + // FloatingActionButton.small( + // tooltip: "back", + // heroTag: "", + // onPressed: () { + // ref.read(toolProvider.notifier).jumpTo(0); + // }, + // child: const Icon(Icons.chevron_left), + // ), + // ], + // ), + extendBodyBehindAppBar: PlatformExtension.isDesktopOrWeb, + body: SafeArea( + child: Row( + children: [ + Sidemenu( + items: [ + SidemenuLabel(title: "Template"), + SidemenuButton( + icon: EvaIcons.file_text, + title: "Load Template", + onTap: () {}, + ), + SidemenuButton( + icon: EvaIcons.save, + title: "Save Template", + onTap: () async { + final String? r = await showGeneralDialog( + context: context, + barrierDismissible: true, + barrierColor: Colors.transparent, + barrierLabel: "new-template", + pageBuilder: (c, _, __) { + return const Center( + child: NewTemplateDialog(), + ); + }); - // generateFromTemplate(v: l, enablePlugin: true) - // .then((value) async { - // final md = await optimizeDoc(s: _editorState.toStr()); - // setState( - // () { - // _widgetBuilder = (context) => Editor( - // datasource: Datasource( - // type: DatasourceType.markdown, - // content: md, - // ), - // onEditorStateChange: (editorState) { - // _editorState = editorState; - // }, - // showTemplateFeatures: true, - // ); - // }, - // ); - // }); - // }, - // ), - // FloatingActionButton.small( - // tooltip: "test-chain", - // heroTag: null, - // child: const Icon(Bootstrap.activity), - // onPressed: () async { - // String s = jsonEncode(_editorState.document.toJson()); - // if (widget.enablePlugin) { - // // 存一份数据 - // RecordUtils.putNewMessage( - // MessageType.query, _editorState.toStr()); - // } - // final res = await templateRenderer(template: s); - // if (res != null) { - // _jsonString = jsonEncode(jsonDecode(res)); + if (r != null) { + ref + .read(templateNotifierProvider.notifier) + .addTemplate(LlmTemplate() + ..template = + jsonEncode(_editorState.document.toJson()) + ..name = r); + } + }, + ), + SidemenuDivider(), + SidemenuLabel(title: "Chain"), + SidemenuButton( + icon: Bootstrap.magic, + title: "Chain designer", + onTap: () { + ref.read(chainFlowProvider.notifier).changeContent( + jsonEncode(_editorState.document.toJson())); - // setState(() { - // _editorState = - // EditorState(document: Document.fromJson(jsonDecode(res))); - // }); - // if (widget.enablePlugin) { - // // 存一份数据 - // RecordUtils.putNewMessage( - // MessageType.response, _editorState.toStr()); - // } - // } - // }, - // ), - FloatingActionButton.small( - tooltip: "back", - heroTag: "", - onPressed: () { - ref.read(toolProvider.notifier).jumpTo(0); - }, - child: const Icon(Icons.chevron_left), + showGeneralDialog( + context: context, + barrierColor: Colors.transparent, + barrierLabel: "chain-flow", + barrierDismissible: true, + pageBuilder: (c, _, __) { + return const Center( + child: ChainFlowDesigner(), + ); + }); + }, + ), + SidemenuButton( + icon: Bootstrap.view_stacked, + title: "Chain viewer", + onTap: () { + if (ref.read(chainFlowProvider).items.flowItems.isEmpty) { + return; + } + + if (key.currentState!.isEndDrawerOpen) { + key.currentState!.closeEndDrawer(); + } else { + key.currentState!.openEndDrawer(); + } + }, + ), + SidemenuDivider(), + ], + footer: SidemenuButton( + icon: Icons.chevron_left, + title: "Back", + onTap: () { + ref.read(toolProvider.notifier).jumpTo(0); + }, + ), ), + Expanded(child: _widgetBuilder(context)) ], - ), - extendBodyBehindAppBar: PlatformExtension.isDesktopOrWeb, - body: SafeArea(child: _widgetBuilder(context)), + )), ); } } diff --git a/lib/tool_entry/routers/routers.dart b/lib/tool_entry/routers/routers.dart index 88d08c4..a97d371 100644 --- a/lib/tool_entry/routers/routers.dart +++ b/lib/tool_entry/routers/routers.dart @@ -66,8 +66,8 @@ class ToolEntryRoutersNotifier extends AutoDisposeNotifier { } changeRouter(String s) async { - if (ref.read(pageProvider) != 1) { - ref.read(pageProvider.notifier).changePage(1); + if (ref.read(pageProvider) != 2) { + ref.read(pageProvider.notifier).changePage(2); } if (Routers.routers.keys.contains(s)) { diff --git a/pubspec.lock b/pubspec.lock index 9782d76..a5fb286 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -799,6 +799,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "4.9.0" + just_the_tooltip: + dependency: "direct main" + description: + name: just_the_tooltip + sha256: "7a081133d57285bfb41b331f411006d57b433d7b35772e6155745f6a7a09cb82" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.0.12" keyboard_height_plugin: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index f716972..853eb86 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -48,6 +48,7 @@ dependencies: icons_plus: ^5.0.0 isar: ^3.1.0+1 # run `flutter pub run build_runner build` to generate codes isar_flutter_libs: ^3.1.0+1 + just_the_tooltip: ^0.0.12 loading_animation_widget: ^1.2.1 loading_indicator: ^3.1.1 logging: ^1.2.0 From 4d2c5439d6c9bcb49a127d8eac91c219d53126ea Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sat, 25 May 2024 22:09:15 +0800 Subject: [PATCH 03/16] create langchain_lib (dart) --- langchain_lib/.gitignore | 29 ++++++++++++ langchain_lib/.metadata | 10 ++++ langchain_lib/CHANGELOG.md | 3 ++ langchain_lib/LICENSE | 1 + langchain_lib/README.md | 39 ++++++++++++++++ langchain_lib/analysis_options.yaml | 4 ++ langchain_lib/lib/langchain_lib.dart | 7 +++ langchain_lib/pubspec.yaml | 54 ++++++++++++++++++++++ langchain_lib/test/langchain_lib_test.dart | 12 +++++ 9 files changed, 159 insertions(+) create mode 100644 langchain_lib/.gitignore create mode 100644 langchain_lib/.metadata create mode 100644 langchain_lib/CHANGELOG.md create mode 100644 langchain_lib/LICENSE create mode 100644 langchain_lib/README.md create mode 100644 langchain_lib/analysis_options.yaml create mode 100644 langchain_lib/lib/langchain_lib.dart create mode 100644 langchain_lib/pubspec.yaml create mode 100644 langchain_lib/test/langchain_lib_test.dart diff --git a/langchain_lib/.gitignore b/langchain_lib/.gitignore new file mode 100644 index 0000000..ac5aa98 --- /dev/null +++ b/langchain_lib/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/langchain_lib/.metadata b/langchain_lib/.metadata new file mode 100644 index 0000000..6504831 --- /dev/null +++ b/langchain_lib/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "5dcb86f68f239346676ceb1ed1ea385bd215fba1" + channel: "stable" + +project_type: package diff --git a/langchain_lib/CHANGELOG.md b/langchain_lib/CHANGELOG.md new file mode 100644 index 0000000..41cc7d8 --- /dev/null +++ b/langchain_lib/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/langchain_lib/LICENSE b/langchain_lib/LICENSE new file mode 100644 index 0000000..ba75c69 --- /dev/null +++ b/langchain_lib/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/langchain_lib/README.md b/langchain_lib/README.md new file mode 100644 index 0000000..02fe8ec --- /dev/null +++ b/langchain_lib/README.md @@ -0,0 +1,39 @@ + + +TODO: Put a short description of the package here that helps potential users +know whether this package might be useful for them. + +## Features + +TODO: List what your package can do. Maybe include images, gifs, or videos. + +## Getting started + +TODO: List prerequisites and provide or point to information on how to +start using the package. + +## Usage + +TODO: Include short and useful examples for package users. Add longer examples +to `/example` folder. + +```dart +const like = 'sample'; +``` + +## Additional information + +TODO: Tell users more about the package: where to find more information, how to +contribute to the package, how to file issues, what response they can expect +from the package authors, and more. diff --git a/langchain_lib/analysis_options.yaml b/langchain_lib/analysis_options.yaml new file mode 100644 index 0000000..a5744c1 --- /dev/null +++ b/langchain_lib/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/langchain_lib/lib/langchain_lib.dart b/langchain_lib/lib/langchain_lib.dart new file mode 100644 index 0000000..82edfc5 --- /dev/null +++ b/langchain_lib/lib/langchain_lib.dart @@ -0,0 +1,7 @@ +library langchain_lib; + +/// A Calculator. +class Calculator { + /// Returns [value] plus 1. + int addOne(int value) => value + 1; +} diff --git a/langchain_lib/pubspec.yaml b/langchain_lib/pubspec.yaml new file mode 100644 index 0000000..86af58f --- /dev/null +++ b/langchain_lib/pubspec.yaml @@ -0,0 +1,54 @@ +name: langchain_lib +description: "A new Flutter package project." +version: 0.0.1 +homepage: + +environment: + sdk: '>=3.4.0 <4.0.0' + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^3.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # To add assets to your package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/assets-and-images/#from-packages + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # To add custom fonts to your package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/custom-fonts/#from-packages diff --git a/langchain_lib/test/langchain_lib_test.dart b/langchain_lib/test/langchain_lib_test.dart new file mode 100644 index 0000000..67c9f5d --- /dev/null +++ b/langchain_lib/test/langchain_lib_test.dart @@ -0,0 +1,12 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:langchain_lib/langchain_lib.dart'; + +void main() { + test('adds one to input values', () { + final calculator = Calculator(); + expect(calculator.addOne(2), 3); + expect(calculator.addOne(-7), -6); + expect(calculator.addOne(0), 1); + }); +} From 3ec40e2d3c1ed53d300cc21741144b891c1d7d56 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sun, 26 May 2024 09:36:33 +0800 Subject: [PATCH 04/16] refactor: chat --- langchain_lib/analysis_options.yaml | 3 + langchain_lib/lib/client/client.dart | 7 ++ langchain_lib/lib/client/load_env.dart | 27 ++++++++ langchain_lib/lib/client/openai_client.dart | 41 ++++++++++++ langchain_lib/lib/langchain_lib.dart | 8 +-- langchain_lib/lib/message/message_util.dart | 22 ++++++ langchain_lib/pubspec.yaml | 36 +--------- langchain_lib/test/langchain_lib_test.dart | 12 ---- langchain_lib/test/test_openai_client.dart | 43 ++++++++++++ lib/llm/ai_client.dart | 15 +++++ lib/llm/langchain/components/chat_ui.dart | 74 ++++++++++++--------- lib/main.dart | 4 ++ pubspec.lock | 73 +++++++++++++++++++- pubspec.yaml | 2 + 14 files changed, 283 insertions(+), 84 deletions(-) create mode 100644 langchain_lib/lib/client/client.dart create mode 100644 langchain_lib/lib/client/load_env.dart create mode 100644 langchain_lib/lib/client/openai_client.dart create mode 100644 langchain_lib/lib/message/message_util.dart delete mode 100644 langchain_lib/test/langchain_lib_test.dart create mode 100644 langchain_lib/test/test_openai_client.dart create mode 100644 lib/llm/ai_client.dart diff --git a/langchain_lib/analysis_options.yaml b/langchain_lib/analysis_options.yaml index a5744c1..120c4a8 100644 --- a/langchain_lib/analysis_options.yaml +++ b/langchain_lib/analysis_options.yaml @@ -1,3 +1,6 @@ +analyzer: + errors: + avoid_print: ignore include: package:flutter_lints/flutter.yaml # Additional information about this file can be found at diff --git a/langchain_lib/lib/client/client.dart b/langchain_lib/lib/client/client.dart new file mode 100644 index 0000000..261df8d --- /dev/null +++ b/langchain_lib/lib/client/client.dart @@ -0,0 +1,7 @@ +import 'package:langchain/langchain.dart'; + +abstract class Client { + Future invoke(List history); + + Stream stream(List history); +} diff --git a/langchain_lib/lib/client/load_env.dart b/langchain_lib/lib/client/load_env.dart new file mode 100644 index 0000000..d8dd1fe --- /dev/null +++ b/langchain_lib/lib/client/load_env.dart @@ -0,0 +1,27 @@ +import 'dart:io'; + +List loadEnv(String path) { + File f = File(path); + if (f.existsSync()) { + final lines = f.readAsLinesSync(); + // return f.readAsLinesSync(); + final List result = []; + for (final i in lines) { + if (i.startsWith('#')) { + continue; + } + final s = i.split("="); + if (s.length == 2) { + if (s[0].trim() == "LLM_BASE" || + s[0].trim() == "LLM_MODEL_NAME" || + s[0].trim() == "LLM_SK") { + result.add(s[1].trim()); + } + } + } + + return result; + } else { + return []; + } +} diff --git a/langchain_lib/lib/client/openai_client.dart b/langchain_lib/lib/client/openai_client.dart new file mode 100644 index 0000000..41b18c3 --- /dev/null +++ b/langchain_lib/lib/client/openai_client.dart @@ -0,0 +1,41 @@ +import 'package:langchain/langchain.dart'; +import 'package:langchain_lib/client/client.dart'; +import 'package:langchain_openai/langchain_openai.dart'; + +import 'load_env.dart'; + +class OpenaiClient extends Client { + final String baseUrl; + final String? apiKey; + final String? modelName; + + OpenaiClient({required this.baseUrl, this.apiKey, this.modelName}) { + model = ChatOpenAI( + apiKey: apiKey, + baseUrl: baseUrl, + defaultOptions: ChatOpenAIOptions(model: modelName)); + } + + late final ChatOpenAI model; + + @override + Future invoke(List history) async { + final prompt = PromptValue.chat(history); + return await model.invoke(prompt); + } + + @override + Stream stream(List history) { + final prompt = PromptValue.chat(history); + return model.stream(prompt); + } + + static Client? fromEnv(String path) { + final envs = loadEnv(path); + if (envs.length != 3) { + return OpenaiClient(baseUrl: ""); + } + + return OpenaiClient(baseUrl: envs[0], apiKey: envs[2], modelName: envs[1]); + } +} diff --git a/langchain_lib/lib/langchain_lib.dart b/langchain_lib/lib/langchain_lib.dart index 82edfc5..b0fc397 100644 --- a/langchain_lib/lib/langchain_lib.dart +++ b/langchain_lib/lib/langchain_lib.dart @@ -1,7 +1,5 @@ library langchain_lib; -/// A Calculator. -class Calculator { - /// Returns [value] plus 1. - int addOne(int value) => value + 1; -} +export 'client/openai_client.dart'; +export 'package:langchain/langchain.dart'; +export 'message/message_util.dart'; diff --git a/langchain_lib/lib/message/message_util.dart b/langchain_lib/lib/message/message_util.dart new file mode 100644 index 0000000..bf6f593 --- /dev/null +++ b/langchain_lib/lib/message/message_util.dart @@ -0,0 +1,22 @@ +import 'package:langchain/langchain.dart'; + +class MessageUtil { + MessageUtil._(); + static ChatMessage createSystemMessage(final String content) { + return SystemChatMessage(content: content); + } + + static ChatMessage createHumanMessage( + /* support text only right now */ final String content) { + return HumanChatMessage(content: ChatMessageContentText(text: content)); + } + + static ChatMessage createAiMessage(final String content) { + return AIChatMessage(content: content); + } + + static ChatMessage createToolMessage( + final String content, final String toolId) { + return ToolChatMessage(content: content, toolCallId: toolId); + } +} diff --git a/langchain_lib/pubspec.yaml b/langchain_lib/pubspec.yaml index 86af58f..0d90d2b 100644 --- a/langchain_lib/pubspec.yaml +++ b/langchain_lib/pubspec.yaml @@ -10,45 +10,13 @@ environment: dependencies: flutter: sdk: flutter + langchain: ^0.7.1 + langchain_openai: ^0.6.1+1 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.0 -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. flutter: - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/langchain_lib/test/langchain_lib_test.dart b/langchain_lib/test/langchain_lib_test.dart deleted file mode 100644 index 67c9f5d..0000000 --- a/langchain_lib/test/langchain_lib_test.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; - -import 'package:langchain_lib/langchain_lib.dart'; - -void main() { - test('adds one to input values', () { - final calculator = Calculator(); - expect(calculator.addOne(2), 3); - expect(calculator.addOne(-7), -6); - expect(calculator.addOne(0), 1); - }); -} diff --git a/langchain_lib/test/test_openai_client.dart b/langchain_lib/test/test_openai_client.dart new file mode 100644 index 0000000..4de05e4 --- /dev/null +++ b/langchain_lib/test/test_openai_client.dart @@ -0,0 +1,43 @@ +import 'dart:io'; + +import 'package:langchain/langchain.dart'; +import 'package:langchain_lib/client/openai_client.dart'; +import 'package:langchain_lib/client/load_env.dart'; + +void main() async { + List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + if (envs.length != 3) { + return; + } + + final client = OpenaiClient( + baseUrl: envs[0], + apiKey: envs[2], + modelName: envs[1], + ); + + await client.invoke([ + ChatMessage.system( + 'You are a helpful assistant that translates English to French.'), + ChatMessage.humanText('I love programming.'), + ]).then((value) { + print(value.outputAsString); + }); + + print( + "====================================================================="); + + await Future.delayed(const Duration(seconds: 3)); + + final stream = + client.stream([ChatMessage.humanText("给我将一个爱因斯坦和椅子的故事,200字以内。")]); + + stream.listen( + (event) { + stdout.write(event.outputAsString); + }, + onDone: () { + stdout.write("\nThe end.\n"); + }, + ); +} diff --git a/lib/llm/ai_client.dart b/lib/llm/ai_client.dart new file mode 100644 index 0000000..bb61776 --- /dev/null +++ b/lib/llm/ai_client.dart @@ -0,0 +1,15 @@ +import 'package:langchain_lib/client/client.dart'; +import 'package:langchain_lib/client/openai_client.dart'; + +class AiClient { + AiClient._(); + + static final _instance = AiClient._(); + + factory AiClient() => _instance; + + late Client? client; + initOpenAi(String path) { + client = OpenaiClient.fromEnv(path); + } +} diff --git a/lib/llm/langchain/components/chat_ui.dart b/lib/llm/langchain/components/chat_ui.dart index bc40c08..b05fb92 100644 --- a/lib/llm/langchain/components/chat_ui.dart +++ b/lib/llm/langchain/components/chat_ui.dart @@ -1,5 +1,6 @@ import 'package:all_in_one/common/logger.dart'; import 'package:all_in_one/isar/llm_history.dart'; +import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/llm/chatchat/components/input_field.dart'; import 'package:all_in_one/llm/chatchat/models/llm_response.dart'; import 'package:all_in_one/llm/chatchat/models/request_message_box.dart'; @@ -8,11 +9,12 @@ import 'package:all_in_one/llm/chatchat/notifiers/message_notifier.dart'; import 'package:all_in_one/llm/chatchat/notifiers/message_state.dart'; import 'package:all_in_one/llm/langchain/langchain_config.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart' as llm; -import 'package:all_in_one/src/rust/llm.dart'; +// import 'package:all_in_one/src/rust/api/llm_api.dart' as llm; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:langchain_lib/langchain_lib.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; +import 'package:uuid/uuid.dart'; class ChatUI extends ConsumerStatefulWidget { const ChatUI({super.key, required this.chatTag}); @@ -23,34 +25,19 @@ class ChatUI extends ConsumerStatefulWidget { } class _ChatUIState extends ConsumerState { - final llmStream = llm.llmMessageStream(); + // final llmStream = llm.llmMessageStream(); final LangchainConfig config = LangchainConfig(); + final AiClient aiClient = AiClient(); @override void initState() { super.initState(); - - llmStream.listen((event) { - // print(event.content); - - if (event.content == "!over!") { - final last = ref.read(messageProvider).messageBox.last; - ref - .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) - .updateHistory(id, last.content, MessageType.response, - roleType: event.type); - } else { - final res = LLMResponse(messageId: event.uuid, text: event.content); - ref.read(messageProvider.notifier).updateMessageBox(res); - } - }); } late int id = 0; @override Widget build(BuildContext context) { - print(widget.chatTag); final state = ref.watch(messageProvider); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { @@ -128,6 +115,12 @@ class _ChatUIState extends ConsumerState { } _handleInputMessage(String s, MessageState state) async { + String uuid = const Uuid().v4(); + + if (aiClient.client == null) { + return; + } + if (state.isLoading) { return; } @@ -152,27 +145,44 @@ class _ChatUIState extends ConsumerState { .read(historyProvider((LLMType.openai, widget.chatTag)).notifier) .getMessages(config.historyLength, id); - List history; + List history = messages.map((v) { + if (v.roleType == 0) { + return MessageUtil.createHumanMessage(v.content ?? ""); + } else if (v.roleType == 1) { + return MessageUtil.createSystemMessage(v.content ?? ""); + } else if (v.roleType == 2) { + return MessageUtil.createAiMessage(v.content ?? ""); + } else { + return MessageUtil.createToolMessage(v.content ?? "", ""); + } + }).toList(); + if (model != null && model.toMessage()!.content != "normal") { - history = [ - model.toMessage()!, - ...messages.map((e) => - LLMMessage(uuid: "", content: e.content ?? "", type: e.roleType)) - ]; - } else { - history = messages - .map((e) => - LLMMessage(uuid: "", content: e.content ?? "", type: e.roleType)) - .toList(); + history.insert(0, MessageUtil.createSystemMessage(model.systemPrompt)); } for (final i in history) { - logger.info("${i.type} ${i.content}"); + logger.info(i.contentAsString); } + history.add(MessageUtil.createHumanMessage(s)); + ref .read(historyProvider((LLMType.openai, widget.chatTag)).notifier) .updateHistory(id, s, MessageType.query); - llm.chat(stream: true, query: s, history: history); + final Stream stream = aiClient.client!.stream(history); + + stream.listen( + (event) { + final res = LLMResponse(messageId: uuid, text: event.outputAsString); + ref.read(messageProvider.notifier).updateMessageBox(res); + }, + onDone: () { + final last = ref.read(messageProvider).messageBox.last; + ref + .read(historyProvider((LLMType.chatchat, widget.chatTag)).notifier) + .updateHistory(id, last.content, MessageType.response, roleType: 2); + }, + ); } } diff --git a/lib/main.dart b/lib/main.dart index 70254be..8728413 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,6 +6,7 @@ import 'package:all_in_one/common/dev_utils.dart'; import 'package:all_in_one/common/logger.dart'; import 'package:all_in_one/isar/database.dart'; import 'package:all_in_one/isar/software.dart'; +import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/src/rust/api/llm_api.dart' as llm; import 'package:all_in_one/src/rust/api/software_monitor_api.dart' as smapi; import 'package:all_in_one/src/rust/api/sub_window_api.dart' as sw; @@ -31,6 +32,9 @@ Future main() async { } }); + AiClient aiClient = AiClient(); + aiClient.initOpenAi(DevUtils.env); + if (Platform.isWindows) { llm.initLlm(p: DevUtils.env); llm.initPromptFromPath(s: DevUtils.prompt); diff --git a/pubspec.lock b/pubspec.lock index a5fb286..5ad9c26 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -369,6 +369,22 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.3.1" + fetch_api: + dependency: transitive + description: + name: fetch_api + sha256: c0a76bfd84d4bc5a0733ab8b9fcee268d5069228790a6dd71fc2a6d1049223cc + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.0" + fetch_client: + dependency: transitive + description: + name: fetch_client + sha256: "0b935eff9dfa84fb56bddadaf020c9aa61f02cbd6fa8dad914d6d343a838936d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" ffi: dependency: transitive description: @@ -621,6 +637,14 @@ packages: description: flutter source: sdk version: "0.0.0" + freezed_annotation: + dependency: transitive + description: + name: freezed_annotation + sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.1" frontend_server_client: dependency: transitive description: @@ -815,6 +839,45 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "0.0.5" + langchain: + dependency: transitive + description: + name: langchain + sha256: "7773a0f113d729f0593879b5852b05c7a32d5fb3eddf3aabffa5e15d9baaf12e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.1" + langchain_core: + dependency: transitive + description: + name: langchain_core + sha256: da71ddb5b392ac699d876e9b84d769b0e879809316b0269359deda884cffdc9b + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.3.1" + langchain_lib: + dependency: "direct main" + description: + path: langchain_lib + relative: true + source: path + version: "0.0.1" + langchain_openai: + dependency: transitive + description: + name: langchain_openai + sha256: "4b54c2d79804ba38e134952e60f7ab079f950c90f90de31517a58b68248bf52e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.6.1+1" + langchain_tiktoken: + dependency: transitive + description: + name: langchain_tiktoken + sha256: c1804f4b3e56574ca67e562305d9f11e3eabe3c8aa87fea8635992f7efc66674 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" leak_tracker: dependency: transitive description: @@ -951,6 +1014,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.2.0" + openai_dart: + dependency: transitive + description: + name: openai_dart + sha256: "366aaac9efc807d8b3f0ea1d19e6cb85a38f268ed2284430d95954850bca6eb6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.3.2+1" package_config: dependency: transitive description: @@ -1581,5 +1652,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.3.0 <4.0.0" + dart: ">=3.4.0 <4.0.0" flutter: ">=3.19.0" diff --git a/pubspec.yaml b/pubspec.yaml index 853eb86..e01f4de 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -49,6 +49,8 @@ dependencies: isar: ^3.1.0+1 # run `flutter pub run build_runner build` to generate codes isar_flutter_libs: ^3.1.0+1 just_the_tooltip: ^0.0.12 + langchain_lib: + path: langchain_lib loading_animation_widget: ^1.2.1 loading_indicator: ^3.1.1 logging: ^1.2.0 From e88e6d9e45fb9d804b4dc7991db6086e20c1b8fa Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sun, 26 May 2024 10:01:07 +0800 Subject: [PATCH 05/16] refactor: ai assistant request --- lib/llm/editor/components/show_ai_menu.dart | 54 ++++++++++++++++++--- lib/llm/editor/compose_screen.dart | 2 - 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/lib/llm/editor/components/show_ai_menu.dart b/lib/llm/editor/components/show_ai_menu.dart index 02c5038..e1bde02 100644 --- a/lib/llm/editor/components/show_ai_menu.dart +++ b/lib/llm/editor/components/show_ai_menu.dart @@ -1,12 +1,14 @@ // ignore_for_file: non_constant_identifier_names +import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/llm/editor/notifiers/ai_generate_config_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; +// import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:all_in_one/styles/app_style.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icons_plus/icons_plus.dart'; +import 'package:langchain_lib/langchain_lib.dart'; import 'add_tag_button.dart'; import 'dropdown_button.dart'; @@ -247,14 +249,14 @@ class AiMenuWidget extends ConsumerStatefulWidget { class _AiMenuWidgetState extends ConsumerState { final TextEditingController controller = TextEditingController(); final TextEditingController resController = TextEditingController(); - late Stream aiHelperStream = aiHelperMessageStream(); + // late Stream aiHelperStream = aiHelperMessageStream(); @override void initState() { super.initState(); - aiHelperStream.listen((v) { - resController.text += v; - }); + // aiHelperStream.listen((v) { + // resController.text += v; + // }); } @override @@ -319,7 +321,7 @@ class _AiMenuWidgetState extends ConsumerState { } final state = ref.read(aiGenerateConfigNotifierProvider); resController.text = ""; - aiHelperQuickRequest( + _aiQuickRequest( s: controller.text, tone: state.tone, lang: state.lang, @@ -372,7 +374,7 @@ class _AiMenuWidgetState extends ConsumerState { } final state = ref.read(aiGenerateConfigNotifierProvider); resController.text = ""; - aiHelperQuickRequest( + _aiQuickRequest( s: controller.text, tone: state.tone, lang: state.lang, @@ -404,6 +406,44 @@ class _AiMenuWidgetState extends ConsumerState { ), ); } + + final AiClient client = AiClient(); + + _aiQuickRequest({ + required String s, + required String tone, + required String lang, + required String length, + required List extra, + }) { + if (client.client == null) { + return; + } + final List requirements = List.from(extra); + if (lang != "中文") { + requirements.add("请使用$lang回答"); + } + switch (length) { + case "中等的": + requirements.add("结果在500~1000字"); + break; + case "长文": + requirements.add("结果在1000~1500字"); + break; + default: + requirements.add("结果在500字以内"); + } + if (tone != "正常的") { + requirements.add("请使用$tone口吻回答"); + } + String prompt = "$s。要求如下:\n{$requirements.join('\n')}"; + final Stream stream = + client.client!.stream([MessageUtil.createHumanMessage(prompt)]); + + stream.listen((v) { + resController.text += v.outputAsString; + }); + } } class StyleConfigWidget extends ConsumerStatefulWidget { diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 01bf06e..257992d 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -10,10 +10,8 @@ import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:all_in_one/llm/plugins/mind_map.dart'; import 'package:all_in_one/llm/plugins/models/mind_map_model.dart'; import 'package:all_in_one/llm/plugins/record/record_utils.dart'; -import 'package:all_in_one/llm/template_editor/components/loading_dialog.dart'; import 'package:all_in_one/llm/template_editor/extension.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; From dd645bbba27dd559d7e016e2363d98b1fdc680b4 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sun, 26 May 2024 13:36:21 +0800 Subject: [PATCH 06/16] update tests --- langchain_lib/analysis_options.yaml | 1 + langchain_lib/lib/client/client.dart | 3 ++ langchain_lib/lib/client/openai_client.dart | 38 +++++++++++++++++++ langchain_lib/lib/models/template_item.dart | 21 +++++++++++ langchain_lib/test/test_example.dart | 42 +++++++++++++++++++++ langchain_lib/test/test_seq_chain.dart | 32 ++++++++++++++++ lib/llm/ai_client.dart | 13 +++++++ 7 files changed, 150 insertions(+) create mode 100644 langchain_lib/lib/models/template_item.dart create mode 100644 langchain_lib/test/test_example.dart create mode 100644 langchain_lib/test/test_seq_chain.dart diff --git a/langchain_lib/analysis_options.yaml b/langchain_lib/analysis_options.yaml index 120c4a8..3b16d94 100644 --- a/langchain_lib/analysis_options.yaml +++ b/langchain_lib/analysis_options.yaml @@ -1,6 +1,7 @@ analyzer: errors: avoid_print: ignore + constant_identifier_names: ignore include: package:flutter_lints/flutter.yaml # Additional information about this file can be found at diff --git a/langchain_lib/lib/client/client.dart b/langchain_lib/lib/client/client.dart index 261df8d..b08307f 100644 --- a/langchain_lib/lib/client/client.dart +++ b/langchain_lib/lib/client/client.dart @@ -1,7 +1,10 @@ import 'package:langchain/langchain.dart'; +import 'package:langchain_lib/models/template_item.dart'; abstract class Client { Future invoke(List history); Stream stream(List history); + + BaseChain? intoChain(List items); } diff --git a/langchain_lib/lib/client/openai_client.dart b/langchain_lib/lib/client/openai_client.dart index 41b18c3..69c708f 100644 --- a/langchain_lib/lib/client/openai_client.dart +++ b/langchain_lib/lib/client/openai_client.dart @@ -1,5 +1,6 @@ import 'package:langchain/langchain.dart'; import 'package:langchain_lib/client/client.dart'; +import 'package:langchain_lib/models/template_item.dart'; import 'package:langchain_openai/langchain_openai.dart'; import 'load_env.dart'; @@ -38,4 +39,41 @@ class OpenaiClient extends Client { return OpenaiClient(baseUrl: envs[0], apiKey: envs[2], modelName: envs[1]); } + + @override + BaseChain? intoChain(List items) { + if (items.isEmpty) { + return null; + } + if (items.length == 1) { + final prompt = LLMChain( + llm: model, prompt: PromptTemplate.fromTemplate(items[0].prompt)); + + return prompt; + } else { + // final prompt = SequentialChain(chains: []); + List chains = []; + for (int i = 0; i < items.length; i++) { + String input = "input$i"; + String output = "input${i + 1}"; + String promptStr; + if (i == 0) { + promptStr = "请根据以下要求,帮我生成对应的文案。 {$input}"; + } else { + promptStr = + "请根据以下内容和额外要求,帮我生成对应的文案。内容: {$input}, 额外要求: ${items[i].prompt}"; + } + print(promptStr); + final prompt = PromptTemplate.fromTemplate(promptStr); + // chains.add() + final chain = LLMChain(llm: model, prompt: prompt, outputKey: output); + chains.add(chain); + } + final seqChain = SequentialChain( + chains: chains, + // memory: const SimpleMemory(), + returnIntermediateOutputs: true); + return seqChain; + } + } } diff --git a/langchain_lib/lib/models/template_item.dart b/langchain_lib/lib/models/template_item.dart new file mode 100644 index 0000000..748e9be --- /dev/null +++ b/langchain_lib/lib/models/template_item.dart @@ -0,0 +1,21 @@ +class TemplateItem { + final String prompt; + final int index; + final int? next; + final AttributeType attrType; + final String? extra; + + TemplateItem({ + required this.prompt, + required this.index, + this.next, + required this.attrType, + this.extra, + }); +} + +enum AttributeType { + Prompt, + File, + Sql, +} diff --git a/langchain_lib/test/test_example.dart b/langchain_lib/test/test_example.dart new file mode 100644 index 0000000..7a96d3f --- /dev/null +++ b/langchain_lib/test/test_example.dart @@ -0,0 +1,42 @@ +import 'package:langchain/langchain.dart'; +import 'package:langchain_lib/client/load_env.dart'; +import 'package:langchain_openai/langchain_openai.dart'; + +void main() async { + List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + if (envs.length != 3) { + return; + } + final llm = ChatOpenAI( + apiKey: envs[2], + baseUrl: envs[0], + defaultOptions: ChatOpenAIOptions(model: envs[1])); + +// This is an LLMChain to write a synopsis given a title of a play + const synopsisTemplate = ''' +You are a playwright. Given the title of play, it is your job to write a synopsis for that title. + +Title: {title} +Playwright: This is a synopsis for the above play:'''; + final synopsisPromptTemplate = PromptTemplate.fromTemplate(synopsisTemplate); + final synopsisChain = + LLMChain(llm: llm, prompt: synopsisPromptTemplate, outputKey: "synopsis"); + +// This is an LLMChain to write a review of a play given a synopsis + const reviewTemplate = ''' +You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. + +Play Synopsis: +{synopsis} +Review from a New York Times play critic of the above play:'''; + final reviewPromptTemplate = PromptTemplate.fromTemplate(reviewTemplate); + final reviewChain = + LLMChain(llm: llm, prompt: reviewPromptTemplate, outputKey: "review"); + +// This is the overall chain where we run these two chains in sequence + final overallChain = SimpleSequentialChain( + chains: [synopsisChain, reviewChain], inputKey: "title"); + final review = + await overallChain.invoke({"title": 'Tragedy at sunset on the beach'}); + print(review); +} diff --git a/langchain_lib/test/test_seq_chain.dart b/langchain_lib/test/test_seq_chain.dart new file mode 100644 index 0000000..1447910 --- /dev/null +++ b/langchain_lib/test/test_seq_chain.dart @@ -0,0 +1,32 @@ +import 'package:langchain_lib/client/load_env.dart'; +import 'package:langchain_lib/langchain_lib.dart'; +import 'package:langchain_lib/models/template_item.dart'; + +void main() { + List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + if (envs.length != 3) { + return; + } + final client = OpenaiClient( + baseUrl: envs[0], + apiKey: envs[2], + modelName: envs[1], + ); + + BaseChain? chain = client.intoChain([ + TemplateItem( + prompt: "帮我梳理rust学习路线", + index: 1, + next: 2, + attrType: AttributeType.Prompt), + TemplateItem( + prompt: "请帮我总结到200字以内", index: 2, attrType: AttributeType.Prompt) + ]); + + // chain.invoke(input) + if (chain != null) { + chain.call({"input0": "帮我梳理rust学习路线"}, returnOnlyOutputs: false).then((v) { + print(v); + }); + } +} diff --git a/lib/llm/ai_client.dart b/lib/llm/ai_client.dart index bb61776..ee43ea3 100644 --- a/lib/llm/ai_client.dart +++ b/lib/llm/ai_client.dart @@ -1,5 +1,6 @@ import 'package:langchain_lib/client/client.dart'; import 'package:langchain_lib/client/openai_client.dart'; +import 'package:langchain_lib/langchain_lib.dart'; class AiClient { AiClient._(); @@ -12,4 +13,16 @@ class AiClient { initOpenAi(String path) { client = OpenaiClient.fromEnv(path); } + + Stream optimizeDoc(String doc) { + final history = [ + MessageUtil.createSystemMessage( + "你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), + MessageUtil.createHumanMessage( + "请帮我改写优化以下文章。注意:1.进行文章改写时请尽量使用简体中文。\n2.只改写优化 标签中的部分。\n3.保留 标签中的内容。\n4.最终结果中删除 标签。"), + MessageUtil.createHumanMessage(doc) + ]; + + return client!.stream(history); + } } From 93c3f9c9aa2efdf0b74f86368eda76047c2bc791 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Sun, 26 May 2024 18:16:44 +0800 Subject: [PATCH 07/16] refactor: remove rust langchain ( WIP ) --- langchain_lib/lib/client/client.dart | 6 + langchain_lib/lib/client/openai_client.dart | 42 +- langchain_lib/test/test_seq_chain.dart | 3 +- langchain_lib/test/test_seq_chain2.dart | 30 + lib/app/windows.dart | 4 +- lib/llm/ai_client.dart | 11 +- lib/llm/chatchat/chatchat_config.dart | 5 +- lib/llm/editor/compose_screen.dart | 71 +- lib/llm/langchain/components/chat_ui.dart | 2 +- .../langchain/components/seq_chain_flow.dart | 4 +- lib/llm/langchain/models/tool_model.dart | 14 +- .../components/chain_flow.dart | 3 +- .../components/loading_dialog.dart | 54 +- .../notifiers/chain_flow_notifier.dart | 2 +- lib/llm/template_editor/template_editor.dart | 42 +- lib/main.dart | 8 - lib/src/rust/api/llm_api.dart | 81 - lib/src/rust/api/llm_plugin_api.dart | 10 +- lib/src/rust/api/simple.dart | 4 + lib/src/rust/frb_generated.dart | 1629 ++-------------- lib/src/rust/frb_generated.io.dart | 362 +--- lib/src/rust/frb_generated.web.dart | 362 +--- lib/src/rust/llm.dart | 59 - lib/src/rust/llm/app_flowy_model.dart | 133 -- lib/src/rust/llm/template.dart | 39 - rust/Cargo.lock | 1655 +---------------- rust/Cargo.toml | 6 +- rust/src/api/llm_api.rs | 160 -- rust/src/api/llm_plugin_api.rs | 25 +- rust/src/api/mod.rs | 1 - rust/src/api/simple.rs | 12 + rust/src/frb_generated.rs | 1547 +-------------- rust/src/llm/ai_helper.rs | 42 - rust/src/llm/app_flowy_model.rs | 177 -- rust/src/llm/internal_prompts.rs | 6 +- rust/src/llm/mod.rs | 220 --- rust/src/llm/models.rs | 40 - rust/src/llm/plugins/chat_file.rs | 19 - rust/src/llm/plugins/mind_map.rs | 82 - rust/src/llm/plugins/mod.rs | 24 - rust/src/llm/sequential_chain_builder.rs | 30 - rust/src/llm/template.rs | 676 +------ rust/src/llm/tests.rs | 263 --- 43 files changed, 572 insertions(+), 7393 deletions(-) create mode 100644 langchain_lib/test/test_seq_chain2.dart delete mode 100644 lib/src/rust/api/llm_api.dart delete mode 100644 lib/src/rust/llm.dart delete mode 100644 lib/src/rust/llm/template.dart delete mode 100644 rust/src/api/llm_api.rs delete mode 100644 rust/src/llm/ai_helper.rs delete mode 100644 rust/src/llm/models.rs delete mode 100644 rust/src/llm/plugins/mind_map.rs delete mode 100644 rust/src/llm/sequential_chain_builder.rs delete mode 100644 rust/src/llm/tests.rs diff --git a/langchain_lib/lib/client/client.dart b/langchain_lib/lib/client/client.dart index b08307f..3adde31 100644 --- a/langchain_lib/lib/client/client.dart +++ b/langchain_lib/lib/client/client.dart @@ -7,4 +7,10 @@ abstract class Client { Stream stream(List history); BaseChain? intoChain(List items); + + Future> invokeChain( + BaseChain chain, int chainLength, String input); + + Future> invokeChainWithTemplateItems( + List items); } diff --git a/langchain_lib/lib/client/openai_client.dart b/langchain_lib/lib/client/openai_client.dart index 69c708f..b734826 100644 --- a/langchain_lib/lib/client/openai_client.dart +++ b/langchain_lib/lib/client/openai_client.dart @@ -47,7 +47,9 @@ class OpenaiClient extends Client { } if (items.length == 1) { final prompt = LLMChain( - llm: model, prompt: PromptTemplate.fromTemplate(items[0].prompt)); + llm: model, + outputKey: "output", + prompt: PromptTemplate.fromTemplate("{input}")); return prompt; } else { @@ -76,4 +78,42 @@ class OpenaiClient extends Client { return seqChain; } } + + @override + Future> invokeChain( + BaseChain chain, int chainLength, String input) async { + final dynamic result; + if (chainLength == 1) { + result = (await chain.call(input))['output'].content; + } else { + result = await chain.call({"input0": input}, returnOnlyOutputs: false); + } + Map r = {}; + if (result is Map) { + for (int i = 0; i < chainLength; i++) { + if (result["input${i + 1}"] != null) { + if (result["input${i + 1}"] is AIChatMessage) { + r["input${i + 1}"] = result["input${i + 1}"].content; + } else { + r["input${i + 1}"] = result["input${i + 1}"]; + } + } + } + } else { + r["input$chainLength"] = result.toString(); + } + + return r; + } + + @override + Future> invokeChainWithTemplateItems( + List items) async { + final chain = intoChain(items); + if (chain != null) { + return invokeChain(chain, items.length, items.first.prompt); + } + + return {}; + } } diff --git a/langchain_lib/test/test_seq_chain.dart b/langchain_lib/test/test_seq_chain.dart index 1447910..99ae3c4 100644 --- a/langchain_lib/test/test_seq_chain.dart +++ b/langchain_lib/test/test_seq_chain.dart @@ -25,7 +25,8 @@ void main() { // chain.invoke(input) if (chain != null) { - chain.call({"input0": "帮我梳理rust学习路线"}, returnOnlyOutputs: false).then((v) { + client.invokeChain(chain, 2, "帮我梳理rust学习路线").then((v) { + print(v.length); print(v); }); } diff --git a/langchain_lib/test/test_seq_chain2.dart b/langchain_lib/test/test_seq_chain2.dart new file mode 100644 index 0000000..7088b99 --- /dev/null +++ b/langchain_lib/test/test_seq_chain2.dart @@ -0,0 +1,30 @@ +import 'package:langchain_lib/client/load_env.dart'; +import 'package:langchain_lib/langchain_lib.dart'; +import 'package:langchain_lib/models/template_item.dart'; + +void main() { + List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + if (envs.length != 3) { + return; + } + final client = OpenaiClient( + baseUrl: envs[0], + apiKey: envs[2], + modelName: envs[1], + ); + + BaseChain? chain = client.intoChain([ + TemplateItem( + prompt: "1+1等于多少", + index: 1, + next: null, + attrType: AttributeType.Prompt), + ]); + + // chain.invoke(input) + if (chain != null) { + client.invokeChain(chain, 1, "1+1等于多少").then((v) { + print(v); + }); + } +} diff --git a/lib/app/windows.dart b/lib/app/windows.dart index f998e77..5903226 100644 --- a/lib/app/windows.dart +++ b/lib/app/windows.dart @@ -6,7 +6,7 @@ import 'package:all_in_one/layout/layout.dart'; import 'package:all_in_one/schedule/cron_listener.dart'; import 'package:all_in_one/software_monitor/notifier/monitor_item_notifier.dart'; import 'package:all_in_one/common/logger.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; +import 'package:all_in_one/src/rust/api/simple.dart'; import 'package:all_in_one/styles/app_style.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; @@ -97,7 +97,7 @@ class __WrapperState extends ConsumerState<_Wrapper> { } final scheduleStream = CronListener.controller.stream; - final errorStream = errorMessageStream(); + final errorStream = rustErrorStream(); final stream = Platform.isWindows ? smapi.softwareWatchingWithForegroundMessageStream() diff --git a/lib/llm/ai_client.dart b/lib/llm/ai_client.dart index ee43ea3..9515038 100644 --- a/lib/llm/ai_client.dart +++ b/lib/llm/ai_client.dart @@ -1,5 +1,4 @@ import 'package:langchain_lib/client/client.dart'; -import 'package:langchain_lib/client/openai_client.dart'; import 'package:langchain_lib/langchain_lib.dart'; class AiClient { @@ -25,4 +24,14 @@ class AiClient { return client!.stream(history); } + + Stream textToMindMap(String text) { + final history = [ + MessageUtil.createSystemMessage("你是一个专业的分析师,善于整理思维导图。"), + MessageUtil.createHumanMessage( + "请帮我将以下内容转为思维导图json格式。注意:1.只需要返回json。2. json格式参考 { \"subject\":\"string\",\"subNodes\":[ { \"node\":\"string\",\" description \":\"string\",\"subNodes\":[ { \"node\":\"string\",\" description \":\"string\" } ] } ] } 。3. json不需要换行。"), + MessageUtil.createHumanMessage(text) + ]; + return client!.stream(history); + } } diff --git a/lib/llm/chatchat/chatchat_config.dart b/lib/llm/chatchat/chatchat_config.dart index cb6fd01..99949c8 100644 --- a/lib/llm/chatchat/chatchat_config.dart +++ b/lib/llm/chatchat/chatchat_config.dart @@ -1,4 +1,3 @@ -import 'package:all_in_one/src/rust/api/llm_api.dart' as llm; import 'package:dio/dio.dart'; import 'models/history.dart'; @@ -30,8 +29,8 @@ class ChatchatConfig { return _dio!; } - late String _baseUrl = llm.getLlmConfig()?.chatBase ?? ""; - late String _modelName = llm.getLlmConfig()?.name ?? ""; + late String _baseUrl = ""; + late String _modelName = ""; final String _knowledgeChat = "/chat/knowledge_base_chat"; diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 257992d..b197aa5 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; import 'package:all_in_one/isar/llm_history.dart'; +import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; @@ -12,7 +13,6 @@ import 'package:all_in_one/llm/plugins/models/mind_map_model.dart'; import 'package:all_in_one/llm/plugins/record/record_utils.dart'; import 'package:all_in_one/llm/template_editor/extension.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -37,43 +37,14 @@ class _ComposeScreenState extends ConsumerState { final uuid = const Uuid(); late String result = ""; bool isTemplateLoaded = false; + final AiClient aiClient = AiClient(); - late Stream toMapStream = mindMapStream(); + // late Stream toMapStream = mindMapStream(); @override void initState() { super.initState(); - toMapStream.listen((event) { - if (event == "!over!") { - result = result.replaceAll("\n", ""); - try { - MindMapData data = MindMapData.fromJson(jsonDecode(result)); - showGeneralDialog( - barrierColor: Colors.transparent, - barrierLabel: "dashboard from map", - barrierDismissible: true, - context: context, - pageBuilder: (c, _, __) { - return Center( - child: DashboardFromMap( - mindMapData: data, - onAddingToEditor: (p0) { - _editorState.selection ??= Selection.single( - path: [0], startOffset: 0, endOffset: 0); - _editorState.insertImageNode(p0); - }, - ), - ); - }); - } catch (_) { - return; - } - } else { - result += event; - } - }); - _widgetBuilder = (context) => Editor( // jsonString: Future(() => _jsonString), datasource: Datasource(type: DatasourceType.json, content: ""), @@ -196,7 +167,41 @@ class _ComposeScreenState extends ConsumerState { } result = ""; - textToMindMap(s: text.join("\n")); + final stream = aiClient.textToMindMap(text.join("\n")); + + stream.listen( + (event) { + result += event.outputAsString; + }, + onDone: () { + result = result.replaceAll("\n", ""); + try { + MindMapData data = + MindMapData.fromJson(jsonDecode(result)); + showGeneralDialog( + barrierColor: Colors.transparent, + barrierLabel: "dashboard from map", + barrierDismissible: true, + context: context, + pageBuilder: (c, _, __) { + return Center( + child: DashboardFromMap( + mindMapData: data, + onAddingToEditor: (p0) { + _editorState.selection ??= Selection.single( + path: [0], + startOffset: 0, + endOffset: 0); + _editorState.insertImageNode(p0); + }, + ), + ); + }); + } catch (_) { + return; + } + }, + ); }, ), SidemenuDivider(), diff --git a/lib/llm/langchain/components/chat_ui.dart b/lib/llm/langchain/components/chat_ui.dart index b05fb92..098c1e7 100644 --- a/lib/llm/langchain/components/chat_ui.dart +++ b/lib/llm/langchain/components/chat_ui.dart @@ -157,7 +157,7 @@ class _ChatUIState extends ConsumerState { } }).toList(); - if (model != null && model.toMessage()!.content != "normal") { + if (model != null && model.systemPrompt != "normal") { history.insert(0, MessageUtil.createSystemMessage(model.systemPrompt)); } diff --git a/lib/llm/langchain/components/seq_chain_flow.dart b/lib/llm/langchain/components/seq_chain_flow.dart index ebe3d23..7699cdd 100644 --- a/lib/llm/langchain/components/seq_chain_flow.dart +++ b/lib/llm/langchain/components/seq_chain_flow.dart @@ -4,7 +4,7 @@ import 'package:all_in_one/llm/langchain/extension.dart'; import 'package:all_in_one/llm/langchain/models/chains.dart'; import 'package:all_in_one/llm/langchain/notifiers/chain_notifier.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; +// import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:flutter/material.dart'; import 'package:flutter_expandable_fab/flutter_expandable_fab.dart'; import 'package:flutter_flow_chart/flutter_flow_chart.dart'; @@ -91,7 +91,7 @@ class _FlowScreenState extends ConsumerState { Chains chains = Chains(items: ref.read(chainProvider.notifier).items); final jsonStr = jsonEncode(chains.toJson()); - sequentialChainChat(jsonStr: jsonStr, query: "shoe"); + // sequentialChainChat(jsonStr: jsonStr, query: "shoe"); } }, ), diff --git a/lib/llm/langchain/models/tool_model.dart b/lib/llm/langchain/models/tool_model.dart index 75d555a..72a49b6 100644 --- a/lib/llm/langchain/models/tool_model.dart +++ b/lib/llm/langchain/models/tool_model.dart @@ -1,5 +1,3 @@ -import 'package:all_in_one/src/rust/llm.dart'; - class ToolModel { final String imgPath; final String systemPrompt; @@ -21,10 +19,10 @@ class ToolModel { ); } - LLMMessage? toMessage() { - if (type != "tool") { - return null; - } - return LLMMessage(uuid: "", content: systemPrompt, type: 1); - } + // LLMMessage? toMessage() { + // if (type != "tool") { + // return null; + // } + // return LLMMessage(uuid: "", content: systemPrompt, type: 1); + // } } diff --git a/lib/llm/template_editor/components/chain_flow.dart b/lib/llm/template_editor/components/chain_flow.dart index fa7b684..ffc6276 100644 --- a/lib/llm/template_editor/components/chain_flow.dart +++ b/lib/llm/template_editor/components/chain_flow.dart @@ -6,7 +6,7 @@ import 'dart:ui'; import 'package:all_in_one/llm/template_editor/components/connector_painter.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_state.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; +import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; import 'package:all_in_one/styles/app_style.dart'; import 'package:auto_size_text/auto_size_text.dart'; @@ -15,6 +15,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_flow_chart/flutter_flow_chart.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_tags_x/flutter_tags_x.dart'; +// import 'package:langchain_lib/models/template_item.dart'; class ChainFlow extends ConsumerStatefulWidget { const ChainFlow({super.key}); diff --git a/lib/llm/template_editor/components/loading_dialog.dart b/lib/llm/template_editor/components/loading_dialog.dart index 7830147..09c4c5d 100644 --- a/lib/llm/template_editor/components/loading_dialog.dart +++ b/lib/llm/template_editor/components/loading_dialog.dart @@ -1,6 +1,4 @@ import 'package:all_in_one/layout/styles.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; -import 'package:all_in_one/src/rust/llm/template.dart'; import 'package:blurrycontainer/blurrycontainer.dart'; import 'package:flutter/material.dart'; @@ -12,37 +10,37 @@ class LoadingDialog extends StatefulWidget { } class _LoadingDialogState extends State { - final stateStream = templateStateStream(); + // final stateStream = templateStateStream(); String state = "evaluating..."; @override void initState() { super.initState(); - stateStream.listen((event) { - if (mounted) { - switch (event) { - case TemplateRunningStage.format: - setState(() { - state = "formating..."; - }); - case TemplateRunningStage.eval: - setState(() { - state = "evaluating..."; - }); - case TemplateRunningStage.optimize: - setState(() { - state = "optimizing..."; - }); - case TemplateRunningStage.done: - setState(() { - state = "done"; - }); - Future.delayed(const Duration(milliseconds: 500), () { - Navigator.of(context).pop(); - }); - } - } - }); + // stateStream.listen((event) { + // if (mounted) { + // switch (event) { + // case TemplateRunningStage.format: + // setState(() { + // state = "formating..."; + // }); + // case TemplateRunningStage.eval: + // setState(() { + // state = "evaluating..."; + // }); + // case TemplateRunningStage.optimize: + // setState(() { + // state = "optimizing..."; + // }); + // case TemplateRunningStage.done: + // setState(() { + // state = "done"; + // }); + // Future.delayed(const Duration(milliseconds: 500), () { + // Navigator.of(context).pop(); + // }); + // } + // } + // }); } @override diff --git a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart index a13d6e5..9d92aef 100644 --- a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart +++ b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart @@ -1,5 +1,5 @@ -import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:langchain_lib/models/template_item.dart'; import 'chain_flow_state.dart'; diff --git a/lib/llm/template_editor/template_editor.dart b/lib/llm/template_editor/template_editor.dart index 475b52c..cece195 100644 --- a/lib/llm/template_editor/template_editor.dart +++ b/lib/llm/template_editor/template_editor.dart @@ -10,7 +10,7 @@ import 'package:all_in_one/llm/template_editor/components/chain_flow.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; import 'package:all_in_one/llm/template_editor/notifiers/template_notifier.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart'; +// import 'package:all_in_one/src/rust/api/llm_api.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -40,7 +40,7 @@ class _TemplateEditorState extends ConsumerState { late String _jsonString; late WidgetBuilder _widgetBuilder; - final stream = templateMessageStream(); + // final stream = templateMessageStream(); @override void initState() { @@ -83,25 +83,25 @@ class _TemplateEditorState extends ConsumerState { /// 返回的都是全文, /// 如果是stream的返回方式 /// 最好每次只返回最后的内容,不需要全文返回 - stream.listen((event) { - // print(event.response); - for (final i in _editorState.document.root.children) { - if ((i.attributes['delta'] as List).isNotEmpty) { - // Node? existsNode = null; - Map? map = null; - for (int j = 0; j < i.attributes['delta'].length; j++) { - if (i.attributes['delta'][j]["insert"] != null && - i.attributes['delta'][j]["insert"].contains(event.prompt)) { - map = i.attributes; - map['delta'][j]['insert'] = event.prompt + event.response; - } - } - if (map != null) { - i.updateAttributes(map); - } - } - } - }); + // stream.listen((event) { + // // print(event.response); + // for (final i in _editorState.document.root.children) { + // if ((i.attributes['delta'] as List).isNotEmpty) { + // // Node? existsNode = null; + // Map? map = null; + // for (int j = 0; j < i.attributes['delta'].length; j++) { + // if (i.attributes['delta'][j]["insert"] != null && + // i.attributes['delta'][j]["insert"].contains(event.prompt)) { + // map = i.attributes; + // map['delta'][j]['insert'] = event.prompt + event.response; + // } + // } + // if (map != null) { + // i.updateAttributes(map); + // } + // } + // } + // }); } final GlobalKey key = GlobalKey(); diff --git a/lib/main.dart b/lib/main.dart index 8728413..e6f1464 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -3,11 +3,9 @@ import 'dart:io'; import 'package:all_in_one/app/linux.dart'; import 'package:all_in_one/app/windows.dart'; import 'package:all_in_one/common/dev_utils.dart'; -import 'package:all_in_one/common/logger.dart'; import 'package:all_in_one/isar/database.dart'; import 'package:all_in_one/isar/software.dart'; import 'package:all_in_one/llm/ai_client.dart'; -import 'package:all_in_one/src/rust/api/llm_api.dart' as llm; import 'package:all_in_one/src/rust/api/software_monitor_api.dart' as smapi; import 'package:all_in_one/src/rust/api/sub_window_api.dart' as sw; import 'package:all_in_one/src/rust/api/system_monitor_api.dart' as sm; @@ -35,12 +33,6 @@ Future main() async { AiClient aiClient = AiClient(); aiClient.initOpenAi(DevUtils.env); - if (Platform.isWindows) { - llm.initLlm(p: DevUtils.env); - llm.initPromptFromPath(s: DevUtils.prompt); - logger.info("CHAT_CHAT_BASE :${llm.getLlmConfig()?.chatBase}"); - } - IsarDatabase database = IsarDatabase(); await database.initialDatabase(); diff --git a/lib/src/rust/api/llm_api.dart b/lib/src/rust/api/llm_api.dart deleted file mode 100644 index 0600444..0000000 --- a/lib/src/rust/api/llm_api.dart +++ /dev/null @@ -1,81 +0,0 @@ -// This file is automatically generated, so please do not edit it. -// Generated by `flutter_rust_bridge`@ 2.0.0-dev.35. - -// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import - -import '../errors.dart'; -import '../frb_generated.dart'; -import '../llm.dart'; -import '../llm/app_flowy_model.dart'; -import '../llm/template.dart'; -import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; - -void initLlm({required String p, dynamic hint}) => - RustLib.instance.api.crateApiLlmApiInitLlm(p: p, hint: hint); - -EnvParams? getLlmConfig({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiGetLlmConfig(hint: hint); - -Stream llmMessageStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiLlmMessageStream(hint: hint); - -Stream aiHelperMessageStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiAiHelperMessageStream(hint: hint); - -Stream templateMessageStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiTemplateMessageStream(hint: hint); - -Stream errorMessageStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiErrorMessageStream(hint: hint); - -Stream templateStateStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmApiTemplateStateStream(hint: hint); - -Future chat( - {String? uuid, - List? history, - required bool stream, - required String query, - dynamic hint}) => - RustLib.instance.api.crateApiLlmApiChat( - uuid: uuid, history: history, stream: stream, query: query, hint: hint); - -Future sequentialChainChat( - {required String jsonStr, required String query, dynamic hint}) => - RustLib.instance.api.crateApiLlmApiSequentialChainChat( - jsonStr: jsonStr, query: query, hint: hint); - -Future templateRenderer({required String template, dynamic hint}) => - RustLib.instance.api - .crateApiLlmApiTemplateRenderer(template: template, hint: hint); - -Future> templateToPrompts( - {required String template, dynamic hint}) => - RustLib.instance.api - .crateApiLlmApiTemplateToPrompts(template: template, hint: hint); - -Future generateFromTemplate( - {required List<(String, int, int?, AttributeType, String?)> v, - required bool enablePlugin, - dynamic hint}) => - RustLib.instance.api.crateApiLlmApiGenerateFromTemplate( - v: v, enablePlugin: enablePlugin, hint: hint); - -Future optimizeDoc({required String s, dynamic hint}) => - RustLib.instance.api.crateApiLlmApiOptimizeDoc(s: s, hint: hint); - -Root? getDocRootFromStr({required String s, dynamic hint}) => - RustLib.instance.api.crateApiLlmApiGetDocRootFromStr(s: s, hint: hint); - -Future aiHelperQuickRequest( - {required String s, - required String tone, - required String lang, - required String length, - required List extra, - dynamic hint}) => - RustLib.instance.api.crateApiLlmApiAiHelperQuickRequest( - s: s, tone: tone, lang: lang, length: length, extra: extra, hint: hint); - -void initPromptFromPath({required String s, dynamic hint}) => - RustLib.instance.api.crateApiLlmApiInitPromptFromPath(s: s, hint: hint); diff --git a/lib/src/rust/api/llm_plugin_api.dart b/lib/src/rust/api/llm_plugin_api.dart index 600e502..11c4f39 100644 --- a/lib/src/rust/api/llm_plugin_api.dart +++ b/lib/src/rust/api/llm_plugin_api.dart @@ -4,6 +4,7 @@ // ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import import '../frb_generated.dart'; +import '../llm/app_flowy_model.dart'; import '../llm/plugins/chat_db.dart'; import '../llm/plugins/chat_db/mysql.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; @@ -21,8 +22,7 @@ Future?> eval( RustLib.instance.api.crateApiLlmPluginApiEval( sqlStr: sqlStr, db: db, keys: keys, hint: hint); -Future textToMindMap({required String s, dynamic hint}) => - RustLib.instance.api.crateApiLlmPluginApiTextToMindMap(s: s, hint: hint); - -Stream mindMapStream({dynamic hint}) => - RustLib.instance.api.crateApiLlmPluginApiMindMapStream(hint: hint); +Future> templateToPrompts( + {required String template, dynamic hint}) => + RustLib.instance.api + .crateApiLlmPluginApiTemplateToPrompts(template: template, hint: hint); diff --git a/lib/src/rust/api/simple.dart b/lib/src/rust/api/simple.dart index 3e57bb0..bf5a466 100644 --- a/lib/src/rust/api/simple.dart +++ b/lib/src/rust/api/simple.dart @@ -3,8 +3,12 @@ // ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import +import '../errors.dart'; import '../frb_generated.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; String greet({required String name, dynamic hint}) => RustLib.instance.api.crateApiSimpleGreet(name: name, hint: hint); + +Stream rustErrorStream({dynamic hint}) => + RustLib.instance.api.crateApiSimpleRustErrorStream(hint: hint); diff --git a/lib/src/rust/frb_generated.dart b/lib/src/rust/frb_generated.dart index 4a89fd9..de6dd5e 100644 --- a/lib/src/rust/frb_generated.dart +++ b/lib/src/rust/frb_generated.dart @@ -3,7 +3,6 @@ // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field -import 'api/llm_api.dart'; import 'api/llm_plugin_api.dart'; import 'api/process_port_mapper_api.dart'; import 'api/simple.dart'; @@ -14,11 +13,9 @@ import 'dart:async'; import 'dart:convert'; import 'errors.dart'; import 'frb_generated.io.dart' if (dart.library.html) 'frb_generated.web.dart'; -import 'llm.dart'; import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; -import 'llm/template.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; import 'software_monitor/software.dart'; import 'system_monitor.dart'; @@ -70,7 +67,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.0.0-dev.35'; @override - int get rustContentHash => 1113812267; + int get rustContentHash => -576783616; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -81,56 +78,6 @@ class RustLib extends BaseEntrypoint { } abstract class RustLibApi extends BaseApi { - Stream crateApiLlmApiAiHelperMessageStream({dynamic hint}); - - Future crateApiLlmApiAiHelperQuickRequest( - {required String s, - required String tone, - required String lang, - required String length, - required List extra, - dynamic hint}); - - Future crateApiLlmApiChat( - {String? uuid, - List? history, - required bool stream, - required String query, - dynamic hint}); - - Stream crateApiLlmApiErrorMessageStream({dynamic hint}); - - Future crateApiLlmApiGenerateFromTemplate( - {required List<(String, int, int?, AttributeType, String?)> v, - required bool enablePlugin, - dynamic hint}); - - Root? crateApiLlmApiGetDocRootFromStr({required String s, dynamic hint}); - - EnvParams? crateApiLlmApiGetLlmConfig({dynamic hint}); - - void crateApiLlmApiInitLlm({required String p, dynamic hint}); - - void crateApiLlmApiInitPromptFromPath({required String s, dynamic hint}); - - Stream crateApiLlmApiLlmMessageStream({dynamic hint}); - - Future crateApiLlmApiOptimizeDoc({required String s, dynamic hint}); - - Future crateApiLlmApiSequentialChainChat( - {required String jsonStr, required String query, dynamic hint}); - - Stream crateApiLlmApiTemplateMessageStream({dynamic hint}); - - Future crateApiLlmApiTemplateRenderer( - {required String template, dynamic hint}); - - Stream crateApiLlmApiTemplateStateStream( - {dynamic hint}); - - Future> - crateApiLlmApiTemplateToPrompts({required String template, dynamic hint}); - Future?> crateApiLlmPluginApiEval( {required String sqlStr, required DatabaseInfo db, @@ -140,10 +87,9 @@ abstract class RustLibApi extends BaseApi { Future>> crateApiLlmPluginApiGetMysqlTableInfo( {required DatabaseInfo s, dynamic hint}); - Stream crateApiLlmPluginApiMindMapStream({dynamic hint}); - - Future crateApiLlmPluginApiTextToMindMap( - {required String s, dynamic hint}); + Future> + crateApiLlmPluginApiTemplateToPrompts( + {required String template, dynamic hint}); Future> crateApiProcessPortMapperApiGetProcessPortMappers({dynamic hint}); @@ -152,6 +98,8 @@ abstract class RustLibApi extends BaseApi { Future crateApiSimpleInitApp({dynamic hint}); + Stream crateApiSimpleRustErrorStream({dynamic hint}); + Future crateApiSoftwareMonitorApiAddToWatchingList( {required int id, required String name, dynamic hint}); @@ -181,465 +129,23 @@ abstract class RustLibApi extends BaseApi { Stream crateApiSystemMonitorApiSystemMonitorMessageStream( {dynamic hint}); - RustArcIncrementStrongCountFnType - get rust_arc_increment_strong_count_RustSimpleNotifyLibPinWindowItem; - - RustArcDecrementStrongCountFnType - get rust_arc_decrement_strong_count_RustSimpleNotifyLibPinWindowItem; - - CrossPlatformFinalizerArg - get rust_arc_decrement_strong_count_RustSimpleNotifyLibPinWindowItemPtr; -} - -class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { - RustLibApiImpl({ - required super.handler, - required super.wire, - required super.generalizedFrbRustBinding, - required super.portManager, - }); - - @override - Stream crateApiLlmApiAiHelperMessageStream({dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_String_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmApiAiHelperMessageStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmApiAiHelperMessageStreamConstMeta => - const TaskConstMeta( - debugName: "ai_helper_message_stream", - argNames: ["s"], - ); - - @override - Future crateApiLlmApiAiHelperQuickRequest( - {required String s, - required String tone, - required String lang, - required String length, - required List extra, - dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(s, serializer); - sse_encode_String(tone, serializer); - sse_encode_String(lang, serializer); - sse_encode_String(length, serializer); - sse_encode_list_String(extra, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 15, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiAiHelperQuickRequestConstMeta, - argValues: [s, tone, lang, length, extra], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiAiHelperQuickRequestConstMeta => - const TaskConstMeta( - debugName: "ai_helper_quick_request", - argNames: ["s", "tone", "lang", "length", "extra"], - ); - - @override - Future crateApiLlmApiChat( - {String? uuid, - List? history, - required bool stream, - required String query, - dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_opt_String(uuid, serializer); - sse_encode_opt_list_llm_message(history, serializer); - sse_encode_bool(stream, serializer); - sse_encode_String(query, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 8, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiChatConstMeta, - argValues: [uuid, history, stream, query], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiChatConstMeta => const TaskConstMeta( - debugName: "chat", - argNames: ["uuid", "history", "stream", "query"], - ); - - @override - Stream crateApiLlmApiErrorMessageStream({dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_rust_error_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 6)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmApiErrorMessageStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmApiErrorMessageStreamConstMeta => - const TaskConstMeta( - debugName: "error_message_stream", - argNames: ["s"], - ); - - @override - Future crateApiLlmApiGenerateFromTemplate( - {required List<(String, int, int?, AttributeType, String?)> v, - required bool enablePlugin, - dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - v, serializer); - sse_encode_bool(enablePlugin, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 12, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiGenerateFromTemplateConstMeta, - argValues: [v, enablePlugin], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiGenerateFromTemplateConstMeta => - const TaskConstMeta( - debugName: "generate_from_template", - argNames: ["v", "enablePlugin"], - ); - - @override - Root? crateApiLlmApiGetDocRootFromStr({required String s, dynamic hint}) { - return handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 14)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_opt_box_autoadd_root, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiGetDocRootFromStrConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiGetDocRootFromStrConstMeta => - const TaskConstMeta( - debugName: "get_doc_root_from_str", - argNames: ["s"], - ); - - @override - EnvParams? crateApiLlmApiGetLlmConfig({dynamic hint}) { - return handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 2)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_opt_box_autoadd_env_params, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiGetLlmConfigConstMeta, - argValues: [], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiGetLlmConfigConstMeta => const TaskConstMeta( - debugName: "get_llm_config", - argNames: [], - ); - - @override - void crateApiLlmApiInitLlm({required String p, dynamic hint}) { - return handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(p, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 1)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiInitLlmConstMeta, - argValues: [p], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiInitLlmConstMeta => const TaskConstMeta( - debugName: "init_llm", - argNames: ["p"], - ); - - @override - void crateApiLlmApiInitPromptFromPath({required String s, dynamic hint}) { - return handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 16)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiInitPromptFromPathConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiInitPromptFromPathConstMeta => - const TaskConstMeta( - debugName: "init_prompt_from_path", - argNames: ["s"], - ); - - @override - Stream crateApiLlmApiLlmMessageStream({dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_llm_message_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 3)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmApiLlmMessageStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmApiLlmMessageStreamConstMeta => - const TaskConstMeta( - debugName: "llm_message_stream", - argNames: ["s"], - ); - - @override - Future crateApiLlmApiOptimizeDoc({required String s, dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(s, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 13, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_String, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiOptimizeDocConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiOptimizeDocConstMeta => const TaskConstMeta( - debugName: "optimize_doc", - argNames: ["s"], - ); - - @override - Future crateApiLlmApiSequentialChainChat( - {required String jsonStr, required String query, dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(jsonStr, serializer); - sse_encode_String(query, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 9, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiSequentialChainChatConstMeta, - argValues: [jsonStr, query], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiSequentialChainChatConstMeta => - const TaskConstMeta( - debugName: "sequential_chain_chat", - argNames: ["jsonStr", "query"], - ); - - @override - Stream crateApiLlmApiTemplateMessageStream({dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_template_result_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 5)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmApiTemplateMessageStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmApiTemplateMessageStreamConstMeta => - const TaskConstMeta( - debugName: "template_message_stream", - argNames: ["s"], - ); - - @override - Future crateApiLlmApiTemplateRenderer( - {required String template, dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(template, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 10, port: port_); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_opt_String, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiTemplateRendererConstMeta, - argValues: [template], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmApiTemplateRendererConstMeta => - const TaskConstMeta( - debugName: "template_renderer", - argNames: ["template"], - ); - - @override - Stream crateApiLlmApiTemplateStateStream( - {dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_template_running_stage_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 7)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmApiTemplateStateStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmApiTemplateStateStreamConstMeta => - const TaskConstMeta( - debugName: "template_state_stream", - argNames: ["s"], - ); - - @override - Future> - crateApiLlmApiTemplateToPrompts( - {required String template, dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(template, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 11, port: port_); - }, - codec: SseCodec( - decodeSuccessData: - sse_decode_list_record_string_attribute_type_opt_string, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmApiTemplateToPromptsConstMeta, - argValues: [template], - apiImpl: this, - hint: hint, - )); - } + RustArcIncrementStrongCountFnType + get rust_arc_increment_strong_count_RustSimpleNotifyLibPinWindowItem; - TaskConstMeta get kCrateApiLlmApiTemplateToPromptsConstMeta => - const TaskConstMeta( - debugName: "template_to_prompts", - argNames: ["template"], - ); + RustArcDecrementStrongCountFnType + get rust_arc_decrement_strong_count_RustSimpleNotifyLibPinWindowItem; + + CrossPlatformFinalizerArg + get rust_arc_decrement_strong_count_RustSimpleNotifyLibPinWindowItemPtr; +} + +class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { + RustLibApiImpl({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); @override Future?> crateApiLlmPluginApiEval( @@ -654,7 +160,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_box_autoadd_database_info(db, serializer); sse_encode_list_record_string_cell_type(keys, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 18, port: port_); + funcId: 2, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_opt_Map_String_String, @@ -680,7 +186,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_box_autoadd_database_info(s, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 17, port: port_); + funcId: 1, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_list_table_info, @@ -700,57 +206,32 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); @override - Stream crateApiLlmPluginApiMindMapStream({dynamic hint}) { - final s = RustStreamSink(); - handler.executeSync(SyncTask( - callFfi: () { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_StreamSink_String_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 20)!; - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_AnyhowException, - ), - constMeta: kCrateApiLlmPluginApiMindMapStreamConstMeta, - argValues: [s], - apiImpl: this, - hint: hint, - )); - return s.stream; - } - - TaskConstMeta get kCrateApiLlmPluginApiMindMapStreamConstMeta => - const TaskConstMeta( - debugName: "mind_map_stream", - argNames: ["s"], - ); - - @override - Future crateApiLlmPluginApiTextToMindMap( - {required String s, dynamic hint}) { + Future> + crateApiLlmPluginApiTemplateToPrompts( + {required String template, dynamic hint}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(s, serializer); + sse_encode_String(template, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 19, port: port_); + funcId: 3, port: port_); }, codec: SseCodec( - decodeSuccessData: sse_decode_unit, + decodeSuccessData: + sse_decode_list_record_string_attribute_type_opt_string, decodeErrorData: null, ), - constMeta: kCrateApiLlmPluginApiTextToMindMapConstMeta, - argValues: [s], + constMeta: kCrateApiLlmPluginApiTemplateToPromptsConstMeta, + argValues: [template], apiImpl: this, hint: hint, )); } - TaskConstMeta get kCrateApiLlmPluginApiTextToMindMapConstMeta => + TaskConstMeta get kCrateApiLlmPluginApiTemplateToPromptsConstMeta => const TaskConstMeta( - debugName: "text_to_mind_map", - argNames: ["s"], + debugName: "template_to_prompts", + argNames: ["template"], ); @override @@ -760,7 +241,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 21, port: port_); + funcId: 4, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_process_port_mapper, @@ -786,7 +267,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(name, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 22)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 5)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -810,7 +291,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 23, port: port_); + funcId: 6, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -828,6 +309,33 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: [], ); + @override + Stream crateApiSimpleRustErrorStream({dynamic hint}) { + final s = RustStreamSink(); + handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_StreamSink_rust_error_Sse(s, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 7)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiSimpleRustErrorStreamConstMeta, + argValues: [s], + apiImpl: this, + hint: hint, + )); + return s.stream; + } + + TaskConstMeta get kCrateApiSimpleRustErrorStreamConstMeta => + const TaskConstMeta( + debugName: "rust_error_stream", + argNames: ["s"], + ); + @override Future crateApiSoftwareMonitorApiAddToWatchingList( {required int id, required String name, dynamic hint}) { @@ -837,7 +345,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_64(id, serializer); sse_encode_String(name, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 28, port: port_); + funcId: 12, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -863,7 +371,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 25, port: port_); + funcId: 9, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_software, @@ -890,7 +398,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_list_record_i_64_string(items, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 24, port: port_); + funcId: 8, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -917,7 +425,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_i_64(id, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 29, port: port_); + funcId: 13, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -945,7 +453,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_list_prim_i_64_strict_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 26)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 10)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -977,7 +485,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_record_list_prim_i_64_strict_string_Sse( s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 27)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 11)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -1005,7 +513,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 30, port: port_); + funcId: 14, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -1033,7 +541,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( data, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 31, port: port_); + funcId: 15, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -1058,7 +566,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 33, port: port_); + funcId: 17, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -1085,7 +593,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_monitor_info_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 32)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 16)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -1143,12 +651,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return RustSimpleNotifyLibPinWindowItem.dcoDecode(raw as List); } - @protected - RustStreamSink dco_decode_StreamSink_String_Sse(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - throw UnimplementedError(); - } - @protected RustStreamSink dco_decode_StreamSink_list_prim_i_64_strict_Sse( dynamic raw) { @@ -1156,13 +658,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { throw UnimplementedError(); } - @protected - RustStreamSink dco_decode_StreamSink_llm_message_Sse( - dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - throw UnimplementedError(); - } - @protected RustStreamSink dco_decode_StreamSink_monitor_info_Sse( dynamic raw) { @@ -1184,20 +679,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { throw UnimplementedError(); } - @protected - RustStreamSink dco_decode_StreamSink_template_result_Sse( - dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - throw UnimplementedError(); - } - - @protected - RustStreamSink - dco_decode_StreamSink_template_running_stage_Sse(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - throw UnimplementedError(); - } - @protected String dco_decode_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1210,38 +691,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return AttributeType.values[raw as int]; } - @protected - Attributes dco_decode_attributes(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 4) - throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); - return Attributes( - bold: dco_decode_opt_box_autoadd_bool(arr[0]), - italic: dco_decode_opt_box_autoadd_bool(arr[1]), - file: dco_decode_opt_String(arr[2]), - sql: dco_decode_opt_String(arr[3]), - ); - } - - @protected - bool dco_decode_bool(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw as bool; - } - - @protected - Attributes dco_decode_box_autoadd_attributes(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_attributes(raw); - } - - @protected - bool dco_decode_box_autoadd_bool(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw as bool; - } - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1254,54 +703,18 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_database_info(raw); } - @protected - EnvParams dco_decode_box_autoadd_env_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_env_params(raw); - } - - @protected - int dco_decode_box_autoadd_i_64(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_i_64(raw); - } - @protected MemoryInfo dco_decode_box_autoadd_memory_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return dco_decode_memory_info(raw); } - @protected - Root dco_decode_box_autoadd_root(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_root(raw); - } - - @protected - int dco_decode_box_autoadd_u_32(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw as int; - } - @protected CellType dco_decode_cell_type(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return CellType.values[raw as int]; } - @protected - Children dco_decode_children(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return Children( - typeField: dco_decode_String(arr[0]), - data: dco_decode_data(arr[1]), - ); - } - @protected CpuInfo dco_decode_cpu_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1313,19 +726,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - Data dco_decode_data(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return Data( - level: dco_decode_opt_box_autoadd_i_64(arr[0]), - delta: dco_decode_list_delum(arr[1]), - align: dco_decode_opt_String(arr[2]), - ); - } - @protected DatabaseInfo dco_decode_database_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1342,44 +742,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - Delum dco_decode_delum(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return Delum( - insert: dco_decode_String(arr[0]), - attributes: dco_decode_opt_box_autoadd_attributes(arr[1]), - ); - } - - @protected - Document dco_decode_document(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return Document( - typeField: dco_decode_String(arr[0]), - children: dco_decode_list_children(arr[1]), - ); - } - - @protected - EnvParams dco_decode_env_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 4) - throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); - return EnvParams( - base: dco_decode_String(arr[0]), - name: dco_decode_String(arr[1]), - chatBase: dco_decode_String(arr[2]), - sk: dco_decode_opt_String(arr[3]), - ); - } - @protected ErrorModule dco_decode_error_module(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1421,36 +783,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { .toList(); } - @protected - List dco_decode_list_String(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_String).toList(); - } - - @protected - List dco_decode_list_children(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_children).toList(); - } - - @protected - List dco_decode_list_delum(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_delum).toList(); - } - @protected List> dco_decode_list_list_table_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return (raw as List).map(dco_decode_list_table_info).toList(); } - @protected - List dco_decode_list_llm_message(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_llm_message).toList(); - } - @protected List dco_decode_list_mounted_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1505,17 +843,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_record_string_string).toList(); } - @protected - List<(String, int, int?, AttributeType, String?)> - dco_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List) - .map( - dco_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string) - .toList(); - } - @protected List dco_decode_list_software(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1540,19 +867,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_table_info).toList(); } - @protected - LLMMessage dco_decode_llm_message(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return LLMMessage( - uuid: dco_decode_String(arr[0]), - content: dco_decode_String(arr[1]), - type: dco_decode_u_8(arr[2]), - ); - } - @protected MemoryInfo dco_decode_memory_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1586,79 +900,37 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final arr = raw as List; if (arr.length != 5) throw Exception('unexpected arr length: expect 5 but see ${arr.length}'); - return MountedInfo( - disk: dco_decode_String(arr[0]), - name: dco_decode_String(arr[1]), - fs: dco_decode_String(arr[2]), - available: dco_decode_u_64(arr[3]), - total: dco_decode_u_64(arr[4]), - ); - } - - @protected - Map? dco_decode_opt_Map_String_String(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_Map_String_String(raw); - } - - @protected - String? dco_decode_opt_String(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_String(raw); - } - - @protected - Attributes? dco_decode_opt_box_autoadd_attributes(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_attributes(raw); - } - - @protected - bool? dco_decode_opt_box_autoadd_bool(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_bool(raw); - } - - @protected - CpuInfo? dco_decode_opt_box_autoadd_cpu_info(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_cpu_info(raw); - } - - @protected - EnvParams? dco_decode_opt_box_autoadd_env_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_env_params(raw); - } - - @protected - int? dco_decode_opt_box_autoadd_i_64(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_i_64(raw); + return MountedInfo( + disk: dco_decode_String(arr[0]), + name: dco_decode_String(arr[1]), + fs: dco_decode_String(arr[2]), + available: dco_decode_u_64(arr[3]), + total: dco_decode_u_64(arr[4]), + ); } @protected - MemoryInfo? dco_decode_opt_box_autoadd_memory_info(dynamic raw) { + Map? dco_decode_opt_Map_String_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_memory_info(raw); + return raw == null ? null : dco_decode_Map_String_String(raw); } @protected - Root? dco_decode_opt_box_autoadd_root(dynamic raw) { + String? dco_decode_opt_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_root(raw); + return raw == null ? null : dco_decode_String(raw); } @protected - int? dco_decode_opt_box_autoadd_u_32(dynamic raw) { + CpuInfo? dco_decode_opt_box_autoadd_cpu_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_u_32(raw); + return raw == null ? null : dco_decode_box_autoadd_cpu_info(raw); } @protected - List? dco_decode_opt_list_llm_message(dynamic raw) { + MemoryInfo? dco_decode_opt_box_autoadd_memory_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_list_llm_message(raw); + return raw == null ? null : dco_decode_box_autoadd_memory_info(raw); } @protected @@ -1767,40 +1039,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) dco_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 5) { - throw Exception('Expected 5 elements, got ${arr.length}'); - } - return ( - dco_decode_String(arr[0]), - dco_decode_u_32(arr[1]), - dco_decode_opt_box_autoadd_u_32(arr[2]), - dco_decode_attribute_type(arr[3]), - dco_decode_opt_String(arr[4]), - ); - } - - @protected - Root dco_decode_root(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) - throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return Root( - document: dco_decode_document(arr[0]), - ); - } - @protected RustError dco_decode_rust_error(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1865,25 +1103,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - TemplateResult dco_decode_template_result(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return TemplateResult( - prompt: dco_decode_String(arr[0]), - index: dco_decode_u_32(arr[1]), - response: dco_decode_String(arr[2]), - ); - } - - @protected - TemplateRunningStage dco_decode_template_running_stage(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return TemplateRunningStage.values[raw as int]; - } - @protected int dco_decode_u_32(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1947,13 +1166,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_decode_usize(deserializer), sse_decode_i_32(deserializer)); } - @protected - RustStreamSink sse_decode_StreamSink_String_Sse( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - throw UnimplementedError('Unreachable ()'); - } - @protected RustStreamSink sse_decode_StreamSink_list_prim_i_64_strict_Sse( SseDeserializer deserializer) { @@ -1961,13 +1173,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { throw UnimplementedError('Unreachable ()'); } - @protected - RustStreamSink sse_decode_StreamSink_llm_message_Sse( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - throw UnimplementedError('Unreachable ()'); - } - @protected RustStreamSink sse_decode_StreamSink_monitor_info_Sse( SseDeserializer deserializer) { @@ -1990,21 +1195,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { throw UnimplementedError('Unreachable ()'); } - @protected - RustStreamSink sse_decode_StreamSink_template_result_Sse( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - throw UnimplementedError('Unreachable ()'); - } - - @protected - RustStreamSink - sse_decode_StreamSink_template_running_stage_Sse( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - throw UnimplementedError('Unreachable ()'); - } - @protected String sse_decode_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2019,35 +1209,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return AttributeType.values[inner]; } - @protected - Attributes sse_decode_attributes(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_bold = sse_decode_opt_box_autoadd_bool(deserializer); - var var_italic = sse_decode_opt_box_autoadd_bool(deserializer); - var var_file = sse_decode_opt_String(deserializer); - var var_sql = sse_decode_opt_String(deserializer); - return Attributes( - bold: var_bold, italic: var_italic, file: var_file, sql: var_sql); - } - - @protected - bool sse_decode_bool(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return deserializer.buffer.getUint8() != 0; - } - - @protected - Attributes sse_decode_box_autoadd_attributes(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_attributes(deserializer)); - } - - @protected - bool sse_decode_box_autoadd_bool(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_bool(deserializer)); - } - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2061,36 +1222,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_database_info(deserializer)); } - @protected - EnvParams sse_decode_box_autoadd_env_params(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_env_params(deserializer)); - } - - @protected - int sse_decode_box_autoadd_i_64(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_i_64(deserializer)); - } - @protected MemoryInfo sse_decode_box_autoadd_memory_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs return (sse_decode_memory_info(deserializer)); } - @protected - Root sse_decode_box_autoadd_root(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_root(deserializer)); - } - - @protected - int sse_decode_box_autoadd_u_32(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_u_32(deserializer)); - } - @protected CellType sse_decode_cell_type(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2098,14 +1235,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return CellType.values[inner]; } - @protected - Children sse_decode_children(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_typeField = sse_decode_String(deserializer); - var var_data = sse_decode_data(deserializer); - return Children(typeField: var_typeField, data: var_data); - } - @protected CpuInfo sse_decode_cpu_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2113,15 +1242,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return CpuInfo(current: var_current); } - @protected - Data sse_decode_data(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_level = sse_decode_opt_box_autoadd_i_64(deserializer); - var var_delta = sse_decode_list_delum(deserializer); - var var_align = sse_decode_opt_String(deserializer); - return Data(level: var_level, delta: var_delta, align: var_align); - } - @protected DatabaseInfo sse_decode_database_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2140,33 +1260,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { database: var_database); } - @protected - Delum sse_decode_delum(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_insert = sse_decode_String(deserializer); - var var_attributes = sse_decode_opt_box_autoadd_attributes(deserializer); - return Delum(insert: var_insert, attributes: var_attributes); - } - - @protected - Document sse_decode_document(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_typeField = sse_decode_String(deserializer); - var var_children = sse_decode_list_children(deserializer); - return Document(typeField: var_typeField, children: var_children); - } - - @protected - EnvParams sse_decode_env_params(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_base = sse_decode_String(deserializer); - var var_name = sse_decode_String(deserializer); - var var_chatBase = sse_decode_String(deserializer); - var var_sk = sse_decode_opt_String(deserializer); - return EnvParams( - base: var_base, name: var_name, chatBase: var_chatBase, sk: var_sk); - } - @protected ErrorModule sse_decode_error_module(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2215,42 +1308,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List sse_decode_list_String(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_String(deserializer)); - } - return ans_; - } - - @protected - List sse_decode_list_children(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_children(deserializer)); - } - return ans_; - } - - @protected - List sse_decode_list_delum(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_delum(deserializer)); - } - return ans_; - } - @protected List> sse_decode_list_list_table_info( SseDeserializer deserializer) { @@ -2264,18 +1321,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List sse_decode_list_llm_message(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_llm_message(deserializer)); - } - return ans_; - } - @protected List sse_decode_list_mounted_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2369,22 +1414,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List<(String, int, int?, AttributeType, String?)> - sse_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = <(String, int, int?, AttributeType, String?)>[]; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add( - sse_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - deserializer)); - } - return ans_; - } - @protected List sse_decode_list_software(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2434,15 +1463,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - LLMMessage sse_decode_llm_message(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_uuid = sse_decode_String(deserializer); - var var_content = sse_decode_String(deserializer); - var var_type = sse_decode_u_8(deserializer); - return LLMMessage(uuid: var_uuid, content: var_content, type: var_type); - } - @protected MemoryInfo sse_decode_memory_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2475,135 +1495,55 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_fs = sse_decode_String(deserializer); var var_available = sse_decode_u_64(deserializer); var var_total = sse_decode_u_64(deserializer); - return MountedInfo( - disk: var_disk, - name: var_name, - fs: var_fs, - available: var_available, - total: var_total); - } - - @protected - Map? sse_decode_opt_Map_String_String( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_Map_String_String(deserializer)); - } else { - return null; - } - } - - @protected - String? sse_decode_opt_String(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_String(deserializer)); - } else { - return null; - } - } - - @protected - Attributes? sse_decode_opt_box_autoadd_attributes( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_attributes(deserializer)); - } else { - return null; - } - } - - @protected - bool? sse_decode_opt_box_autoadd_bool(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_bool(deserializer)); - } else { - return null; - } - } - - @protected - CpuInfo? sse_decode_opt_box_autoadd_cpu_info(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_cpu_info(deserializer)); - } else { - return null; - } - } - - @protected - EnvParams? sse_decode_opt_box_autoadd_env_params( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_env_params(deserializer)); - } else { - return null; - } - } - - @protected - int? sse_decode_opt_box_autoadd_i_64(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_i_64(deserializer)); - } else { - return null; - } + return MountedInfo( + disk: var_disk, + name: var_name, + fs: var_fs, + available: var_available, + total: var_total); } @protected - MemoryInfo? sse_decode_opt_box_autoadd_memory_info( + Map? sse_decode_opt_Map_String_String( SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_memory_info(deserializer)); + return (sse_decode_Map_String_String(deserializer)); } else { return null; } } @protected - Root? sse_decode_opt_box_autoadd_root(SseDeserializer deserializer) { + String? sse_decode_opt_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_root(deserializer)); + return (sse_decode_String(deserializer)); } else { return null; } } @protected - int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer) { + CpuInfo? sse_decode_opt_box_autoadd_cpu_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_u_32(deserializer)); + return (sse_decode_box_autoadd_cpu_info(deserializer)); } else { return null; } } @protected - List? sse_decode_opt_list_llm_message( + MemoryInfo? sse_decode_opt_box_autoadd_memory_info( SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs if (sse_decode_bool(deserializer)) { - return (sse_decode_list_llm_message(deserializer)); + return (sse_decode_box_autoadd_memory_info(deserializer)); } else { return null; } @@ -2717,31 +1657,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (var_field0, var_field1); } - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) sse_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_field0 = sse_decode_String(deserializer); - var var_field1 = sse_decode_u_32(deserializer); - var var_field2 = sse_decode_opt_box_autoadd_u_32(deserializer); - var var_field3 = sse_decode_attribute_type(deserializer); - var var_field4 = sse_decode_opt_String(deserializer); - return (var_field0, var_field1, var_field2, var_field3, var_field4); - } - - @protected - Root sse_decode_root(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_document = sse_decode_document(deserializer); - return Root(document: var_document); - } - @protected RustError sse_decode_rust_error(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2793,24 +1708,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { dataType: var_dataType); } - @protected - TemplateResult sse_decode_template_result(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_prompt = sse_decode_String(deserializer); - var var_index = sse_decode_u_32(deserializer); - var var_response = sse_decode_String(deserializer); - return TemplateResult( - prompt: var_prompt, index: var_index, response: var_response); - } - - @protected - TemplateRunningStage sse_decode_template_running_stage( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var inner = sse_decode_i_32(deserializer); - return TemplateRunningStage.values[inner]; - } - @protected int sse_decode_u_32(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2840,6 +1737,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return deserializer.buffer.getUint64(); } + @protected + bool sse_decode_bool(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint8() != 0; + } + @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer) { @@ -2871,17 +1774,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_usize(self.sseEncode(move: null), serializer); } - @protected - void sse_encode_StreamSink_String_Sse( - RustStreamSink self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String( - self.setupAndSerialize( - codec: SseCodec( - decodeSuccessData: sse_decode_String, decodeErrorData: null)), - serializer); - } - @protected void sse_encode_StreamSink_list_prim_i_64_strict_Sse( RustStreamSink self, SseSerializer serializer) { @@ -2894,18 +1786,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer); } - @protected - void sse_encode_StreamSink_llm_message_Sse( - RustStreamSink self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String( - self.setupAndSerialize( - codec: SseCodec( - decodeSuccessData: sse_decode_llm_message, - decodeErrorData: null)), - serializer); - } - @protected void sse_encode_StreamSink_monitor_info_Sse( RustStreamSink self, SseSerializer serializer) { @@ -2943,30 +1823,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer); } - @protected - void sse_encode_StreamSink_template_result_Sse( - RustStreamSink self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String( - self.setupAndSerialize( - codec: SseCodec( - decodeSuccessData: sse_decode_template_result, - decodeErrorData: null)), - serializer); - } - - @protected - void sse_encode_StreamSink_template_running_stage_Sse( - RustStreamSink self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String( - self.setupAndSerialize( - codec: SseCodec( - decodeSuccessData: sse_decode_template_running_stage, - decodeErrorData: null)), - serializer); - } - @protected void sse_encode_String(String self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2979,34 +1835,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_32(self.index, serializer); } - @protected - void sse_encode_attributes(Attributes self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_opt_box_autoadd_bool(self.bold, serializer); - sse_encode_opt_box_autoadd_bool(self.italic, serializer); - sse_encode_opt_String(self.file, serializer); - sse_encode_opt_String(self.sql, serializer); - } - - @protected - void sse_encode_bool(bool self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - serializer.buffer.putUint8(self ? 1 : 0); - } - - @protected - void sse_encode_box_autoadd_attributes( - Attributes self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_attributes(self, serializer); - } - - @protected - void sse_encode_box_autoadd_bool(bool self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_bool(self, serializer); - } - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3020,19 +1848,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_database_info(self, serializer); } - @protected - void sse_encode_box_autoadd_env_params( - EnvParams self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_env_params(self, serializer); - } - - @protected - void sse_encode_box_autoadd_i_64(int self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_64(self, serializer); - } - @protected void sse_encode_box_autoadd_memory_info( MemoryInfo self, SseSerializer serializer) { @@ -3040,45 +1855,18 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_memory_info(self, serializer); } - @protected - void sse_encode_box_autoadd_root(Root self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_root(self, serializer); - } - - @protected - void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_32(self, serializer); - } - @protected void sse_encode_cell_type(CellType self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_i_32(self.index, serializer); } - @protected - void sse_encode_children(Children self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.typeField, serializer); - sse_encode_data(self.data, serializer); - } - @protected void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_f_32(self.current, serializer); } - @protected - void sse_encode_data(Data self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_opt_box_autoadd_i_64(self.level, serializer); - sse_encode_list_delum(self.delta, serializer); - sse_encode_opt_String(self.align, serializer); - } - @protected void sse_encode_database_info(DatabaseInfo self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3090,29 +1878,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.database, serializer); } - @protected - void sse_encode_delum(Delum self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.insert, serializer); - sse_encode_opt_box_autoadd_attributes(self.attributes, serializer); - } - - @protected - void sse_encode_document(Document self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.typeField, serializer); - sse_encode_list_children(self.children, serializer); - } - - @protected - void sse_encode_env_params(EnvParams self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.base, serializer); - sse_encode_String(self.name, serializer); - sse_encode_String(self.chatBase, serializer); - sse_encode_opt_String(self.sk, serializer); - } - @protected void sse_encode_error_module(ErrorModule self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3156,33 +1921,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_String(List self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_String(item, serializer); - } - } - - @protected - void sse_encode_list_children(List self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_children(item, serializer); - } - } - - @protected - void sse_encode_list_delum(List self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_delum(item, serializer); - } - } - @protected void sse_encode_list_list_table_info( List> self, SseSerializer serializer) { @@ -3193,16 +1931,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_llm_message( - List self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_llm_message(item, serializer); - } - } - @protected void sse_encode_list_mounted_info( List self, SseSerializer serializer) { @@ -3279,19 +2007,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void - sse_encode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - List<(String, int, int?, AttributeType, String?)> self, - SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - item, serializer); - } - } - @protected void sse_encode_list_software(List self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3331,14 +2046,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_llm_message(LLMMessage self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.uuid, serializer); - sse_encode_String(self.content, serializer); - sse_encode_u_8(self.type, serializer); - } - @protected void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3387,27 +2094,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_opt_box_autoadd_attributes( - Attributes? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_attributes(self, serializer); - } - } - - @protected - void sse_encode_opt_box_autoadd_bool(bool? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_bool(self, serializer); - } - } - @protected void sse_encode_opt_box_autoadd_cpu_info( CpuInfo? self, SseSerializer serializer) { @@ -3419,27 +2105,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_opt_box_autoadd_env_params( - EnvParams? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_env_params(self, serializer); - } - } - - @protected - void sse_encode_opt_box_autoadd_i_64(int? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_i_64(self, serializer); - } - } - @protected void sse_encode_opt_box_autoadd_memory_info( MemoryInfo? self, SseSerializer serializer) { @@ -3451,37 +2116,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_opt_box_autoadd_root(Root? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_root(self, serializer); - } - } - - @protected - void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_u_32(self, serializer); - } - } - - @protected - void sse_encode_opt_list_llm_message( - List? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_list_llm_message(self, serializer); - } - } - @protected void sse_encode_opt_list_mounted_info( List? self, SseSerializer serializer) { @@ -3577,25 +2211,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.$2, serializer); } - @protected - void - sse_encode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - (String, int, int?, AttributeType, String?) self, - SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.$1, serializer); - sse_encode_u_32(self.$2, serializer); - sse_encode_opt_box_autoadd_u_32(self.$3, serializer); - sse_encode_attribute_type(self.$4, serializer); - sse_encode_opt_String(self.$5, serializer); - } - - @protected - void sse_encode_root(Root self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_document(self.document, serializer); - } - @protected void sse_encode_rust_error(RustError self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3636,22 +2251,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.dataType, serializer); } - @protected - void sse_encode_template_result( - TemplateResult self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.prompt, serializer); - sse_encode_u_32(self.index, serializer); - sse_encode_String(self.response, serializer); - } - - @protected - void sse_encode_template_running_stage( - TemplateRunningStage self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.index, serializer); - } - @protected void sse_encode_u_32(int self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3680,4 +2279,10 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { // Codec=Sse (Serialization based), see doc to use other codecs serializer.buffer.putUint64(self); } + + @protected + void sse_encode_bool(bool self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint8(self ? 1 : 0); + } } diff --git a/lib/src/rust/frb_generated.io.dart b/lib/src/rust/frb_generated.io.dart index cd3e12d..952a952 100644 --- a/lib/src/rust/frb_generated.io.dart +++ b/lib/src/rust/frb_generated.io.dart @@ -3,7 +3,6 @@ // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field -import 'api/llm_api.dart'; import 'api/llm_plugin_api.dart'; import 'api/process_port_mapper_api.dart'; import 'api/simple.dart'; @@ -15,11 +14,9 @@ import 'dart:convert'; import 'dart:ffi' as ffi; import 'errors.dart'; import 'frb_generated.dart'; -import 'llm.dart'; import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; -import 'llm/template.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart'; import 'software_monitor/software.dart'; import 'system_monitor.dart'; @@ -52,16 +49,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_String_Sse(dynamic raw); - @protected RustStreamSink dco_decode_StreamSink_list_prim_i_64_strict_Sse( dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_llm_message_Sse(dynamic raw); - @protected RustStreamSink dco_decode_StreamSink_monitor_info_Sse( dynamic raw); @@ -74,77 +65,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected RustStreamSink dco_decode_StreamSink_rust_error_Sse(dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_template_result_Sse( - dynamic raw); - - @protected - RustStreamSink - dco_decode_StreamSink_template_running_stage_Sse(dynamic raw); - @protected String dco_decode_String(dynamic raw); @protected AttributeType dco_decode_attribute_type(dynamic raw); - @protected - Attributes dco_decode_attributes(dynamic raw); - - @protected - bool dco_decode_bool(dynamic raw); - - @protected - Attributes dco_decode_box_autoadd_attributes(dynamic raw); - - @protected - bool dco_decode_box_autoadd_bool(dynamic raw); - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw); @protected DatabaseInfo dco_decode_box_autoadd_database_info(dynamic raw); - @protected - EnvParams dco_decode_box_autoadd_env_params(dynamic raw); - - @protected - int dco_decode_box_autoadd_i_64(dynamic raw); - @protected MemoryInfo dco_decode_box_autoadd_memory_info(dynamic raw); - @protected - Root dco_decode_box_autoadd_root(dynamic raw); - - @protected - int dco_decode_box_autoadd_u_32(dynamic raw); - @protected CellType dco_decode_cell_type(dynamic raw); - @protected - Children dco_decode_children(dynamic raw); - @protected CpuInfo dco_decode_cpu_info(dynamic raw); - @protected - Data dco_decode_data(dynamic raw); - @protected DatabaseInfo dco_decode_database_info(dynamic raw); - @protected - Delum dco_decode_delum(dynamic raw); - - @protected - Document dco_decode_document(dynamic raw); - - @protected - EnvParams dco_decode_env_params(dynamic raw); - @protected ErrorModule dco_decode_error_module(dynamic raw); @@ -165,21 +109,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( dynamic raw); - @protected - List dco_decode_list_String(dynamic raw); - - @protected - List dco_decode_list_children(dynamic raw); - - @protected - List dco_decode_list_delum(dynamic raw); - @protected List> dco_decode_list_list_table_info(dynamic raw); - @protected - List dco_decode_list_llm_message(dynamic raw); - @protected List dco_decode_list_mounted_info(dynamic raw); @@ -205,11 +137,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List<(String, String)> dco_decode_list_record_string_string(dynamic raw); - @protected - List<(String, int, int?, AttributeType, String?)> - dco_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw); - @protected List dco_decode_list_software(dynamic raw); @@ -222,9 +149,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_table_info(dynamic raw); - @protected - LLMMessage dco_decode_llm_message(dynamic raw); - @protected MemoryInfo dco_decode_memory_info(dynamic raw); @@ -240,33 +164,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? dco_decode_opt_String(dynamic raw); - @protected - Attributes? dco_decode_opt_box_autoadd_attributes(dynamic raw); - - @protected - bool? dco_decode_opt_box_autoadd_bool(dynamic raw); - @protected CpuInfo? dco_decode_opt_box_autoadd_cpu_info(dynamic raw); - @protected - EnvParams? dco_decode_opt_box_autoadd_env_params(dynamic raw); - - @protected - int? dco_decode_opt_box_autoadd_i_64(dynamic raw); - @protected MemoryInfo? dco_decode_opt_box_autoadd_memory_info(dynamic raw); - @protected - Root? dco_decode_opt_box_autoadd_root(dynamic raw); - - @protected - int? dco_decode_opt_box_autoadd_u_32(dynamic raw); - - @protected - List? dco_decode_opt_list_llm_message(dynamic raw); - @protected List? dco_decode_opt_list_mounted_info(dynamic raw); @@ -299,19 +202,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected (String, String) dco_decode_record_string_string(dynamic raw); - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) dco_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw); - - @protected - Root dco_decode_root(dynamic raw); - @protected RustError dco_decode_rust_error(dynamic raw); @@ -327,12 +217,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected TableInfo dco_decode_table_info(dynamic raw); - @protected - TemplateResult dco_decode_template_result(dynamic raw); - - @protected - TemplateRunningStage dco_decode_template_running_stage(dynamic raw); - @protected int dco_decode_u_32(dynamic raw); @@ -365,18 +249,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_String_Sse( - SseDeserializer deserializer); - @protected RustStreamSink sse_decode_StreamSink_list_prim_i_64_strict_Sse( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_llm_message_Sse( - SseDeserializer deserializer); - @protected RustStreamSink sse_decode_StreamSink_monitor_info_Sse( SseDeserializer deserializer); @@ -390,33 +266,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { RustStreamSink sse_decode_StreamSink_rust_error_Sse( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_template_result_Sse( - SseDeserializer deserializer); - - @protected - RustStreamSink - sse_decode_StreamSink_template_running_stage_Sse( - SseDeserializer deserializer); - @protected String sse_decode_String(SseDeserializer deserializer); @protected AttributeType sse_decode_attribute_type(SseDeserializer deserializer); - @protected - Attributes sse_decode_attributes(SseDeserializer deserializer); - - @protected - bool sse_decode_bool(SseDeserializer deserializer); - - @protected - Attributes sse_decode_box_autoadd_attributes(SseDeserializer deserializer); - - @protected - bool sse_decode_box_autoadd_bool(SseDeserializer deserializer); - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer); @@ -424,45 +279,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { DatabaseInfo sse_decode_box_autoadd_database_info( SseDeserializer deserializer); - @protected - EnvParams sse_decode_box_autoadd_env_params(SseDeserializer deserializer); - - @protected - int sse_decode_box_autoadd_i_64(SseDeserializer deserializer); - @protected MemoryInfo sse_decode_box_autoadd_memory_info(SseDeserializer deserializer); - @protected - Root sse_decode_box_autoadd_root(SseDeserializer deserializer); - - @protected - int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); - @protected CellType sse_decode_cell_type(SseDeserializer deserializer); - @protected - Children sse_decode_children(SseDeserializer deserializer); - @protected CpuInfo sse_decode_cpu_info(SseDeserializer deserializer); - @protected - Data sse_decode_data(SseDeserializer deserializer); - @protected DatabaseInfo sse_decode_database_info(SseDeserializer deserializer); - @protected - Delum sse_decode_delum(SseDeserializer deserializer); - - @protected - Document sse_decode_document(SseDeserializer deserializer); - - @protected - EnvParams sse_decode_env_params(SseDeserializer deserializer); - @protected ErrorModule sse_decode_error_module(SseDeserializer deserializer); @@ -483,22 +311,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( SseDeserializer deserializer); - @protected - List sse_decode_list_String(SseDeserializer deserializer); - - @protected - List sse_decode_list_children(SseDeserializer deserializer); - - @protected - List sse_decode_list_delum(SseDeserializer deserializer); - @protected List> sse_decode_list_list_table_info( SseDeserializer deserializer); - @protected - List sse_decode_list_llm_message(SseDeserializer deserializer); - @protected List sse_decode_list_mounted_info(SseDeserializer deserializer); @@ -529,11 +345,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List<(String, String)> sse_decode_list_record_string_string( SseDeserializer deserializer); - @protected - List<(String, int, int?, AttributeType, String?)> - sse_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer); - @protected List sse_decode_list_software(SseDeserializer deserializer); @@ -547,9 +358,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_table_info(SseDeserializer deserializer); - @protected - LLMMessage sse_decode_llm_message(SseDeserializer deserializer); - @protected MemoryInfo sse_decode_memory_info(SseDeserializer deserializer); @@ -566,37 +374,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? sse_decode_opt_String(SseDeserializer deserializer); - @protected - Attributes? sse_decode_opt_box_autoadd_attributes( - SseDeserializer deserializer); - - @protected - bool? sse_decode_opt_box_autoadd_bool(SseDeserializer deserializer); - @protected CpuInfo? sse_decode_opt_box_autoadd_cpu_info(SseDeserializer deserializer); - @protected - EnvParams? sse_decode_opt_box_autoadd_env_params( - SseDeserializer deserializer); - - @protected - int? sse_decode_opt_box_autoadd_i_64(SseDeserializer deserializer); - @protected MemoryInfo? sse_decode_opt_box_autoadd_memory_info( SseDeserializer deserializer); - @protected - Root? sse_decode_opt_box_autoadd_root(SseDeserializer deserializer); - - @protected - int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); - - @protected - List? sse_decode_opt_list_llm_message( - SseDeserializer deserializer); - @protected List? sse_decode_opt_list_mounted_info( SseDeserializer deserializer); @@ -636,19 +420,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (String, String) sse_decode_record_string_string( SseDeserializer deserializer); - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) sse_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer); - - @protected - Root sse_decode_root(SseDeserializer deserializer); - @protected RustError sse_decode_rust_error(SseDeserializer deserializer); @@ -664,13 +435,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected TableInfo sse_decode_table_info(SseDeserializer deserializer); - @protected - TemplateResult sse_decode_template_result(SseDeserializer deserializer); - - @protected - TemplateRunningStage sse_decode_template_running_stage( - SseDeserializer deserializer); - @protected int sse_decode_u_32(SseDeserializer deserializer); @@ -686,6 +450,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int sse_decode_usize(SseDeserializer deserializer); + @protected + bool sse_decode_bool(SseDeserializer deserializer); + @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer); @@ -704,18 +471,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( RustSimpleNotifyLibPinWindowItem self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_String_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_StreamSink_list_prim_i_64_strict_Sse( RustStreamSink self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_llm_message_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_StreamSink_monitor_info_Sse( RustStreamSink self, SseSerializer serializer); @@ -728,33 +487,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_StreamSink_rust_error_Sse( RustStreamSink self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_template_result_Sse( - RustStreamSink self, SseSerializer serializer); - - @protected - void sse_encode_StreamSink_template_running_stage_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_String(String self, SseSerializer serializer); @protected void sse_encode_attribute_type(AttributeType self, SseSerializer serializer); - @protected - void sse_encode_attributes(Attributes self, SseSerializer serializer); - - @protected - void sse_encode_bool(bool self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_attributes( - Attributes self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_bool(bool self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer); @@ -762,47 +500,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_box_autoadd_database_info( DatabaseInfo self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_env_params( - EnvParams self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_i_64(int self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_memory_info( MemoryInfo self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_root(Root self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); - @protected void sse_encode_cell_type(CellType self, SseSerializer serializer); - @protected - void sse_encode_children(Children self, SseSerializer serializer); - @protected void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer); - @protected - void sse_encode_data(Data self, SseSerializer serializer); - @protected void sse_encode_database_info(DatabaseInfo self, SseSerializer serializer); - @protected - void sse_encode_delum(Delum self, SseSerializer serializer); - - @protected - void sse_encode_document(Document self, SseSerializer serializer); - - @protected - void sse_encode_env_params(EnvParams self, SseSerializer serializer); - @protected void sse_encode_error_module(ErrorModule self, SseSerializer serializer); @@ -824,23 +534,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List self, SseSerializer serializer); - @protected - void sse_encode_list_String(List self, SseSerializer serializer); - - @protected - void sse_encode_list_children(List self, SseSerializer serializer); - - @protected - void sse_encode_list_delum(List self, SseSerializer serializer); - @protected void sse_encode_list_list_table_info( List> self, SseSerializer serializer); - @protected - void sse_encode_list_llm_message( - List self, SseSerializer serializer); - @protected void sse_encode_list_mounted_info( List self, SseSerializer serializer); @@ -873,12 +570,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_record_string_string( List<(String, String)> self, SseSerializer serializer); - @protected - void - sse_encode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - List<(String, int, int?, AttributeType, String?)> self, - SseSerializer serializer); - @protected void sse_encode_list_software(List self, SseSerializer serializer); @@ -894,9 +585,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_table_info( List self, SseSerializer serializer); - @protected - void sse_encode_llm_message(LLMMessage self, SseSerializer serializer); - @protected void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer); @@ -913,38 +601,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_String(String? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_attributes( - Attributes? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_bool(bool? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_cpu_info( CpuInfo? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_env_params( - EnvParams? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_i_64(int? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_memory_info( MemoryInfo? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_root(Root? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); - - @protected - void sse_encode_opt_list_llm_message( - List? self, SseSerializer serializer); - @protected void sse_encode_opt_list_mounted_info( List? self, SseSerializer serializer); @@ -985,15 +649,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_record_string_string( (String, String) self, SseSerializer serializer); - @protected - void - sse_encode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - (String, int, int?, AttributeType, String?) self, - SseSerializer serializer); - - @protected - void sse_encode_root(Root self, SseSerializer serializer); - @protected void sse_encode_rust_error(RustError self, SseSerializer serializer); @@ -1010,14 +665,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_table_info(TableInfo self, SseSerializer serializer); - @protected - void sse_encode_template_result( - TemplateResult self, SseSerializer serializer); - - @protected - void sse_encode_template_running_stage( - TemplateRunningStage self, SseSerializer serializer); - @protected void sse_encode_u_32(int self, SseSerializer serializer); @@ -1032,6 +679,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_usize(int self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); } // Section: wire_class diff --git a/lib/src/rust/frb_generated.web.dart b/lib/src/rust/frb_generated.web.dart index c9cd4b1..807af59 100644 --- a/lib/src/rust/frb_generated.web.dart +++ b/lib/src/rust/frb_generated.web.dart @@ -3,7 +3,6 @@ // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field -import 'api/llm_api.dart'; import 'api/llm_plugin_api.dart'; import 'api/process_port_mapper_api.dart'; import 'api/simple.dart'; @@ -14,11 +13,9 @@ import 'dart:async'; import 'dart:convert'; import 'errors.dart'; import 'frb_generated.dart'; -import 'llm.dart'; import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; -import 'llm/template.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart'; import 'software_monitor/software.dart'; import 'system_monitor.dart'; @@ -51,16 +48,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_String_Sse(dynamic raw); - @protected RustStreamSink dco_decode_StreamSink_list_prim_i_64_strict_Sse( dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_llm_message_Sse(dynamic raw); - @protected RustStreamSink dco_decode_StreamSink_monitor_info_Sse( dynamic raw); @@ -73,77 +64,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected RustStreamSink dco_decode_StreamSink_rust_error_Sse(dynamic raw); - @protected - RustStreamSink dco_decode_StreamSink_template_result_Sse( - dynamic raw); - - @protected - RustStreamSink - dco_decode_StreamSink_template_running_stage_Sse(dynamic raw); - @protected String dco_decode_String(dynamic raw); @protected AttributeType dco_decode_attribute_type(dynamic raw); - @protected - Attributes dco_decode_attributes(dynamic raw); - - @protected - bool dco_decode_bool(dynamic raw); - - @protected - Attributes dco_decode_box_autoadd_attributes(dynamic raw); - - @protected - bool dco_decode_box_autoadd_bool(dynamic raw); - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw); @protected DatabaseInfo dco_decode_box_autoadd_database_info(dynamic raw); - @protected - EnvParams dco_decode_box_autoadd_env_params(dynamic raw); - - @protected - int dco_decode_box_autoadd_i_64(dynamic raw); - @protected MemoryInfo dco_decode_box_autoadd_memory_info(dynamic raw); - @protected - Root dco_decode_box_autoadd_root(dynamic raw); - - @protected - int dco_decode_box_autoadd_u_32(dynamic raw); - @protected CellType dco_decode_cell_type(dynamic raw); - @protected - Children dco_decode_children(dynamic raw); - @protected CpuInfo dco_decode_cpu_info(dynamic raw); - @protected - Data dco_decode_data(dynamic raw); - @protected DatabaseInfo dco_decode_database_info(dynamic raw); - @protected - Delum dco_decode_delum(dynamic raw); - - @protected - Document dco_decode_document(dynamic raw); - - @protected - EnvParams dco_decode_env_params(dynamic raw); - @protected ErrorModule dco_decode_error_module(dynamic raw); @@ -164,21 +108,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( dynamic raw); - @protected - List dco_decode_list_String(dynamic raw); - - @protected - List dco_decode_list_children(dynamic raw); - - @protected - List dco_decode_list_delum(dynamic raw); - @protected List> dco_decode_list_list_table_info(dynamic raw); - @protected - List dco_decode_list_llm_message(dynamic raw); - @protected List dco_decode_list_mounted_info(dynamic raw); @@ -204,11 +136,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List<(String, String)> dco_decode_list_record_string_string(dynamic raw); - @protected - List<(String, int, int?, AttributeType, String?)> - dco_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw); - @protected List dco_decode_list_software(dynamic raw); @@ -221,9 +148,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_table_info(dynamic raw); - @protected - LLMMessage dco_decode_llm_message(dynamic raw); - @protected MemoryInfo dco_decode_memory_info(dynamic raw); @@ -239,33 +163,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? dco_decode_opt_String(dynamic raw); - @protected - Attributes? dco_decode_opt_box_autoadd_attributes(dynamic raw); - - @protected - bool? dco_decode_opt_box_autoadd_bool(dynamic raw); - @protected CpuInfo? dco_decode_opt_box_autoadd_cpu_info(dynamic raw); - @protected - EnvParams? dco_decode_opt_box_autoadd_env_params(dynamic raw); - - @protected - int? dco_decode_opt_box_autoadd_i_64(dynamic raw); - @protected MemoryInfo? dco_decode_opt_box_autoadd_memory_info(dynamic raw); - @protected - Root? dco_decode_opt_box_autoadd_root(dynamic raw); - - @protected - int? dco_decode_opt_box_autoadd_u_32(dynamic raw); - - @protected - List? dco_decode_opt_list_llm_message(dynamic raw); - @protected List? dco_decode_opt_list_mounted_info(dynamic raw); @@ -298,19 +201,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected (String, String) dco_decode_record_string_string(dynamic raw); - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) dco_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - dynamic raw); - - @protected - Root dco_decode_root(dynamic raw); - @protected RustError dco_decode_rust_error(dynamic raw); @@ -326,12 +216,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected TableInfo dco_decode_table_info(dynamic raw); - @protected - TemplateResult dco_decode_template_result(dynamic raw); - - @protected - TemplateRunningStage dco_decode_template_running_stage(dynamic raw); - @protected int dco_decode_u_32(dynamic raw); @@ -364,18 +248,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_String_Sse( - SseDeserializer deserializer); - @protected RustStreamSink sse_decode_StreamSink_list_prim_i_64_strict_Sse( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_llm_message_Sse( - SseDeserializer deserializer); - @protected RustStreamSink sse_decode_StreamSink_monitor_info_Sse( SseDeserializer deserializer); @@ -389,33 +265,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { RustStreamSink sse_decode_StreamSink_rust_error_Sse( SseDeserializer deserializer); - @protected - RustStreamSink sse_decode_StreamSink_template_result_Sse( - SseDeserializer deserializer); - - @protected - RustStreamSink - sse_decode_StreamSink_template_running_stage_Sse( - SseDeserializer deserializer); - @protected String sse_decode_String(SseDeserializer deserializer); @protected AttributeType sse_decode_attribute_type(SseDeserializer deserializer); - @protected - Attributes sse_decode_attributes(SseDeserializer deserializer); - - @protected - bool sse_decode_bool(SseDeserializer deserializer); - - @protected - Attributes sse_decode_box_autoadd_attributes(SseDeserializer deserializer); - - @protected - bool sse_decode_box_autoadd_bool(SseDeserializer deserializer); - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer); @@ -423,45 +278,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { DatabaseInfo sse_decode_box_autoadd_database_info( SseDeserializer deserializer); - @protected - EnvParams sse_decode_box_autoadd_env_params(SseDeserializer deserializer); - - @protected - int sse_decode_box_autoadd_i_64(SseDeserializer deserializer); - @protected MemoryInfo sse_decode_box_autoadd_memory_info(SseDeserializer deserializer); - @protected - Root sse_decode_box_autoadd_root(SseDeserializer deserializer); - - @protected - int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); - @protected CellType sse_decode_cell_type(SseDeserializer deserializer); - @protected - Children sse_decode_children(SseDeserializer deserializer); - @protected CpuInfo sse_decode_cpu_info(SseDeserializer deserializer); - @protected - Data sse_decode_data(SseDeserializer deserializer); - @protected DatabaseInfo sse_decode_database_info(SseDeserializer deserializer); - @protected - Delum sse_decode_delum(SseDeserializer deserializer); - - @protected - Document sse_decode_document(SseDeserializer deserializer); - - @protected - EnvParams sse_decode_env_params(SseDeserializer deserializer); - @protected ErrorModule sse_decode_error_module(SseDeserializer deserializer); @@ -482,22 +310,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( SseDeserializer deserializer); - @protected - List sse_decode_list_String(SseDeserializer deserializer); - - @protected - List sse_decode_list_children(SseDeserializer deserializer); - - @protected - List sse_decode_list_delum(SseDeserializer deserializer); - @protected List> sse_decode_list_list_table_info( SseDeserializer deserializer); - @protected - List sse_decode_list_llm_message(SseDeserializer deserializer); - @protected List sse_decode_list_mounted_info(SseDeserializer deserializer); @@ -528,11 +344,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List<(String, String)> sse_decode_list_record_string_string( SseDeserializer deserializer); - @protected - List<(String, int, int?, AttributeType, String?)> - sse_decode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer); - @protected List sse_decode_list_software(SseDeserializer deserializer); @@ -546,9 +357,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_table_info(SseDeserializer deserializer); - @protected - LLMMessage sse_decode_llm_message(SseDeserializer deserializer); - @protected MemoryInfo sse_decode_memory_info(SseDeserializer deserializer); @@ -565,37 +373,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? sse_decode_opt_String(SseDeserializer deserializer); - @protected - Attributes? sse_decode_opt_box_autoadd_attributes( - SseDeserializer deserializer); - - @protected - bool? sse_decode_opt_box_autoadd_bool(SseDeserializer deserializer); - @protected CpuInfo? sse_decode_opt_box_autoadd_cpu_info(SseDeserializer deserializer); - @protected - EnvParams? sse_decode_opt_box_autoadd_env_params( - SseDeserializer deserializer); - - @protected - int? sse_decode_opt_box_autoadd_i_64(SseDeserializer deserializer); - @protected MemoryInfo? sse_decode_opt_box_autoadd_memory_info( SseDeserializer deserializer); - @protected - Root? sse_decode_opt_box_autoadd_root(SseDeserializer deserializer); - - @protected - int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); - - @protected - List? sse_decode_opt_list_llm_message( - SseDeserializer deserializer); - @protected List? sse_decode_opt_list_mounted_info( SseDeserializer deserializer); @@ -635,19 +419,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (String, String) sse_decode_record_string_string( SseDeserializer deserializer); - @protected - ( - String, - int, - int?, - AttributeType, - String? - ) sse_decode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - SseDeserializer deserializer); - - @protected - Root sse_decode_root(SseDeserializer deserializer); - @protected RustError sse_decode_rust_error(SseDeserializer deserializer); @@ -663,13 +434,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected TableInfo sse_decode_table_info(SseDeserializer deserializer); - @protected - TemplateResult sse_decode_template_result(SseDeserializer deserializer); - - @protected - TemplateRunningStage sse_decode_template_running_stage( - SseDeserializer deserializer); - @protected int sse_decode_u_32(SseDeserializer deserializer); @@ -685,6 +449,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int sse_decode_usize(SseDeserializer deserializer); + @protected + bool sse_decode_bool(SseDeserializer deserializer); + @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer); @@ -703,18 +470,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( RustSimpleNotifyLibPinWindowItem self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_String_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_StreamSink_list_prim_i_64_strict_Sse( RustStreamSink self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_llm_message_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_StreamSink_monitor_info_Sse( RustStreamSink self, SseSerializer serializer); @@ -727,33 +486,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_StreamSink_rust_error_Sse( RustStreamSink self, SseSerializer serializer); - @protected - void sse_encode_StreamSink_template_result_Sse( - RustStreamSink self, SseSerializer serializer); - - @protected - void sse_encode_StreamSink_template_running_stage_Sse( - RustStreamSink self, SseSerializer serializer); - @protected void sse_encode_String(String self, SseSerializer serializer); @protected void sse_encode_attribute_type(AttributeType self, SseSerializer serializer); - @protected - void sse_encode_attributes(Attributes self, SseSerializer serializer); - - @protected - void sse_encode_bool(bool self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_attributes( - Attributes self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_bool(bool self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer); @@ -761,47 +499,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_box_autoadd_database_info( DatabaseInfo self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_env_params( - EnvParams self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_i_64(int self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_memory_info( MemoryInfo self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_root(Root self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); - @protected void sse_encode_cell_type(CellType self, SseSerializer serializer); - @protected - void sse_encode_children(Children self, SseSerializer serializer); - @protected void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer); - @protected - void sse_encode_data(Data self, SseSerializer serializer); - @protected void sse_encode_database_info(DatabaseInfo self, SseSerializer serializer); - @protected - void sse_encode_delum(Delum self, SseSerializer serializer); - - @protected - void sse_encode_document(Document self, SseSerializer serializer); - - @protected - void sse_encode_env_params(EnvParams self, SseSerializer serializer); - @protected void sse_encode_error_module(ErrorModule self, SseSerializer serializer); @@ -823,23 +533,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List self, SseSerializer serializer); - @protected - void sse_encode_list_String(List self, SseSerializer serializer); - - @protected - void sse_encode_list_children(List self, SseSerializer serializer); - - @protected - void sse_encode_list_delum(List self, SseSerializer serializer); - @protected void sse_encode_list_list_table_info( List> self, SseSerializer serializer); - @protected - void sse_encode_list_llm_message( - List self, SseSerializer serializer); - @protected void sse_encode_list_mounted_info( List self, SseSerializer serializer); @@ -872,12 +569,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_record_string_string( List<(String, String)> self, SseSerializer serializer); - @protected - void - sse_encode_list_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - List<(String, int, int?, AttributeType, String?)> self, - SseSerializer serializer); - @protected void sse_encode_list_software(List self, SseSerializer serializer); @@ -893,9 +584,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_table_info( List self, SseSerializer serializer); - @protected - void sse_encode_llm_message(LLMMessage self, SseSerializer serializer); - @protected void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer); @@ -912,38 +600,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_String(String? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_attributes( - Attributes? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_bool(bool? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_cpu_info( CpuInfo? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_env_params( - EnvParams? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_i_64(int? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_memory_info( MemoryInfo? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_root(Root? self, SseSerializer serializer); - - @protected - void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); - - @protected - void sse_encode_opt_list_llm_message( - List? self, SseSerializer serializer); - @protected void sse_encode_opt_list_mounted_info( List? self, SseSerializer serializer); @@ -984,15 +648,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_record_string_string( (String, String) self, SseSerializer serializer); - @protected - void - sse_encode_record_string_u_32_opt_box_autoadd_u_32_attribute_type_opt_string( - (String, int, int?, AttributeType, String?) self, - SseSerializer serializer); - - @protected - void sse_encode_root(Root self, SseSerializer serializer); - @protected void sse_encode_rust_error(RustError self, SseSerializer serializer); @@ -1009,14 +664,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_table_info(TableInfo self, SseSerializer serializer); - @protected - void sse_encode_template_result( - TemplateResult self, SseSerializer serializer); - - @protected - void sse_encode_template_running_stage( - TemplateRunningStage self, SseSerializer serializer); - @protected void sse_encode_u_32(int self, SseSerializer serializer); @@ -1031,6 +678,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_usize(int self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); } // Section: wire_class diff --git a/lib/src/rust/llm.dart b/lib/src/rust/llm.dart deleted file mode 100644 index 37f450c..0000000 --- a/lib/src/rust/llm.dart +++ /dev/null @@ -1,59 +0,0 @@ -// This file is automatically generated, so please do not edit it. -// Generated by `flutter_rust_bridge`@ 2.0.0-dev.35. - -// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import - -import 'frb_generated.dart'; -import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; - -class EnvParams { - final String base; - final String name; - final String chatBase; - final String? sk; - - const EnvParams({ - required this.base, - required this.name, - required this.chatBase, - this.sk, - }); - - @override - int get hashCode => - base.hashCode ^ name.hashCode ^ chatBase.hashCode ^ sk.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is EnvParams && - runtimeType == other.runtimeType && - base == other.base && - name == other.name && - chatBase == other.chatBase && - sk == other.sk; -} - -class LLMMessage { - final String uuid; - final String content; - final int type; - - const LLMMessage({ - required this.uuid, - required this.content, - required this.type, - }); - - @override - int get hashCode => uuid.hashCode ^ content.hashCode ^ type.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is LLMMessage && - runtimeType == other.runtimeType && - uuid == other.uuid && - content == other.content && - type == other.type; -} diff --git a/lib/src/rust/llm/app_flowy_model.dart b/lib/src/rust/llm/app_flowy_model.dart index e280875..fa807eb 100644 --- a/lib/src/rust/llm/app_flowy_model.dart +++ b/lib/src/rust/llm/app_flowy_model.dart @@ -12,136 +12,3 @@ enum AttributeType { sql, ; } - -class Attributes { - final bool? bold; - final bool? italic; - final String? file; - final String? sql; - - const Attributes({ - this.bold, - this.italic, - this.file, - this.sql, - }); - - @override - int get hashCode => - bold.hashCode ^ italic.hashCode ^ file.hashCode ^ sql.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Attributes && - runtimeType == other.runtimeType && - bold == other.bold && - italic == other.italic && - file == other.file && - sql == other.sql; -} - -class Children { - final String typeField; - final Data data; - - const Children({ - required this.typeField, - required this.data, - }); - - @override - int get hashCode => typeField.hashCode ^ data.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Children && - runtimeType == other.runtimeType && - typeField == other.typeField && - data == other.data; -} - -class Data { - final int? level; - final List delta; - final String? align; - - const Data({ - this.level, - required this.delta, - this.align, - }); - - @override - int get hashCode => level.hashCode ^ delta.hashCode ^ align.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Data && - runtimeType == other.runtimeType && - level == other.level && - delta == other.delta && - align == other.align; -} - -class Delum { - final String insert; - final Attributes? attributes; - - const Delum({ - required this.insert, - this.attributes, - }); - - @override - int get hashCode => insert.hashCode ^ attributes.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Delum && - runtimeType == other.runtimeType && - insert == other.insert && - attributes == other.attributes; -} - -class Document { - final String typeField; - final List children; - - const Document({ - required this.typeField, - required this.children, - }); - - @override - int get hashCode => typeField.hashCode ^ children.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Document && - runtimeType == other.runtimeType && - typeField == other.typeField && - children == other.children; -} - -class Root { - final Document document; - - const Root({ - required this.document, - }); - - @override - int get hashCode => document.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is Root && - runtimeType == other.runtimeType && - document == other.document; -} diff --git a/lib/src/rust/llm/template.dart b/lib/src/rust/llm/template.dart deleted file mode 100644 index 8c9e349..0000000 --- a/lib/src/rust/llm/template.dart +++ /dev/null @@ -1,39 +0,0 @@ -// This file is automatically generated, so please do not edit it. -// Generated by `flutter_rust_bridge`@ 2.0.0-dev.35. - -// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import - -import '../frb_generated.dart'; -import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; - -class TemplateResult { - final String prompt; - final int index; - final String response; - - const TemplateResult({ - required this.prompt, - required this.index, - required this.response, - }); - - @override - int get hashCode => prompt.hashCode ^ index.hashCode ^ response.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is TemplateResult && - runtimeType == other.runtimeType && - prompt == other.prompt && - index == other.index && - response == other.response; -} - -enum TemplateRunningStage { - format, - eval, - optimize, - done, - ; -} diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 5efd292..0f68610 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -264,16 +264,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" -[[package]] -name = "assert-json-diff" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" -dependencies = [ - "serde", - "serde_json", -] - [[package]] name = "async-broadcast" version = "0.5.1" @@ -297,15 +287,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-convert" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d416feee97712e43152cd42874de162b8f9b77295b1c85e5d92725cc8310bae" -dependencies = [ - "async-trait", -] - [[package]] name = "async-executor" version = "1.11.0" @@ -390,56 +371,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-openai" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11e97f9c5e0ee3260caee9700ba1bb61a6fdc34d2b6786a31e018c5de5198491" -dependencies = [ - "async-convert", - "backoff", - "base64 0.22.0", - "bytes", - "derive_builder 0.20.0", - "futures", - "rand", - "reqwest 0.12.4", - "reqwest-eventsource", - "secrecy", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "tokio-util", - "tracing", -] - -[[package]] -name = "async-openai" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "007f03f7e27271451af57ced242d6adfa04204d1275a91ec0952bf441fd8d102" -dependencies = [ - "async-convert", - "backoff", - "base64 0.22.0", - "bytes", - "derive_builder 0.20.0", - "futures", - "rand", - "reqwest 0.12.4", - "reqwest-eventsource", - "secrecy", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "tokio-util", - "tracing", -] - [[package]] name = "async-process" version = "1.8.1" @@ -486,28 +417,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "async-stream" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.60", -] - [[package]] name = "async-task" version = "4.7.0" @@ -635,20 +544,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" -[[package]] -name = "backoff" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1" -dependencies = [ - "futures-core", - "getrandom", - "instant", - "pin-project-lite", - "rand", - "tokio", -] - [[package]] name = "backtrace" version = "0.3.69" @@ -664,12 +559,6 @@ dependencies = [ "rustc-demangle", ] -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - [[package]] name = "base64" version = "0.21.7" @@ -697,7 +586,7 @@ dependencies = [ "bitflags 2.5.0", "cexpr", "clang-sys", - "itertools 0.12.1", + "itertools", "lazy_static", "lazycell", "log", @@ -711,21 +600,6 @@ dependencies = [ "which", ] -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - [[package]] name = "bit_field" version = "0.10.2" @@ -807,17 +681,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "bstr" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" -dependencies = [ - "memchr", - "regex-automata", - "serde", -] - [[package]] name = "build-target" version = "0.4.0" @@ -929,15 +792,6 @@ dependencies = [ "wayland-client 0.31.2", ] -[[package]] -name = "castaway" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a17ed5635fc8536268e5d4de1e22e81ac34419e5f052d4d51f4e01dcc263fcc" -dependencies = [ - "rustversion", -] - [[package]] name = "cc" version = "1.0.83" @@ -1126,16 +980,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" -[[package]] -name = "colored" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" -dependencies = [ - "lazy_static", - "windows-sys 0.48.0", -] - [[package]] name = "combine" version = "4.6.7" @@ -1146,19 +990,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "compact_str" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f" -dependencies = [ - "castaway", - "cfg-if 1.0.0", - "itoa", - "ryu", - "static_assertions", -] - [[package]] name = "concurrent-queue" version = "2.4.0" @@ -1168,19 +999,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "console" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" -dependencies = [ - "encode_unicode", - "lazy_static", - "libc", - "unicode-width", - "windows-sys 0.52.0", -] - [[package]] name = "console_error_panic_hook" version = "0.1.7" @@ -1541,50 +1359,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "cssparser" -version = "0.31.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3df4f93e5fbbe73ec01ec8d3f68bba73107993a5b1e7519273c32db9b0d5be" -dependencies = [ - "cssparser-macros", - "dtoa-short", - "itoa", - "phf 0.11.2", - "smallvec", -] - -[[package]] -name = "cssparser-macros" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" -dependencies = [ - "quote", - "syn 2.0.60", -] - -[[package]] -name = "csv" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac574ff4d437a7b5ad237ef331c17ccca63c46479e5b5453eb8e10bb99a759fe" -dependencies = [ - "csv-core", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "csv-core" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efa2b3d7902f4b634a20cae3c9c4e6209dc4779feb6863329607560143efa70" -dependencies = [ - "memchr", -] - [[package]] name = "ctor" version = "0.2.7" @@ -1613,28 +1387,8 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858" dependencies = [ - "darling_core 0.10.2", - "darling_macro 0.10.2", -] - -[[package]] -name = "darling" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" -dependencies = [ - "darling_core 0.14.4", - "darling_macro 0.14.4", -] - -[[package]] -name = "darling" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" -dependencies = [ - "darling_core 0.20.8", - "darling_macro 0.20.8", + "darling_core", + "darling_macro", ] [[package]] @@ -1647,71 +1401,21 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim 0.9.3", + "strsim", "syn 1.0.109", ] -[[package]] -name = "darling_core" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 1.0.109", -] - -[[package]] -name = "darling_core" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 2.0.60", -] - [[package]] name = "darling_macro" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" dependencies = [ - "darling_core 0.10.2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "darling_macro" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" -dependencies = [ - "darling_core 0.14.4", + "darling_core", "quote", "syn 1.0.109", ] -[[package]] -name = "darling_macro" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" -dependencies = [ - "darling_core 0.20.8", - "quote", - "syn 2.0.60", -] - [[package]] name = "dart-sys-fork" version = "4.1.1" @@ -1769,15 +1473,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "deranged" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" -dependencies = [ - "powerfmt", -] - [[package]] name = "derivative" version = "2.2.0" @@ -1790,127 +1485,44 @@ dependencies = [ ] [[package]] -name = "derive_builder" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d67778784b508018359cbc8696edb3db78160bab2c2a28ba7f56ef6932997f8" -dependencies = [ - "derive_builder_macro 0.12.0", -] - -[[package]] -name = "derive_builder" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0350b5cb0331628a5916d6c5c0b72e97393b8b6b03b47a9284f4e7f5a405ffd7" -dependencies = [ - "derive_builder_macro 0.20.0", -] - -[[package]] -name = "derive_builder_core" -version = "0.12.0" +name = "derive_more" +version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c11bdc11a0c47bc7d37d582b5285da6849c96681023680b906673c5707af7b0f" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ - "darling 0.14.4", + "convert_case", "proc-macro2", "quote", + "rustc_version", "syn 1.0.109", ] [[package]] -name = "derive_builder_core" -version = "0.20.0" +name = "derive_utils" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d48cda787f839151732d396ac69e3473923d54312c070ee21e9effcaa8ca0b1d" +checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ - "darling 0.20.8", "proc-macro2", "quote", "syn 2.0.60", ] [[package]] -name = "derive_builder_macro" -version = "0.12.0" +name = "digest" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebcda35c7a396850a55ffeac740804b40ffec779b98fffbb1738f4033f0ee79e" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "derive_builder_core 0.12.0", - "syn 1.0.109", + "block-buffer", + "const-oid", + "crypto-common", + "subtle", ] [[package]] -name = "derive_builder_macro" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206868b8242f27cecce124c19fd88157fbd0dd334df2587f36417bafbc85097b" -dependencies = [ - "derive_builder_core 0.20.0", - "syn 2.0.60", -] - -[[package]] -name = "derive_more" -version = "0.99.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" -dependencies = [ - "convert_case", - "proc-macro2", - "quote", - "rustc_version", - "syn 1.0.109", -] - -[[package]] -name = "derive_utils" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.60", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - -[[package]] -name = "dispatch" -version = "0.2.0" +name = "dispatch" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" @@ -2011,21 +1623,6 @@ dependencies = [ "libc", ] -[[package]] -name = "dtoa" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcbb2bf8e87535c23f7a8a321e364ce21462d0ff10cb6407820e8e96dfff6653" - -[[package]] -name = "dtoa-short" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbaceec3c6e4211c79e7b1800fb9680527106beb2f9c51904a3210c03a448c74" -dependencies = [ - "dtoa", -] - [[package]] name = "dwrote" version = "0.11.0" @@ -2040,12 +1637,6 @@ dependencies = [ "wio", ] -[[package]] -name = "ego-tree" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a68a4904193147e0a8dec3314640e6db742afd5f6e634f428a6af230d9b3591" - [[package]] name = "either" version = "1.11.0" @@ -2055,12 +1646,6 @@ dependencies = [ "serde", ] -[[package]] -name = "encode_unicode" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" - [[package]] name = "encoding_rs" version = "0.8.34" @@ -2117,12 +1702,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "esaxx-rs" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" - [[package]] name = "etcetera" version = "0.8.0" @@ -2202,17 +1781,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "eventsource-stream" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" -dependencies = [ - "futures-core", - "nom", - "pin-project-lite", -] - [[package]] name = "exr" version = "1.72.0" @@ -2229,32 +1797,6 @@ dependencies = [ "zune-inflate", ] -[[package]] -name = "fancy-regex" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7493d4c459da9f84325ad297371a6b2b8a162800873a22e3b6b6512e61d18c05" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastembed" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3037262d3bb0f50b32737a863b6117035772345f2f337b580d69fa9f57500cb" -dependencies = [ - "anyhow", - "hf-hub", - "ndarray", - "ort", - "rayon", - "serde_json", - "tokenizers", - "variant_count", -] - [[package]] name = "fastrand" version = "1.9.0" @@ -2484,16 +2026,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "futf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" -dependencies = [ - "mac", - "new_debug_unreachable", -] - [[package]] name = "futures" version = "0.3.30" @@ -2604,12 +2136,6 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" -[[package]] -name = "futures-timer" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" - [[package]] name = "futures-util" version = "0.3.30" @@ -2628,15 +2154,6 @@ dependencies = [ "slab", ] -[[package]] -name = "fxhash" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" -dependencies = [ - "byteorder", -] - [[package]] name = "gbm" version = "0.12.0" @@ -2774,15 +2291,6 @@ dependencies = [ "windows-targets 0.48.5", ] -[[package]] -name = "getopts" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" -dependencies = [ - "unicode-width", -] - [[package]] name = "getrandom" version = "0.2.14" @@ -3125,25 +2633,6 @@ dependencies = [ "syn 2.0.60", ] -[[package]] -name = "h2" -version = "0.3.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "h2" version = "0.4.4" @@ -3155,7 +2644,7 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http 1.1.0", + "http", "indexmap", "slab", "tokio", @@ -3219,23 +2708,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "hf-hub" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b780635574b3d92f036890d8373433d6f9fc7abb320ee42a5c25897fc8ed732" -dependencies = [ - "dirs", - "indicatif", - "log", - "native-tls", - "rand", - "serde", - "serde_json", - "thiserror", - "ureq", -] - [[package]] name = "hkdf" version = "0.12.4" @@ -3263,40 +2735,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "html-escape" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476" -dependencies = [ - "utf8-width", -] - -[[package]] -name = "html5ever" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7" -dependencies = [ - "log", - "mac", - "markup5ever", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.1.0" @@ -3308,17 +2746,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.0.0" @@ -3326,7 +2753,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" dependencies = [ "bytes", - "http 1.1.0", + "http", ] [[package]] @@ -3337,8 +2764,8 @@ checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" dependencies = [ "bytes", "futures-core", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "pin-project-lite", ] @@ -3348,36 +2775,6 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hyper" -version = "0.14.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.26", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.6", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.3.1" @@ -3387,9 +2784,9 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.4", - "http 1.1.0", - "http-body 1.0.0", + "h2", + "http", + "http-body", "httparse", "itoa", "pin-project-lite", @@ -3398,36 +2795,6 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-rustls" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" -dependencies = [ - "futures-util", - "http 1.1.0", - "hyper 1.3.1", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-tls" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" -dependencies = [ - "bytes", - "hyper 0.14.28", - "native-tls", - "tokio", - "tokio-native-tls", -] - [[package]] name = "hyper-tls" version = "0.6.0" @@ -3436,7 +2803,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper 1.3.1", + "hyper", "hyper-util", "native-tls", "tokio", @@ -3453,9 +2820,9 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.1.0", - "http-body 1.0.0", - "hyper 1.3.1", + "http", + "http-body", + "hyper", "pin-project-lite", "socket2 0.5.6", "tokio", @@ -3580,7 +2947,7 @@ dependencies = [ "fontdue", "i-slint-common", "image 0.24.9", - "itertools 0.12.1", + "itertools", "linked_hash_set", "lyon_extra", "lyon_path", @@ -3835,19 +3202,6 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "indicatif" -version = "0.17.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "763a5a8f45087d6bcea4222e7b72c291a054edf80e4ef6efd2a4979878c7bea3" -dependencies = [ - "console", - "instant", - "number_prefix", - "portable-atomic", - "unicode-width", -] - [[package]] name = "infer" version = "0.15.0" @@ -3912,15 +3266,6 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.12.1" @@ -4020,53 +3365,16 @@ dependencies = [ ] [[package]] -name = "langchain-rust" -version = "4.1.0" +name = "lazy-bytes-cast" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10257499f089cd156ad82d0a9cd57d9501fa2c989068992a97eb3c27836f206b" + +[[package]] +name = "lazy_static" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44372931fbc7d664f3338bcabd28916e20aba52c2918b0aec5a65168741ee42a" -dependencies = [ - "async-openai 0.20.0", - "async-recursion", - "async-stream", - "async-trait", - "csv", - "fastembed", - "futures", - "futures-util", - "glob", - "html-escape", - "log", - "lopdf", - "mockito", - "readability", - "regex", - "reqwest 0.12.4", - "reqwest-eventsource", - "scraper", - "secrecy", - "serde", - "serde_json", - "strum_macros", - "text-splitter", - "thiserror", - "tiktoken-rs", - "tokio", - "tokio-stream", - "url", - "urlencoding", -] - -[[package]] -name = "lazy-bytes-cast" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10257499f089cd156ad82d0a9cd57d9501fa2c989068992a97eb3c27836f206b" - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" dependencies = [ "spin 0.5.2", ] @@ -4136,16 +3444,6 @@ dependencies = [ "redox_syscall 0.4.1", ] -[[package]] -name = "libredox" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" -dependencies = [ - "bitflags 2.5.0", - "libc", -] - [[package]] name = "libsqlite3-sys" version = "0.27.0" @@ -4210,26 +3508,6 @@ version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" -[[package]] -name = "lopdf" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e775e4ee264e8a87d50a9efef7b67b4aa988cf94e75630859875fc347e6c872b" -dependencies = [ - "chrono", - "encoding_rs", - "flate2", - "itoa", - "linked-hash-map", - "log", - "md5", - "nom", - "pom", - "rayon", - "time", - "weezl", -] - [[package]] name = "lru" version = "0.12.3" @@ -4276,28 +3554,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "mac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" - -[[package]] -name = "macro_rules_attribute" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a82271f7bc033d84bbca59a3ce3e4159938cb08a9c3aebbe54d215131518a13" -dependencies = [ - "macro_rules_attribute-proc_macro", - "paste", -] - -[[package]] -name = "macro_rules_attribute-proc_macro" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8dd856d451cc0da70e2ef2ce95a18e39a93b7558bedf10201ad28503f918568" - [[package]] name = "malloc_buf" version = "0.0.6" @@ -4307,42 +3563,6 @@ dependencies = [ "libc", ] -[[package]] -name = "markup5ever" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" -dependencies = [ - "log", - "phf 0.10.1", - "phf_codegen", - "string_cache", - "string_cache_codegen", - "tendril", -] - -[[package]] -name = "markup5ever_rcdom" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9521dd6750f8e80ee6c53d65e2e4656d7de37064f3a7a5d2d11d05df93839c2" -dependencies = [ - "html5ever", - "markup5ever", - "tendril", - "xml5ever", -] - -[[package]] -name = "matrixmultiply" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7574c1cf36da4798ab73da5b215bbf444f50718207754cb522201d78d1cd0ff2" -dependencies = [ - "autocfg", - "rawpointer", -] - [[package]] name = "md-5" version = "0.10.6" @@ -4353,12 +3573,6 @@ dependencies = [ "digest", ] -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - [[package]] name = "memchr" version = "2.7.2" @@ -4521,46 +3735,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "mockito" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6e023aa5bdf392aa06c78e4a4e6d498baab5138d0c993503350ebbc37bf1e" -dependencies = [ - "assert-json-diff", - "colored", - "futures-core", - "hyper 0.14.28", - "log", - "rand", - "regex", - "serde_json", - "serde_urlencoded", - "similar", - "tokio", -] - -[[package]] -name = "monostate" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20fffcd8ca4c69d31e036a71abc400147b41f90895df4edcb36497a1f8af8bf" -dependencies = [ - "monostate-impl", - "serde", -] - -[[package]] -name = "monostate-impl" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf307cbbbd777a9c10cec88ddafee572b3484caad5cce0c9236523c3803105a6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.60", -] - [[package]] name = "native-tls" version = "0.2.11" @@ -4579,19 +3753,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "ndarray" -version = "0.15.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb12d4e967ec485a5f71c6311fe28158e9d6f4bc4a447b474184d0f91a8fa32" -dependencies = [ - "matrixmultiply", - "num-complex", - "num-integer", - "num-traits", - "rawpointer", -] - [[package]] name = "ndk" version = "0.3.0" @@ -4660,7 +3821,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05d1c6307dc424d0f65b9b06e94f88248e6305726b14729fd67a5e47b2dc481d" dependencies = [ - "darling 0.10.2", + "darling", "proc-macro-crate 0.1.5", "proc-macro2", "quote", @@ -4691,12 +3852,6 @@ dependencies = [ "jni-sys", ] -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" - [[package]] name = "nix" version = "0.18.0" @@ -4789,21 +3944,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "num-complex" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23c6602fda94a57c990fe0df199a035d83576b496aa29f4e634a8ac6004e68a6" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - [[package]] name = "num-integer" version = "0.1.46" @@ -4897,12 +4037,6 @@ dependencies = [ "syn 2.0.60", ] -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - [[package]] name = "objc" version = "0.2.7" @@ -4999,28 +4133,6 @@ dependencies = [ "portable-atomic", ] -[[package]] -name = "onig" -version = "6.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c4b31c8722ad9171c6d77d3557db078cab2bd50afcc9d09c8b315c59df8ca4f" -dependencies = [ - "bitflags 1.3.2", - "libc", - "once_cell", - "onig_sys", -] - -[[package]] -name = "onig_sys" -version = "69.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b829e3d7e9cc74c7e315ee8edb185bf4190da5acde74afd7fc59c35b1f086e7" -dependencies = [ - "cc", - "pkg-config", -] - [[package]] name = "openssl" version = "0.10.64" @@ -5065,19 +4177,13 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "orbclient" version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52f0d54bde9774d3a51dcf281a5def240c71996bc6ca05d2c847ec8b2b216166" dependencies = [ - "libredox 0.0.2", + "libredox", ] [[package]] @@ -5090,31 +4196,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "ort" -version = "2.0.0-rc.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8e5caf4eb2ead4bc137c3ff4e347940e3e556ceb11a4180627f04b63d7342dd" -dependencies = [ - "compact_str", - "ndarray", - "ort-sys", - "thiserror", - "tracing", -] - -[[package]] -name = "ort-sys" -version = "2.0.0-rc.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ccad267e2a67a8dbf2ceb9497d3a7e8d8f71dc58e65126dd15bf44f6d4612a2" -dependencies = [ - "flate2", - "sha2", - "tar", - "ureq", -] - [[package]] name = "oslog" version = "0.1.0" @@ -5244,86 +4325,6 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" -[[package]] -name = "phf" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" -dependencies = [ - "phf_shared 0.10.0", -] - -[[package]] -name = "phf" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" -dependencies = [ - "phf_macros", - "phf_shared 0.11.2", -] - -[[package]] -name = "phf_codegen" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" -dependencies = [ - "phf_generator 0.10.0", - "phf_shared 0.10.0", -] - -[[package]] -name = "phf_generator" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" -dependencies = [ - "phf_shared 0.10.0", - "rand", -] - -[[package]] -name = "phf_generator" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" -dependencies = [ - "phf_shared 0.11.2", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" -dependencies = [ - "phf_generator 0.11.2", - "phf_shared 0.11.2", - "proc-macro2", - "quote", - "syn 2.0.60", -] - -[[package]] -name = "phf_shared" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" -dependencies = [ - "siphasher", -] - -[[package]] -name = "phf_shared" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" -dependencies = [ - "siphasher", -] - [[package]] name = "pico-args" version = "0.5.0" @@ -5461,15 +4462,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "pom" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c972d8f86e943ad532d0b04e8965a749ad1d18bb981a9c7b3ae72fe7fd7744b" -dependencies = [ - "bstr", -] - [[package]] name = "portable-atomic" version = "1.6.0" @@ -5479,24 +4471,12 @@ dependencies = [ "critical-section", ] -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - [[package]] name = "ppv-lite86" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" -[[package]] -name = "precomputed-hash" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" - [[package]] name = "prettyplease" version = "0.2.15" @@ -5577,17 +4557,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "pulldown-cmark" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76979bea66e7875e7509c4ec5300112b316af87fa7a252ca91c448b32dfe3993" -dependencies = [ - "bitflags 2.5.0", - "memchr", - "unicase", -] - [[package]] name = "qoi" version = "0.4.1" @@ -5687,12 +4656,6 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42a9830a0e1b9fb145ebb365b8bc4ccd75f290f98c0247deafbbe2c75cefb544" -[[package]] -name = "rawpointer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" - [[package]] name = "rayon" version = "1.10.0" @@ -5703,17 +4666,6 @@ dependencies = [ "rayon-core", ] -[[package]] -name = "rayon-cond" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "059f538b55efd2309c9794130bc149c6a553db90e9d99c2030785c82f0bd7df9" -dependencies = [ - "either", - "itertools 0.11.0", - "rayon", -] - [[package]] name = "rayon-core" version = "1.12.1" @@ -5724,20 +4676,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "readability" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e56596e20a6d3cf715182d9b6829220621e6e985cec04d00410cee29821b4220" -dependencies = [ - "html5ever", - "lazy_static", - "markup5ever_rcdom", - "regex", - "reqwest 0.11.27", - "url", -] - [[package]] name = "redox_syscall" version = "0.2.16" @@ -5765,17 +4703,6 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "redox_users" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" -dependencies = [ - "getrandom", - "libredox 0.1.3", - "thiserror", -] - [[package]] name = "regex" version = "1.10.4" @@ -5785,7 +4712,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-automata", - "regex-syntax 0.8.2", + "regex-syntax", ] [[package]] @@ -5796,61 +4723,15 @@ checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.2", + "regex-syntax", ] -[[package]] -name = "regex-syntax" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" - [[package]] name = "regex-syntax" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" -[[package]] -name = "reqwest" -version = "0.11.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" -dependencies = [ - "base64 0.21.7", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2 0.3.26", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.28", - "hyper-tls 0.5.0", - "ipnet", - "js-sys", - "log", - "mime", - "native-tls", - "once_cell", - "percent-encoding", - "pin-project-lite", - "rustls-pemfile 1.0.4", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "system-configuration", - "tokio", - "tokio-native-tls", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "winreg 0.50.0", -] - [[package]] name = "reqwest" version = "0.12.4" @@ -5862,13 +4743,12 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2 0.4.4", - "http 1.1.0", - "http-body 1.0.0", + "h2", + "http", + "http-body", "http-body-util", - "hyper 1.3.1", - "hyper-rustls", - "hyper-tls 0.6.0", + "hyper", + "hyper-tls", "hyper-util", "ipnet", "js-sys", @@ -5879,10 +4759,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls", - "rustls-native-certs", - "rustls-pemfile 2.1.2", - "rustls-pki-types", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", @@ -5890,31 +4767,12 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", - "tokio-rustls", - "tokio-util", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams", "web-sys", - "winreg 0.52.0", -] - -[[package]] -name = "reqwest-eventsource" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632c55746dbb44275691640e7b40c907c16a2dc1a5842aa98aaec90da6ec6bde" -dependencies = [ - "eventsource-stream", - "futures-core", - "futures-timer", - "mime", - "nom", - "pin-project-lite", - "reqwest 0.12.4", - "thiserror", + "winreg", ] [[package]] @@ -5932,27 +4790,12 @@ dependencies = [ ] [[package]] -name = "rgb" -version = "0.8.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05aaa8004b64fd573fc9d002f4e632d51ad4f026c2b5ba95fcb6c2f32c2c47d8" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "ring" -version = "0.17.8" +name = "rgb" +version = "0.8.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +checksum = "05aaa8004b64fd573fc9d002f4e632d51ad4f026c2b5ba95fcb6c2f32c2c47d8" dependencies = [ - "cc", - "cfg-if 1.0.0", - "getrandom", - "libc", - "spin 0.9.8", - "untrusted", - "windows-sys 0.52.0", + "bytemuck", ] [[package]] @@ -5999,16 +4842,13 @@ name = "rust_lib_all_in_one" version = "0.1.0" dependencies = [ "anyhow", - "async-openai 0.21.0", "async-trait", "cron-job", "flutter_rust_bridge", - "futures", "infer", - "langchain-rust", "once_cell", "regex", - "reqwest 0.12.4", + "reqwest", "rust_simple_notify_lib", "serde", "serde_json", @@ -6018,7 +4858,7 @@ dependencies = [ "tokio", "uuid", "winapi", - "winreg 0.52.0", + "winreg", ] [[package]] @@ -6082,42 +4922,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" -dependencies = [ - "openssl-probe", - "rustls-pemfile 2.1.2", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pemfile" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" -dependencies = [ - "base64 0.21.7", -] - [[package]] name = "rustls-pemfile" version = "2.1.2" @@ -6134,17 +4938,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54" -[[package]] -name = "rustls-webpki" -version = "0.102.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3bce581c0dd41bce533ce695a1437fa16a7ab5ac3ccfa99fe1a620a7885eabf" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rusttype" version = "0.9.3" @@ -6241,22 +5034,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "scraper" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b80b33679ff7a0ea53d37f3b39de77ea0c75b12c5805ac43ec0c33b3051af1b" -dependencies = [ - "ahash", - "cssparser", - "ego-tree", - "getopts", - "html5ever", - "once_cell", - "selectors", - "tendril", -] - [[package]] name = "sctk-adwaita" version = "0.8.1" @@ -6270,16 +5047,6 @@ dependencies = [ "tiny-skia", ] -[[package]] -name = "secrecy" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" -dependencies = [ - "serde", - "zeroize", -] - [[package]] name = "security-framework" version = "2.10.0" @@ -6303,25 +5070,6 @@ dependencies = [ "libc", ] -[[package]] -name = "selectors" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb30575f3638fc8f6815f448d50cb1a2e255b0897985c8c59f4d37b72a07b06" -dependencies = [ - "bitflags 2.5.0", - "cssparser", - "derive_more", - "fxhash", - "log", - "new_debug_unreachable", - "phf 0.10.1", - "phf_codegen", - "precomputed-hash", - "servo_arc", - "smallvec", -] - [[package]] name = "semver" version = "1.0.22" @@ -6391,15 +5139,6 @@ dependencies = [ "serde", ] -[[package]] -name = "servo_arc" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d036d71a959e00c77a63538b90a6c2390969f9772b096ea837205c6bd0491a44" -dependencies = [ - "stable_deref_trait", -] - [[package]] name = "sha1" version = "0.10.6" @@ -6453,12 +5192,6 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" -[[package]] -name = "similar" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" - [[package]] name = "simplecss" version = "0.2.1" @@ -6717,25 +5450,13 @@ dependencies = [ "der", ] -[[package]] -name = "spm_precompiled" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" -dependencies = [ - "base64 0.13.1", - "nom", - "serde", - "unicode-segmentation", -] - [[package]] name = "sqlformat" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce81b7bd7c4493975347ef60d8c7e8b742d4694f4c49f93e0a12ea263938176c" dependencies = [ - "itertools 0.12.1", + "itertools", "nom", "unicode_categories", ] @@ -6954,32 +5675,6 @@ dependencies = [ "float-cmp", ] -[[package]] -name = "string_cache" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b" -dependencies = [ - "new_debug_unreachable", - "once_cell", - "parking_lot 0.12.1", - "phf_shared 0.10.0", - "precomputed-hash", - "serde", -] - -[[package]] -name = "string_cache_codegen" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" -dependencies = [ - "phf_generator 0.10.0", - "phf_shared 0.10.0", - "proc-macro2", - "quote", -] - [[package]] name = "stringprep" version = "0.1.4" @@ -6997,12 +5692,6 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "strum" version = "0.26.2" @@ -7213,17 +5902,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "tendril" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" -dependencies = [ - "futf", - "mac", - "utf-8", -] - [[package]] name = "termcolor" version = "1.4.1" @@ -7239,23 +5917,6 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" -[[package]] -name = "text-splitter" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "691e4c33fe08c9637366b4f6ba6217157703f784f1c0a670aa76ac2f8a15733f" -dependencies = [ - "ahash", - "auto_enums", - "either", - "itertools 0.12.1", - "once_cell", - "pulldown-cmark", - "regex", - "tiktoken-rs", - "unicode-segmentation", -] - [[package]] name = "thiserror" version = "1.0.59" @@ -7307,52 +5968,6 @@ dependencies = [ "weezl", ] -[[package]] -name = "tiktoken-rs" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40894b788eb28bbb7e36bdc8b7b1b1488b9c93fa3730f315ab965330c94c0842" -dependencies = [ - "anyhow", - "base64 0.21.7", - "bstr", - "fancy-regex", - "lazy_static", - "parking_lot 0.12.1", - "rustc-hash", -] - -[[package]] -name = "time" -version = "0.3.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" - -[[package]] -name = "time-macros" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tiny-skia" version = "0.11.4" @@ -7406,37 +6021,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" -[[package]] -name = "tokenizers" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9be88c795d8b9f9c4002b3a8f26a6d0876103a6f523b32ea3bac52d8560c17c" -dependencies = [ - "aho-corasick", - "derive_builder 0.12.0", - "esaxx-rs", - "getrandom", - "itertools 0.11.0", - "lazy_static", - "log", - "macro_rules_attribute", - "monostate", - "onig", - "paste", - "rand", - "rayon", - "rayon-cond", - "regex", - "regex-syntax 0.7.5", - "serde", - "serde_json", - "spm_precompiled", - "thiserror", - "unicode-normalization-alignments", - "unicode-segmentation", - "unicode_categories", -] - [[package]] name = "tokio" version = "1.37.0" @@ -7477,17 +6061,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls", - "rustls-pki-types", - "tokio", -] - [[package]] name = "tokio-stream" version = "0.1.15" @@ -7755,15 +6328,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-normalization-alignments" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" -dependencies = [ - "smallvec", -] - [[package]] name = "unicode-properties" version = "0.1.1" @@ -7788,12 +6352,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" -[[package]] -name = "unicode-width" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" - [[package]] name = "unicode-xid" version = "0.2.4" @@ -7806,32 +6364,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "ureq" -version = "2.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d11a831e3c0b56e438a28308e7c810799e3c118417f342d30ecec080105395cd" -dependencies = [ - "base64 0.22.0", - "flate2", - "log", - "native-tls", - "once_cell", - "rustls", - "rustls-pki-types", - "rustls-webpki", - "serde", - "serde_json", - "url", - "webpki-roots", -] - [[package]] name = "url" version = "2.5.0" @@ -7876,18 +6408,6 @@ dependencies = [ "xmlwriter", ] -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8-width" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" - [[package]] name = "uuid" version = "1.8.0" @@ -7910,16 +6430,6 @@ dependencies = [ "syn 2.0.60", ] -[[package]] -name = "variant_count" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aae2faf80ac463422992abf4de234731279c058aaf33171ca70277c98406b124" -dependencies = [ - "quote", - "syn 1.0.109", -] - [[package]] name = "vcpkg" version = "0.2.15" @@ -8064,19 +6574,6 @@ version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" -[[package]] -name = "wasm-streams" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "wayland-backend" version = "0.3.3" @@ -8289,15 +6786,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki-roots" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3de34ae270483955a94f4b21bdaaeb83d508bb84a01435f393818edb0012009" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "weezl" version = "0.1.8" @@ -8751,16 +7239,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "winreg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" -dependencies = [ - "cfg-if 1.0.0", - "windows-sys 0.48.0", -] - [[package]] name = "winreg" version = "0.52.0" @@ -8927,17 +7405,6 @@ version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193" -[[package]] -name = "xml5ever" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4034e1d05af98b51ad7214527730626f019682d797ba38b51689212118d8e650" -dependencies = [ - "log", - "mac", - "markup5ever", -] - [[package]] name = "xmlwriter" version = "0.1.0" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index b71a5e4..1048faa 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -8,13 +8,13 @@ crate-type = ["cdylib", "staticlib"] [dependencies] anyhow = "1" -async-openai = "0.21.0" +# async-openai = "0.21.0" async-trait = "0.1.80" cron-job = "=0.1.4" flutter_rust_bridge = "=2.0.0-dev.35" -futures = "0.3.30" +# futures = "0.3.30" infer = "0.15.0" -langchain-rust = "4.1.0" +# langchain-rust = "4.1.0" once_cell = "1.19.0" regex = "1.10.4" reqwest = { version = "0.12", features = ["json","multipart"] } diff --git a/rust/src/api/llm_api.rs b/rust/src/api/llm_api.rs deleted file mode 100644 index 153b297..0000000 --- a/rust/src/api/llm_api.rs +++ /dev/null @@ -1,160 +0,0 @@ -use flutter_rust_bridge::frb; - -use crate::llm::ai_helper::AI_HELPER_MESSAGE_SINK; -use crate::{ - errors::{RustError, ERROR_MESSAGE_SINK}, - frb_generated::StreamSink, - llm::{ - app_flowy_model::{str_to_doc, template_renderer_impl, AttributeType, Root}, - template::{ - generate_template_items_from_list, AppFlowyTemplate, TemplateResult, - TemplateRunningStage, TEMPLATE_MESSAGE_SINK, TEMPLATE_STATE_SINK, - }, - EnvParams, LLMMessage, ENV_PARAMS, LLM_MESSAGE_SINK, - }, -}; - -#[frb(sync)] -pub fn init_llm(p: String) { - crate::llm::init(p) -} - -#[frb(sync)] -pub fn get_llm_config() -> Option { - let r = ENV_PARAMS.read().unwrap(); - (*r).clone() -} - -#[flutter_rust_bridge::frb(sync)] -pub fn llm_message_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = LLM_MESSAGE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) -} - -#[flutter_rust_bridge::frb(sync)] -pub fn ai_helper_message_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = AI_HELPER_MESSAGE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) -} - -#[flutter_rust_bridge::frb(sync)] -pub fn template_message_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = TEMPLATE_MESSAGE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) -} - -#[flutter_rust_bridge::frb(sync)] -pub fn error_message_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = ERROR_MESSAGE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) -} - -#[flutter_rust_bridge::frb(sync)] -pub fn template_state_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = TEMPLATE_STATE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) -} - -pub fn chat(_uuid: Option, _history: Option>, stream: bool, query: String) { - let rt = tokio::runtime::Runtime::new().unwrap(); - rt.block_on(async { crate::llm::chat(_uuid, _history, stream, query).await }); -} - -pub fn sequential_chain_chat(json_str: String, query: String) { - let rt = tokio::runtime::Runtime::new().unwrap(); - let _ = rt.block_on(async { crate::llm::sequential_chain_chat(json_str, query).await }); -} - -pub fn template_renderer(template: String) -> Option { - let rt = tokio::runtime::Runtime::new().unwrap(); - if let Ok(res) = rt.block_on(async { template_renderer_impl(template).await }) { - return Some(res); - } - - None -} - -pub fn template_to_prompts(template: String) -> Vec<(String, AttributeType, Option)> { - let r = crate::llm::app_flowy_model::get_all_cadidates(template); - if let Ok(_r) = r { - return _r; - } else { - println!("template_to_prompts error {:?}", r.err()); - } - return vec![]; -} - -pub fn generate_from_template( - v: Vec<(String, u32, Option, AttributeType, Option)>, - enable_plugin: bool, -) { - let rt = tokio::runtime::Runtime::new().unwrap(); - rt.block_on(async { - let list = generate_template_items_from_list(v); - let mut a = AppFlowyTemplate::from(list); - a.execute(enable_plugin).await; - }); -} - -pub fn optimize_doc(s: String) -> String { - let rt = tokio::runtime::Runtime::new().unwrap(); - rt.block_on(async { crate::llm::template::optimize_doc(s).await }) -} - -#[flutter_rust_bridge::frb(sync)] -pub fn get_doc_root_from_str(s: String) -> Option { - let r = str_to_doc(s); - if let Ok(_r) = r { - return Some(_r); - } - - None -} - -pub fn ai_helper_quick_request( - s: String, - tone: String, - lang: String, - length: String, - extra: Vec, -) { - let mut requirements: Vec = extra; - let mut prompt = s.clone(); - if lang != "中文" { - requirements.push(format!("请使用{}回答", lang)); - } - match length.as_str() { - "中等的" => { - requirements.push("结果在500~1000字".to_string()); - } - "短文" => { - requirements.push("结果在500字以内".to_string()); - } - "长文" => { - requirements.push("结果在1000~1500字".to_string()); - } - _ => {} - } - - if tone != "正常的" { - requirements.push(format!("请使用{}口吻回答", tone)); - } - - if !requirements.is_empty() { - prompt = format!("{}。要求如下: {}", s, requirements.join(";")); - println!("[rust] final prompt {:?}", prompt) - } - - let rt = tokio::runtime::Runtime::new().unwrap(); - rt.block_on(async { crate::llm::ai_helper::ai_quick_request(prompt).await }); -} - -#[flutter_rust_bridge::frb(sync)] -pub fn init_prompt_from_path(s: String) { - crate::llm::internal_prompts::read_prompts_file(s); -} diff --git a/rust/src/api/llm_plugin_api.rs b/rust/src/api/llm_plugin_api.rs index 8b725d6..4ae4187 100644 --- a/rust/src/api/llm_plugin_api.rs +++ b/rust/src/api/llm_plugin_api.rs @@ -1,9 +1,8 @@ -use std::collections::HashMap; -use crate::llm::plugins::mind_map::MIND_MAP_MESSAGE_SINK; -use crate::frb_generated::StreamSink; +use crate::llm::app_flowy_model::AttributeType; use crate::llm::plugins::chat_db::mysql::CellType; use crate::llm::plugins::chat_db::DatabaseInfo; use crate::llm::plugins::chat_db::TableInfo; +use std::collections::HashMap; pub fn get_mysql_table_info(s: DatabaseInfo) -> Vec> { let rt = tokio::runtime::Runtime::new().unwrap(); @@ -36,16 +35,12 @@ pub fn eval( } } -pub fn text_to_mind_map(s: String) { - let rt = tokio::runtime::Runtime::new().unwrap(); - rt.block_on(async { - crate::llm::plugins::mind_map::text_to_mind_map(s).await; - }); -} - -#[flutter_rust_bridge::frb(sync)] -pub fn mind_map_stream(s: StreamSink) -> anyhow::Result<()> { - let mut stream = MIND_MAP_MESSAGE_SINK.write().unwrap(); - *stream = Some(s); - anyhow::Ok(()) +pub fn template_to_prompts(template: String) -> Vec<(String, AttributeType, Option)> { + let r = crate::llm::app_flowy_model::get_all_cadidates(template); + if let Ok(_r) = r { + return _r; + } else { + println!("template_to_prompts error {:?}", r.err()); + } + return vec![]; } diff --git a/rust/src/api/mod.rs b/rust/src/api/mod.rs index 6b563e4..2bb6a99 100644 --- a/rust/src/api/mod.rs +++ b/rust/src/api/mod.rs @@ -2,7 +2,6 @@ // Do not put code in `mod.rs`, but put in e.g. `simple.rs`. // -pub mod llm_api; pub mod llm_plugin_api; pub mod process_port_mapper_api; pub mod simple; diff --git a/rust/src/api/simple.rs b/rust/src/api/simple.rs index 4360c82..ec5d274 100644 --- a/rust/src/api/simple.rs +++ b/rust/src/api/simple.rs @@ -1,3 +1,8 @@ +use crate::{ + errors::{RustError, ERROR_MESSAGE_SINK}, + frb_generated::StreamSink, +}; +use flutter_rust_bridge::frb; #[flutter_rust_bridge::frb(sync)] // Synchronous mode for simplicity of the demo pub fn greet(name: String) -> String { format!("Hello, {name}!") @@ -8,3 +13,10 @@ pub fn init_app() { // Default utilities - feel free to customize flutter_rust_bridge::setup_default_user_utils(); } + +#[frb(sync)] +pub fn rust_error_stream(s: StreamSink) -> anyhow::Result<()> { + let mut stream = ERROR_MESSAGE_SINK.write().unwrap(); + *stream = Some(s); + anyhow::Ok(()) +} diff --git a/rust/src/frb_generated.rs b/rust/src/frb_generated.rs index aac5ef5..089e205 100644 --- a/rust/src/frb_generated.rs +++ b/rust/src/frb_generated.rs @@ -33,7 +33,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.0.0-dev.35"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1113812267; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -576783616; // Section: executor @@ -41,527 +41,6 @@ flutter_rust_bridge::frb_generated_default_handler!(); // Section: wire_funcs -fn wire__crate__api__llm_api__ai_helper_message_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "ai_helper_message_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = - >::sse_decode( - &mut deserializer, - ); - deserializer.end(); - transform_result_sse((move || { - crate::api::llm_api::ai_helper_message_stream(api_s) - })()) - }, - ) -} -fn wire__crate__api__llm_api__ai_helper_quick_request_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "ai_helper_quick_request", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = ::sse_decode(&mut deserializer); - let api_tone = ::sse_decode(&mut deserializer); - let api_lang = ::sse_decode(&mut deserializer); - let api_length = ::sse_decode(&mut deserializer); - let api_extra = >::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::ai_helper_quick_request( - api_s, api_tone, api_lang, api_length, api_extra, - )) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__chat_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "chat", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api__uuid = >::sse_decode(&mut deserializer); - let api__history = >>::sse_decode(&mut deserializer); - let api_stream = ::sse_decode(&mut deserializer); - let api_query = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::chat( - api__uuid, - api__history, - api_stream, - api_query, - )) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__error_message_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "error_message_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = >::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || crate::api::llm_api::error_message_stream(api_s))()) - }, - ) -} -fn wire__crate__api__llm_api__generate_from_template_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "generate_from_template", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_v = , - crate::llm::app_flowy_model::AttributeType, - Option, - )>>::sse_decode(&mut deserializer); - let api_enable_plugin = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::generate_from_template( - api_v, - api_enable_plugin, - )) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__get_doc_root_from_str_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "get_doc_root_from_str", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = ::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::get_doc_root_from_str(api_s)) - })()) - }, - ) -} -fn wire__crate__api__llm_api__get_llm_config_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "get_llm_config", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - deserializer.end(); - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::get_llm_config()) - })()) - }, - ) -} -fn wire__crate__api__llm_api__init_llm_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "init_llm", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_p = ::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::init_llm(api_p)) - })()) - }, - ) -} -fn wire__crate__api__llm_api__init_prompt_from_path_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "init_prompt_from_path", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = ::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::init_prompt_from_path(api_s)) - })()) - }, - ) -} -fn wire__crate__api__llm_api__llm_message_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "llm_message_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = >::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || crate::api::llm_api::llm_message_stream(api_s))()) - }, - ) -} -fn wire__crate__api__llm_api__optimize_doc_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "optimize_doc", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::optimize_doc(api_s)) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__sequential_chain_chat_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "sequential_chain_chat", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_json_str = ::sse_decode(&mut deserializer); - let api_query = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::sequential_chain_chat( - api_json_str, - api_query, - )) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__template_message_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "template_message_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = >::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || { - crate::api::llm_api::template_message_stream(api_s) - })()) - }, - ) -} -fn wire__crate__api__llm_api__template_renderer_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "template_renderer", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_template = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::template_renderer(api_template)) - })()) - } - }, - ) -} -fn wire__crate__api__llm_api__template_state_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "template_state_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = >::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse((move || crate::api::llm_api::template_state_stream(api_s))()) - }, - ) -} -fn wire__crate__api__llm_api__template_to_prompts_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "template_to_prompts", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_template = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_api::template_to_prompts(api_template)) - })()) - } - }, - ) -} fn wire__crate__api__llm_plugin_api__eval_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -636,37 +115,7 @@ fn wire__crate__api__llm_plugin_api__get_mysql_table_info_impl( }, ) } -fn wire__crate__api__llm_plugin_api__mind_map_stream_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "mind_map_stream", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = - >::sse_decode( - &mut deserializer, - ); - deserializer.end(); - transform_result_sse((move || crate::api::llm_plugin_api::mind_map_stream(api_s))()) - }, - ) -} -fn wire__crate__api__llm_plugin_api__text_to_mind_map_impl( +fn wire__crate__api__llm_plugin_api__template_to_prompts_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -674,7 +123,7 @@ fn wire__crate__api__llm_plugin_api__text_to_mind_map_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "text_to_mind_map", + debug_name: "template_to_prompts", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -688,11 +137,13 @@ fn wire__crate__api__llm_plugin_api__text_to_mind_map_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_s = ::sse_decode(&mut deserializer); + let api_template = ::sse_decode(&mut deserializer); deserializer.end(); move |context| { transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_plugin_api::text_to_mind_map(api_s)) + Result::<_, ()>::Ok(crate::api::llm_plugin_api::template_to_prompts( + api_template, + )) })()) } }, @@ -791,6 +242,36 @@ fn wire__crate__api__simple__init_app_impl( }, ) } +fn wire__crate__api__simple__rust_error_stream_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "rust_error_stream", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_s = >::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse((move || crate::api::simple::rust_error_stream(api_s))()) + }, + ) +} fn wire__crate__api__software_monitor_api__add_to_watching_list_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -1167,14 +648,6 @@ impl SseDecode } } -impl SseDecode for StreamSink { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return StreamSink::deserialize(inner); - } -} - impl SseDecode for StreamSink, flutter_rust_bridge::for_generated::SseCodec> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1183,16 +656,6 @@ impl SseDecode for StreamSink, flutter_rust_bridge::for_generated::SseC } } -impl SseDecode - for StreamSink -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return StreamSink::deserialize(inner); - } -} - impl SseDecode for StreamSink { @@ -1221,32 +684,6 @@ impl SseDecode } } -impl SseDecode - for StreamSink< - crate::llm::template::TemplateResult, - flutter_rust_bridge::for_generated::SseCodec, - > -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return StreamSink::deserialize(inner); - } -} - -impl SseDecode - for StreamSink< - crate::llm::template::TemplateRunningStage, - flutter_rust_bridge::for_generated::SseCodec, - > -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return StreamSink::deserialize(inner); - } -} - impl SseDecode for String { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1268,29 +705,6 @@ impl SseDecode for crate::llm::app_flowy_model::AttributeType { } } -impl SseDecode for crate::llm::app_flowy_model::Attributes { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_bold = >::sse_decode(deserializer); - let mut var_italic = >::sse_decode(deserializer); - let mut var_file = >::sse_decode(deserializer); - let mut var_sql = >::sse_decode(deserializer); - return crate::llm::app_flowy_model::Attributes { - bold: var_bold, - italic: var_italic, - file: var_file, - sql: var_sql, - }; - } -} - -impl SseDecode for bool { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - deserializer.cursor.read_u8().unwrap() != 0 - } -} - impl SseDecode for crate::llm::plugins::chat_db::mysql::CellType { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1303,18 +717,6 @@ impl SseDecode for crate::llm::plugins::chat_db::mysql::CellType { } } -impl SseDecode for crate::llm::app_flowy_model::Children { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_typeField = ::sse_decode(deserializer); - let mut var_data = ::sse_decode(deserializer); - return crate::llm::app_flowy_model::Children { - type_field: var_typeField, - data: var_data, - }; - } -} - impl SseDecode for crate::system_monitor::CpuInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1325,20 +727,6 @@ impl SseDecode for crate::system_monitor::CpuInfo { } } -impl SseDecode for crate::llm::app_flowy_model::Data { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_level = >::sse_decode(deserializer); - let mut var_delta = >::sse_decode(deserializer); - let mut var_align = >::sse_decode(deserializer); - return crate::llm::app_flowy_model::Data { - level: var_level, - delta: var_delta, - align: var_align, - }; - } -} - impl SseDecode for crate::llm::plugins::chat_db::DatabaseInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1359,48 +747,6 @@ impl SseDecode for crate::llm::plugins::chat_db::DatabaseInfo { } } -impl SseDecode for crate::llm::app_flowy_model::Delum { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_insert = ::sse_decode(deserializer); - let mut var_attributes = - >::sse_decode(deserializer); - return crate::llm::app_flowy_model::Delum { - insert: var_insert, - attributes: var_attributes, - }; - } -} - -impl SseDecode for crate::llm::app_flowy_model::Document { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_typeField = ::sse_decode(deserializer); - let mut var_children = - >::sse_decode(deserializer); - return crate::llm::app_flowy_model::Document { - type_field: var_typeField, - children: var_children, - }; - } -} - -impl SseDecode for crate::llm::EnvParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_base = ::sse_decode(deserializer); - let mut var_name = ::sse_decode(deserializer); - let mut var_chatBase = ::sse_decode(deserializer); - let mut var_sk = >::sse_decode(deserializer); - return crate::llm::EnvParams { - base: var_base, - name: var_name, - chat_base: var_chatBase, - sk: var_sk, - }; - } -} - impl SseDecode for crate::errors::ErrorModule { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1461,46 +807,6 @@ impl SseDecode for Vec { } } -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(::sse_decode(deserializer)); - } - return ans_; - } -} - -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - impl SseDecode for Vec> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1508,20 +814,8 @@ impl SseDecode for Vec> { let mut ans_ = vec![]; for idx_ in 0..len_ { ans_.push(>::sse_decode( - deserializer, - )); - } - return ans_; - } -} - -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(::sse_decode(deserializer)); + deserializer, + )); } return ans_; } @@ -1639,32 +933,6 @@ impl SseDecode for Vec<(String, String)> { } } -impl SseDecode - for Vec<( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - )> -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(<( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - )>::sse_decode(deserializer)); - } - return ans_; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1721,20 +989,6 @@ impl SseDecode for Vec { } } -impl SseDecode for crate::llm::LLMMessage { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_uuid = ::sse_decode(deserializer); - let mut var_content = ::sse_decode(deserializer); - let mut var_type = ::sse_decode(deserializer); - return crate::llm::LLMMessage { - uuid: var_uuid, - content: var_content, - _type: var_type, - }; - } -} - impl SseDecode for crate::system_monitor::MemoryInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1810,30 +1064,6 @@ impl SseDecode for Option { } } -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode( - deserializer, - )); - } else { - return None; - } - } -} - -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1845,28 +1075,6 @@ impl SseDecode for Option { } } -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1880,41 +1088,6 @@ impl SseDecode for Option { } } -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode( - deserializer, - )); - } else { - return None; - } - } -} - -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - -impl SseDecode for Option> { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(>::sse_decode(deserializer)); - } else { - return None; - } - } -} - impl SseDecode for Option> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2034,36 +1207,6 @@ impl SseDecode for (String, String) { } } -impl SseDecode - for ( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - ) -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_field0 = ::sse_decode(deserializer); - let mut var_field1 = ::sse_decode(deserializer); - let mut var_field2 = >::sse_decode(deserializer); - let mut var_field3 = ::sse_decode(deserializer); - let mut var_field4 = >::sse_decode(deserializer); - return (var_field0, var_field1, var_field2, var_field3, var_field4); - } -} - -impl SseDecode for crate::llm::app_flowy_model::Root { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_document = ::sse_decode(deserializer); - return crate::llm::app_flowy_model::Root { - document: var_document, - }; - } -} - impl SseDecode for crate::errors::RustError { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2132,34 +1275,6 @@ impl SseDecode for crate::llm::plugins::chat_db::TableInfo { } } -impl SseDecode for crate::llm::template::TemplateResult { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_prompt = ::sse_decode(deserializer); - let mut var_index = ::sse_decode(deserializer); - let mut var_response = ::sse_decode(deserializer); - return crate::llm::template::TemplateResult { - prompt: var_prompt, - index: var_index, - response: var_response, - }; - } -} - -impl SseDecode for crate::llm::template::TemplateRunningStage { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return match inner { - 0 => crate::llm::template::TemplateRunningStage::Format, - 1 => crate::llm::template::TemplateRunningStage::Eval, - 2 => crate::llm::template::TemplateRunningStage::Optimize, - 3 => crate::llm::template::TemplateRunningStage::Done, - _ => unreachable!("Invalid variant for TemplateRunningStage: {}", inner), - }; - } -} - impl SseDecode for u32 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2193,6 +1308,13 @@ impl SseDecode for usize { } } +impl SseDecode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u8().unwrap() != 0 + } +} + fn pde_ffi_dispatcher_primary_impl( func_id: i32, port: flutter_rust_bridge::for_generated::MessagePort, @@ -2202,79 +1324,58 @@ fn pde_ffi_dispatcher_primary_impl( ) { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 15 => wire__crate__api__llm_api__ai_helper_quick_request_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 8 => wire__crate__api__llm_api__chat_impl(port, ptr, rust_vec_len, data_len), - 12 => wire__crate__api__llm_api__generate_from_template_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 13 => wire__crate__api__llm_api__optimize_doc_impl(port, ptr, rust_vec_len, data_len), - 9 => { - wire__crate__api__llm_api__sequential_chain_chat_impl(port, ptr, rust_vec_len, data_len) - } - 10 => wire__crate__api__llm_api__template_renderer_impl(port, ptr, rust_vec_len, data_len), - 11 => { - wire__crate__api__llm_api__template_to_prompts_impl(port, ptr, rust_vec_len, data_len) - } - 18 => wire__crate__api__llm_plugin_api__eval_impl(port, ptr, rust_vec_len, data_len), - 17 => wire__crate__api__llm_plugin_api__get_mysql_table_info_impl( + 2 => wire__crate__api__llm_plugin_api__eval_impl(port, ptr, rust_vec_len, data_len), + 1 => wire__crate__api__llm_plugin_api__get_mysql_table_info_impl( port, ptr, rust_vec_len, data_len, ), - 19 => wire__crate__api__llm_plugin_api__text_to_mind_map_impl( + 3 => wire__crate__api__llm_plugin_api__template_to_prompts_impl( port, ptr, rust_vec_len, data_len, ), - 21 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( + 4 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( port, ptr, rust_vec_len, data_len, ), - 23 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), - 28 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( + 6 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), + 12 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 25 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( + 9 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( port, ptr, rust_vec_len, data_len, ), - 24 => wire__crate__api__software_monitor_api__init_monitor_impl( + 8 => wire__crate__api__software_monitor_api__init_monitor_impl( port, ptr, rust_vec_len, data_len, ), - 29 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( + 13 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 30 => wire__crate__api__sub_window_api__create_event_loop_impl( + 14 => wire__crate__api__sub_window_api__create_event_loop_impl( port, ptr, rust_vec_len, data_len, ), - 31 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), - 33 => wire__crate__api__system_monitor_api__start_system_monitor_impl( + 15 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), + 17 => wire__crate__api__system_monitor_api__start_system_monitor_impl( port, ptr, rust_vec_len, @@ -2292,20 +1393,11 @@ fn pde_ffi_dispatcher_sync_impl( ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 4 => wire__crate__api__llm_api__ai_helper_message_stream_impl(ptr, rust_vec_len, data_len), -6 => wire__crate__api__llm_api__error_message_stream_impl(ptr, rust_vec_len, data_len), -14 => wire__crate__api__llm_api__get_doc_root_from_str_impl(ptr, rust_vec_len, data_len), -2 => wire__crate__api__llm_api__get_llm_config_impl(ptr, rust_vec_len, data_len), -1 => wire__crate__api__llm_api__init_llm_impl(ptr, rust_vec_len, data_len), -16 => wire__crate__api__llm_api__init_prompt_from_path_impl(ptr, rust_vec_len, data_len), -3 => wire__crate__api__llm_api__llm_message_stream_impl(ptr, rust_vec_len, data_len), -5 => wire__crate__api__llm_api__template_message_stream_impl(ptr, rust_vec_len, data_len), -7 => wire__crate__api__llm_api__template_state_stream_impl(ptr, rust_vec_len, data_len), -20 => wire__crate__api__llm_plugin_api__mind_map_stream_impl(ptr, rust_vec_len, data_len), -22 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), -26 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), -27 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), -32 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), + 5 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), +7 => wire__crate__api__simple__rust_error_stream_impl(ptr, rust_vec_len, data_len), +10 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), +11 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), +16 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -2354,29 +1446,6 @@ impl flutter_rust_bridge::IntoIntoDart flutter_rust_bridge::for_generated::DartAbi { - [ - self.bold.into_into_dart().into_dart(), - self.italic.into_into_dart().into_dart(), - self.file.into_into_dart().into_dart(), - self.sql.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Attributes -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Attributes -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::Attributes { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::llm::plugins::chat_db::mysql::CellType { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { @@ -2397,27 +1466,6 @@ impl flutter_rust_bridge::IntoIntoDart flutter_rust_bridge::for_generated::DartAbi { - [ - self.type_field.into_into_dart().into_dart(), - self.data.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Children -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Children -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::Children { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::system_monitor::CpuInfo { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [self.current.into_into_dart().into_dart()].into_dart() @@ -2435,28 +1483,6 @@ impl flutter_rust_bridge::IntoIntoDart } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::app_flowy_model::Data { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.level.into_into_dart().into_dart(), - self.delta.into_into_dart().into_dart(), - self.align.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Data -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Data -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::Data { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::llm::plugins::chat_db::DatabaseInfo { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -2482,66 +1508,6 @@ impl flutter_rust_bridge::IntoIntoDart flutter_rust_bridge::for_generated::DartAbi { - [ - self.insert.into_into_dart().into_dart(), - self.attributes.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Delum -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Delum -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::Delum { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::app_flowy_model::Document { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.type_field.into_into_dart().into_dart(), - self.children.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Document -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Document -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::Document { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::EnvParams { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.base.into_into_dart().into_dart(), - self.name.into_into_dart().into_dart(), - self.chat_base.into_into_dart().into_dart(), - self.sk.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::llm::EnvParams {} -impl flutter_rust_bridge::IntoIntoDart for crate::llm::EnvParams { - fn into_into_dart(self) -> crate::llm::EnvParams { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::errors::ErrorModule { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { @@ -2573,23 +1539,6 @@ impl flutter_rust_bridge::IntoIntoDart for crate::erro } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::LLMMessage { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.uuid.into_into_dart().into_dart(), - self.content.into_into_dart().into_dart(), - self._type.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::llm::LLMMessage {} -impl flutter_rust_bridge::IntoIntoDart for crate::llm::LLMMessage { - fn into_into_dart(self) -> crate::llm::LLMMessage { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::system_monitor::MemoryInfo { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -2674,27 +1623,10 @@ impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::system_monitor::ProcessPortMapper { } -impl flutter_rust_bridge::IntoIntoDart - for crate::system_monitor::ProcessPortMapper -{ - fn into_into_dart(self) -> crate::system_monitor::ProcessPortMapper { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::app_flowy_model::Root { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.document.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::Root -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::Root +impl flutter_rust_bridge::IntoIntoDart + for crate::system_monitor::ProcessPortMapper { - fn into_into_dart(self) -> crate::llm::app_flowy_model::Root { + fn into_into_dart(self) -> crate::system_monitor::ProcessPortMapper { self } } @@ -2802,50 +1734,6 @@ impl flutter_rust_bridge::IntoIntoDart self } } -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::template::TemplateResult { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.prompt.into_into_dart().into_dart(), - self.index.into_into_dart().into_dart(), - self.response.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::template::TemplateResult -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::template::TemplateResult -{ - fn into_into_dart(self) -> crate::llm::template::TemplateResult { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::llm::template::TemplateRunningStage { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - match self { - Self::Format => 0.into_dart(), - Self::Eval => 1.into_dart(), - Self::Optimize => 2.into_dart(), - Self::Done => 3.into_dart(), - } - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::template::TemplateRunningStage -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::template::TemplateRunningStage -{ - fn into_into_dart(self) -> crate::llm::template::TemplateRunningStage { - self - } -} impl SseEncode for flutter_rust_bridge::for_generated::anyhow::Error { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2890,13 +1778,6 @@ impl SseEncode } } -impl SseEncode for StreamSink { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - unimplemented!("") - } -} - impl SseEncode for StreamSink, flutter_rust_bridge::for_generated::SseCodec> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -2904,15 +1785,6 @@ impl SseEncode for StreamSink, flutter_rust_bridge::for_generated::SseC } } -impl SseEncode - for StreamSink -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - unimplemented!("") - } -} - impl SseEncode for StreamSink { @@ -2938,30 +1810,6 @@ impl SseEncode } } -impl SseEncode - for StreamSink< - crate::llm::template::TemplateResult, - flutter_rust_bridge::for_generated::SseCodec, - > -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - unimplemented!("") - } -} - -impl SseEncode - for StreamSink< - crate::llm::template::TemplateRunningStage, - flutter_rust_bridge::for_generated::SseCodec, - > -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - unimplemented!("") - } -} - impl SseEncode for String { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -2986,23 +1834,6 @@ impl SseEncode for crate::llm::app_flowy_model::AttributeType { } } -impl SseEncode for crate::llm::app_flowy_model::Attributes { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.bold, serializer); - >::sse_encode(self.italic, serializer); - >::sse_encode(self.file, serializer); - >::sse_encode(self.sql, serializer); - } -} - -impl SseEncode for bool { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - serializer.cursor.write_u8(self as _).unwrap(); - } -} - impl SseEncode for crate::llm::plugins::chat_db::mysql::CellType { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3019,14 +1850,6 @@ impl SseEncode for crate::llm::plugins::chat_db::mysql::CellType { } } -impl SseEncode for crate::llm::app_flowy_model::Children { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.type_field, serializer); - ::sse_encode(self.data, serializer); - } -} - impl SseEncode for crate::system_monitor::CpuInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3034,15 +1857,6 @@ impl SseEncode for crate::system_monitor::CpuInfo { } } -impl SseEncode for crate::llm::app_flowy_model::Data { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.level, serializer); - >::sse_encode(self.delta, serializer); - >::sse_encode(self.align, serializer); - } -} - impl SseEncode for crate::llm::plugins::chat_db::DatabaseInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3055,32 +1869,6 @@ impl SseEncode for crate::llm::plugins::chat_db::DatabaseInfo { } } -impl SseEncode for crate::llm::app_flowy_model::Delum { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.insert, serializer); - >::sse_encode(self.attributes, serializer); - } -} - -impl SseEncode for crate::llm::app_flowy_model::Document { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.type_field, serializer); - >::sse_encode(self.children, serializer); - } -} - -impl SseEncode for crate::llm::EnvParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.base, serializer); - ::sse_encode(self.name, serializer); - ::sse_encode(self.chat_base, serializer); - >::sse_encode(self.sk, serializer); - } -} - impl SseEncode for crate::errors::ErrorModule { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3145,36 +1933,6 @@ impl SseEncode for Vec { } } -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3185,16 +1943,6 @@ impl SseEncode for Vec> { } } -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3285,30 +2033,6 @@ impl SseEncode for Vec<(String, String)> { } } -impl SseEncode - for Vec<( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - )> -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - <( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - )>::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3349,15 +2073,6 @@ impl SseEncode for Vec { } } -impl SseEncode for crate::llm::LLMMessage { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.uuid, serializer); - ::sse_encode(self.content, serializer); - ::sse_encode(self._type, serializer); - } -} - impl SseEncode for crate::system_monitor::MemoryInfo { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3411,26 +2126,6 @@ impl SseEncode for Option { } } -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3441,26 +2136,6 @@ impl SseEncode for Option { } } -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3471,36 +2146,6 @@ impl SseEncode for Option { } } -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - -impl SseEncode for Option> { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - >::sse_encode(value, serializer); - } - } -} - impl SseEncode for Option> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3598,32 +2243,6 @@ impl SseEncode for (String, String) { } } -impl SseEncode - for ( - String, - u32, - Option, - crate::llm::app_flowy_model::AttributeType, - Option, - ) -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.0, serializer); - ::sse_encode(self.1, serializer); - >::sse_encode(self.2, serializer); - ::sse_encode(self.3, serializer); - >::sse_encode(self.4, serializer); - } -} - -impl SseEncode for crate::llm::app_flowy_model::Root { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.document, serializer); - } -} - impl SseEncode for crate::errors::RustError { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3668,33 +2287,6 @@ impl SseEncode for crate::llm::plugins::chat_db::TableInfo { } } -impl SseEncode for crate::llm::template::TemplateResult { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.prompt, serializer); - ::sse_encode(self.index, serializer); - ::sse_encode(self.response, serializer); - } -} - -impl SseEncode for crate::llm::template::TemplateRunningStage { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode( - match self { - crate::llm::template::TemplateRunningStage::Format => 0, - crate::llm::template::TemplateRunningStage::Eval => 1, - crate::llm::template::TemplateRunningStage::Optimize => 2, - crate::llm::template::TemplateRunningStage::Done => 3, - _ => { - unimplemented!(""); - } - }, - serializer, - ); - } -} - impl SseEncode for u32 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3731,6 +2323,13 @@ impl SseEncode for usize { } } +impl SseEncode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u8(self as _).unwrap(); + } +} + #[cfg(not(target_family = "wasm"))] #[path = "frb_generated.io.rs"] mod io; diff --git a/rust/src/llm/ai_helper.rs b/rust/src/llm/ai_helper.rs deleted file mode 100644 index f91b920..0000000 --- a/rust/src/llm/ai_helper.rs +++ /dev/null @@ -1,42 +0,0 @@ -use futures::StreamExt; -use langchain_rust::language_models::llm::LLM; -use langchain_rust::schemas::Message; -use std::sync::RwLock; - -use crate::llm::StreamSink; - -use super::OPENAI; - -pub static AI_HELPER_MESSAGE_SINK: RwLock>> = RwLock::new(None); - -pub async fn ai_quick_request(s: String) { - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - let mut sm = open_ai - .stream(&vec![Message::new_human_message(s)]) - .await - .unwrap(); - - while let Some(result) = sm.next().await { - match result { - Ok(value) => match AI_HELPER_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(value.content); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - }, - Err(e) => { - println!("Error invoking LLMChain: {:?}", e); - } - } - } -} diff --git a/rust/src/llm/app_flowy_model.rs b/rust/src/llm/app_flowy_model.rs index c2a5745..a176591 100644 --- a/rust/src/llm/app_flowy_model.rs +++ b/rust/src/llm/app_flowy_model.rs @@ -1,5 +1,3 @@ -use super::OPENAI; -use langchain_rust::language_models::llm::LLM; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -117,178 +115,3 @@ pub fn get_all_cadidates( anyhow::Ok(v) } - -#[allow(unused_imports)] -mod tests { - use langchain_rust::{ - language_models::llm::LLM, - llm::{OpenAI, OpenAIConfig}, - }; - use regex::Regex; - - use super::str_to_doc; - - #[tokio::test] - async fn json_read_test() -> anyhow::Result<()> { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let open_ai = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - // let response = open_ai.invoke("how can langsmith help with testing?").await; - - let data = r#" - { - "document": { - "type": "page", - "children": [ - { - "type": "heading", - "data": { - "level": 2, - "delta": [ - { - "insert": "👋 " - }, - { - "insert": "Welcome to", - "attributes": { - "bold": true, - "italic": false - } - }, - { - "insert": " " - }, - { - "insert": "Template editor", - "attributes": { - "bold": true, - "italic": true - } - } - ], - "align": "center" - } - }, - { - "type": "paragraph", - "data": { - "delta": [ - { - "insert": "我司打算本周六进行团建,场地:{{请帮我推荐一个10人左右的场地,坐标常州。仅需要一个地点,且只需要提供场地名称,不需要其它信息}}。" - } - ] - } - }, - { - "type": "paragraph", - "data": { - "delta": [ - { - "insert": "具体流程包括:" - } - ] - } - }, - { - "type": "paragraph", - "data": { - "delta": [ - { - "insert": "{{ 请帮我推荐10人左右团建活动}}" - } - ] - } - }, - { - "type": "paragraph", - "data": { - "delta": [ - { - "insert": "晚餐安排:" - } - ] - } - }, - { - "type": "paragraph", - "data": { - "delta": [ - { - "insert": "{{ 请帮我推荐10人左右团建晚餐菜品推荐,并提供报价单 }}" - } - ] - } - } - ] - } - } - "#; - - let re = Regex::new(r"\{\{(.*?)\}\}").unwrap(); - - let root = str_to_doc(data.to_owned())?; - - let doc = root.document; - let children = doc.children; - - for i in children { - if !i.data.delta.is_empty() { - for mut d in i.data.delta { - for cap in re.captures_iter(&d.insert.clone()) { - if let Some(matched) = cap.get(0) { - println!("Matched text: {}", matched.as_str()); - let response = open_ai.invoke(matched.as_str()).await?; - d.insert = d.insert.replace(matched.as_str(), &response); - println!("response text: {}", d.insert); - } - } - } - } - } - - anyhow::Ok(()) - } -} - -pub async fn template_renderer_impl(template: String) -> anyhow::Result { - let re = Regex::new(r"\{\{(.*?)\}\}").unwrap(); - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - let mut root = str_to_doc(template)?; - - { - let doc = &mut root.document; - let children = &mut doc.children; - - for i in children { - if !i.data.delta.is_empty() { - for d in i.data.delta.iter_mut() { - for cap in re.captures_iter(&d.insert.clone()) { - if let Some(matched) = cap.get(0) { - let response = open_ai.invoke(matched.as_str()).await?; - d.insert = d.insert.replace(matched.as_str(), &response); - // println!("response text: {}", d.insert); - } - } - } - } - } - } - - let res = doc_to_str(&root)?; - - Ok(res) -} diff --git a/rust/src/llm/internal_prompts.rs b/rust/src/llm/internal_prompts.rs index f52eb69..635dead 100644 --- a/rust/src/llm/internal_prompts.rs +++ b/rust/src/llm/internal_prompts.rs @@ -36,9 +36,9 @@ impl Prompts { Self::from_str(contents) } - pub fn get_by_name(&self, key:String,module:String)-> Option{ - for i in &self.prompts{ - if i.module == module && i.name == key{ + pub fn get_by_name(&self, key: String, module: String) -> Option { + for i in &self.prompts { + if i.module == module && i.name == key { return Some(i.prompt.clone()); } } diff --git a/rust/src/llm/mod.rs b/rust/src/llm/mod.rs index ce88d6d..7532819 100644 --- a/rust/src/llm/mod.rs +++ b/rust/src/llm/mod.rs @@ -1,20 +1,8 @@ -pub mod ai_helper; pub mod app_flowy_model; pub mod internal_prompts; -pub mod models; pub mod plugins; -pub mod sequential_chain_builder; pub mod template; -mod tests; -use futures::StreamExt; -use langchain_rust::chain::Chain; -use langchain_rust::language_models::llm::LLM; -use langchain_rust::prompt_args; -use langchain_rust::{ - llm::{OpenAI, OpenAIConfig}, - schemas::Message, -}; use once_cell::sync::Lazy; use std::collections::HashMap; use std::fs::File; @@ -23,27 +11,8 @@ use std::sync::RwLock; use crate::frb_generated::StreamSink; -use self::models::ChainIOes; -use self::sequential_chain_builder::CustomSequentialChain; - pub static ENV_PARAMS: Lazy>> = Lazy::new(|| RwLock::new(None)); -pub static OPENAI: Lazy>> = Lazy::new(|| { - let params; - { - params = ENV_PARAMS.read().unwrap().clone().unwrap(); - } - let open_ai = OpenAI::default() - .with_config( - OpenAIConfig::new() - .with_api_base(params.base) - .with_api_key(params.sk.unwrap()), - ) - .with_model(params.name); - - RwLock::new(open_ai) -}); - #[derive(Debug, Clone)] pub struct EnvParams { pub base: String, @@ -52,37 +21,6 @@ pub struct EnvParams { pub sk: Option, } -pub fn init(p: String) { - // match p { - // Some(_p) => { - // let _ = dotenv::from_path(_p); - // } - // None => { - // dotenv().ok(); - // } - // } - - let map = crate::llm::env_parse(p).unwrap(); - - let base = map.get("LLM_BASE").unwrap().to_string(); - let name = map.get("LLM_MODEL_NAME").unwrap().to_string(); - let sk = map.get("LLM_SK").unwrap_or(&"".to_string()).to_string(); - let chat_base = map - .get("CHAT_CHAT_BASE") - .unwrap_or(&"".to_string()) - .to_string(); - - { - let mut r = ENV_PARAMS.write().unwrap(); - *r = Some(EnvParams { - base, - name, - chat_base, - sk: Some(sk), - }); - } -} - pub static LLM_MESSAGE_SINK: RwLock>> = RwLock::new(None); #[derive(Debug, Clone)] @@ -102,164 +40,6 @@ impl LLMMessage { } } -pub async fn chat( - _uuid: Option, - _history: Option>, - stream: bool, - query: String, -) { - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - - let mut message = LLMMessage::default(); - if _uuid.is_none() { - message.uuid = uuid::Uuid::new_v4().to_string(); - } else { - message.uuid = _uuid.unwrap(); - } - - let mut history = Vec::new(); - if !_history.is_none() { - history = _history - .unwrap() - .iter() - .map(|x| match x._type { - 0 => Message::new_human_message(x.content.clone()), - 1 => Message::new_system_message(x.content.clone()), - 2 => Message::new_ai_message(x.content.clone()), - _ => Message::new_human_message(x.content.clone()), - }) - .collect() - } - history.push(Message::new_human_message(query.clone())); - - if stream { - let mut sm = open_ai.stream(&history).await.unwrap(); - - while let Some(result) = sm.next().await { - match result { - Ok(value) => { - message.content = value.content; - - match LLM_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(message.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - Err(e) => panic!("Error invoking LLMChain: {:?}", e), - } - } - message.content = "!over!".to_owned(); - match LLM_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(message.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } else { - let response = open_ai.generate(&history).await; - // println!("{:?}", response); - match response { - Ok(_r) => { - message.content = _r.generation; - match LLM_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(message.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - Err(e) => { - println!("[rust] error {:?}", e); - message.content = e.to_string(); - match LLM_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(message.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - } - - message.content = "!over!".to_owned(); - match LLM_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(message); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } -} - -pub async fn sequential_chain_chat(json_str: String, query: String) -> anyhow::Result<()> { - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - let items: ChainIOes = serde_json::from_str(&json_str)?; - let first_input = items.items.first().unwrap().input_key.clone(); - let seq = CustomSequentialChain { - chains: items.items, - }; - - let seq_chain = seq.build(open_ai.clone()); - match seq_chain { - Some(_seq) => { - let output = _seq - .execute(prompt_args! { - first_input => query - }) - .await - .unwrap(); - println!("output: {:?}", output); - } - None => { - println!("none"); - } - } - - anyhow::Ok(()) -} - pub fn env_parse(path: String) -> anyhow::Result> { let mut res = HashMap::new(); let file = File::open(path)?; diff --git a/rust/src/llm/models.rs b/rust/src/llm/models.rs deleted file mode 100644 index 19f9514..0000000 --- a/rust/src/llm/models.rs +++ /dev/null @@ -1,40 +0,0 @@ -use langchain_rust::{ - chain::{LLMChain, LLMChainBuilder}, - llm::{Config, OpenAI}, - prompt::HumanMessagePromptTemplate, - template_jinja2, -}; -use serde::Deserialize; - -#[derive(Deserialize)] -pub struct ChainIO { - pub input_key: String, - pub output_key: String, - pub prompt: String, -} - -#[derive(Deserialize)] -pub struct ChainIOes { - pub items: Vec, -} - -impl ChainIO { - fn to_prompt(&self) -> HumanMessagePromptTemplate { - let f = self.prompt.replace("placeholder", &self.input_key); - - HumanMessagePromptTemplate::new(template_jinja2!(f, self.input_key)) - } - - pub fn to_chain( - &self, - llm: OpenAI, - ) -> anyhow::Result { - anyhow::Ok( - LLMChainBuilder::new() - .prompt(self.to_prompt()) - .llm(llm.clone()) - .output_key(self.output_key.clone()) - .build()?, - ) - } -} diff --git a/rust/src/llm/plugins/chat_file.rs b/rust/src/llm/plugins/chat_file.rs index 75d1790..02f11ea 100644 --- a/rust/src/llm/plugins/chat_file.rs +++ b/rust/src/llm/plugins/chat_file.rs @@ -82,22 +82,3 @@ pub async fn get_file_content(p: String) -> anyhow::Result { None => anyhow::bail!("open ai client is None"), } } - -mod tests { - #[tokio::test] - async fn test_read_file() { - crate::llm::init("env".to_owned()); - let s = crate::llm::plugins::chat_file::get_file_content( - r"d:\Desktop\个保法方案.pdf".to_owned(), - ) - .await; - match s { - Ok(_s) => { - println!("{}", _s); - } - Err(_e) => { - println!("{:?}", _e); - } - } - } -} diff --git a/rust/src/llm/plugins/mind_map.rs b/rust/src/llm/plugins/mind_map.rs deleted file mode 100644 index 06f4df2..0000000 --- a/rust/src/llm/plugins/mind_map.rs +++ /dev/null @@ -1,82 +0,0 @@ -use std::sync::RwLock; - -use crate::llm::internal_prompts::INERTNAL_PROMPTS; -use crate::llm::StreamSink; -use crate::llm::OPENAI; -use futures::StreamExt; -use langchain_rust::language_models::llm::LLM; -use langchain_rust::schemas::Message; - -pub static MIND_MAP_MESSAGE_SINK: RwLock>> = RwLock::new(None); - -pub async fn text_to_mind_map(s: String) { - let prompts = INERTNAL_PROMPTS.read().unwrap(); - - if let Some(_p) = prompts.clone() { - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - let mut history = Vec::new(); - - let system_role = _p.get_by_name("role-define".to_owned(), "conversion".to_owned()); - - if system_role.is_none() { - return; - } - - history.push(Message::new_system_message(system_role.unwrap())); - - let inst = _p.get_by_name( - "convert-file-to-mind-map".to_owned(), - "conversion".to_owned(), - ); - - if inst.is_none() { - return; - } - - history.push(Message::new_human_message(inst.unwrap())); - history.push(Message::new_human_message(s)); - - let mut sm = open_ai.stream(&history).await.unwrap(); - - while let Some(result) = sm.next().await { - match result { - Ok(value) => { - println!("{:?}", value.content); - match MIND_MAP_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(value.content); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - Err(_e) => { - println!("Error invoking LLMChain: {:?}", _e); - } - } - } - - match MIND_MAP_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add("!over!".to_owned()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } -} diff --git a/rust/src/llm/plugins/mod.rs b/rust/src/llm/plugins/mod.rs index 39553bb..98d28a7 100644 --- a/rust/src/llm/plugins/mod.rs +++ b/rust/src/llm/plugins/mod.rs @@ -1,26 +1,2 @@ -use async_openai::config::OpenAIConfig; - -use super::ENV_PARAMS; - pub mod chat_db; pub mod chat_file; -pub mod mind_map; - -pub fn get_openai_client() -> (Option>, Option) { - let params = ENV_PARAMS.read().unwrap(); - match params.clone() { - Some(_p) => { - return ( - Some(async_openai::Client::with_config( - OpenAIConfig::new() - .with_api_base(_p.base) - .with_api_key(_p.sk.unwrap()), - )), - Some(_p.name), - ); - } - None => { - return (None, None); - } - } -} diff --git a/rust/src/llm/sequential_chain_builder.rs b/rust/src/llm/sequential_chain_builder.rs deleted file mode 100644 index f237ef1..0000000 --- a/rust/src/llm/sequential_chain_builder.rs +++ /dev/null @@ -1,30 +0,0 @@ -use langchain_rust::{ - chain::{SequentialChain, SequentialChainBuilder}, - llm::{Config, OpenAI}, -}; - -use super::models::ChainIO; - -pub struct CustomSequentialChain { - pub chains: Vec, -} - -impl CustomSequentialChain { - pub fn build( - &self, - llm: OpenAI, - ) -> Option { - let mut seq_chain = SequentialChainBuilder::new(); - - for i in &self.chains { - let _c = i.to_chain(llm.clone()); - if let Ok(_c) = _c { - seq_chain = seq_chain.add_chain(_c); - } else { - return None; - } - } - - Some(seq_chain.build()) - } -} diff --git a/rust/src/llm/template.rs b/rust/src/llm/template.rs index ec2cc44..da19e5a 100644 --- a/rust/src/llm/template.rs +++ b/rust/src/llm/template.rs @@ -1,48 +1,4 @@ -use std::{collections::HashMap, sync::RwLock}; - -use futures::StreamExt; -use langchain_rust::{ - chain::{Chain, LLMChainBuilder, SequentialChainBuilder}, - language_models::llm::LLM, - llm::{Config, OpenAI}, - prompt::{HumanMessagePromptTemplate, PromptTemplate, TemplateFormat}, - prompt_args, - schemas::Message, - template_jinja2, -}; - -use crate::{errors::RustError, frb_generated::StreamSink}; - -use super::{app_flowy_model::AttributeType, plugins::chat_file::get_file_content, OPENAI}; - -pub enum TemplateRunningStage { - Format, - Eval, - Optimize, - Done, -} - -impl TemplateRunningStage { - pub fn change_stage(stage: TemplateRunningStage) { - match TEMPLATE_STATE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(stage); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - - pub fn finish() { - Self::change_stage(TemplateRunningStage::Done) - } -} +use super::app_flowy_model::AttributeType; pub struct AppFlowyTemplate { pub items: Vec, @@ -80,11 +36,6 @@ pub fn generate_template_items_from_list( v } -pub static TEMPLATE_MESSAGE_SINK: RwLock>> = RwLock::new(None); - -pub static TEMPLATE_STATE_SINK: RwLock>> = - RwLock::new(None); - #[derive(Debug, Clone)] pub struct TemplateResult { pub prompt: String, @@ -92,38 +43,6 @@ pub struct TemplateResult { pub response: String, } -pub async fn optimize_doc(doc: String) -> String { - println!("[rust] optimize doc : {:?}", doc); - - TemplateRunningStage::change_stage(TemplateRunningStage::Optimize); - - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - - let out = open_ai - .clone() - .generate(&[ - Message::new_system_message("你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), - Message::new_human_message("请帮我改写优化以下文章。注意:1.进行文章改写时请尽量使用简体中文。\n2.只改写优化 标签中的部分。\n3.保留 标签中的内容。\n4.最终结果中删除 标签。"), - Message::new_human_message(doc), - ]) - .await; - - TemplateRunningStage::change_stage(TemplateRunningStage::Done); - - if let Err(e) = out { - let mut errmsg: RustError = RustError::default(); - errmsg.errmsg = "结果优化失败".to_owned(); - errmsg.context = Some(format!("[traceback] {:?}", e)); - errmsg.send_to_dart(); - return "".to_owned(); - } - - out.unwrap().generation -} - impl AppFlowyTemplate { pub fn from(v: Vec) -> Self { Self { items: v } @@ -171,517 +90,86 @@ impl AppFlowyTemplate { } vecs } - - pub async fn execute(&mut self, enable_plugin: bool) { - TemplateRunningStage::change_stage(TemplateRunningStage::Format); - - let separated_vecs = self.into_multiple(); - println!("[rust] separated_vecs length {}", separated_vecs.len()); - if separated_vecs.is_empty() { - TemplateRunningStage::change_stage(TemplateRunningStage::Done); - return; - } - - let open_ai; - { - open_ai = OPENAI.read().unwrap(); - } - - TemplateRunningStage::change_stage(TemplateRunningStage::Eval); - - for i in separated_vecs { - println!("[rust] chain length {}", i.len()); - let s; - if !enable_plugin { - s = items_to_chain(&i, open_ai.clone()); - } else { - s = items_to_chain_with_plugins(&i, open_ai.clone()).await; - } - - Self::execute_worker(s, i).await; - } - } - - async fn execute_worker(s: (Option>, Option), i: Vec<&TemplateItem>) { - let mut err_msg: RustError = RustError::default(); - - if let Some(c) = s.0 { - if let Some(p) = s.1 { - let out = c - .execute(prompt_args! { - "input0" => p - }) - .await; - - if let Err(_out) = out { - err_msg.errmsg = "chain初始化失败".to_owned(); - err_msg.context = Some(format!("[traceback] {:?}", _out)); - err_msg.send_to_dart(); - TemplateRunningStage::finish(); - return; - } - - let output = out.unwrap().clone(); - - // println!("output {:?}", output); - let mut index = 0; - let mut map: HashMap = HashMap::new(); - // map.insert("input0".to_owned(), p.clone()); - while index < i.len() { - let key = format!("input{}", index + 1); - let value = output.get(&key).unwrap(); - map.insert(i.get(index).unwrap().prompt.clone(), value.to_string()); - index += 1; - } - - println!("map {:?}", map); - - index = 0; - for kv in map.into_iter() { - let template_result = TemplateResult { - prompt: kv.0, - index: index.try_into().unwrap(), - response: kv.1, - }; - - match TEMPLATE_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(template_result.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - - index += 1; - } - - // stream not implemented for seq-chain - - // let mut stream = c - // .stream(prompt_args! { - // "input0" => p - // }) - // .await - // .unwrap(); - - // while let Some(result) = stream.next().await { - // match result { - // Ok(value) => value.to_stdout().unwrap(), - // Err(e) => panic!("Error invoking LLMChain: {:?}", e), - // } - // } - } else { - let mut template_result = TemplateResult { - prompt: i.first().unwrap().prompt.clone(), - index: i.first().unwrap().index, - response: "".to_string(), - }; - let st = c.stream(HashMap::new()).await; - - match st { - Ok(mut stream) => { - while let Some(result) = stream.next().await { - match result { - Ok(value) => { - // value.to_stdout().unwrap(); - template_result.response += &value.content; - match TEMPLATE_MESSAGE_SINK.try_read() { - Ok(s) => match s.as_ref() { - Some(s0) => { - let _ = s0.add(template_result.clone()); - } - None => { - println!("[rust-error] Stream is None"); - } - }, - Err(_) => { - println!("[rust-error] Stream read error"); - } - } - } - Err(e) => panic!("Error invoking LLMChain: {:?}", e), - } - } - } - Err(_e) => { - err_msg.errmsg = "stream 错误".to_owned(); - err_msg.context = Some(format!("[traceback] {:?}", _e)); - err_msg.send_to_dart(); - TemplateRunningStage::finish(); - } - } - } - } - } -} - -fn items_to_chain( - items: &Vec<&TemplateItem>, - llm: OpenAI, -) -> (Option>, Option) { - if items.is_empty() { - return (None, None); - } - - if items.len() == 1 { - // 返回一般的LLMChain - let prompt = HumanMessagePromptTemplate::new(PromptTemplate::new( - items.first().unwrap().prompt.clone(), - vec![], - TemplateFormat::FString, - )); - let normal_chain = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .build() - .unwrap(); - return (Some(Box::new(normal_chain)), None); - } - - if items.len() > 1 { - // let mut chains: Vec = Vec::new(); - let mut seq_chain_builder = SequentialChainBuilder::new(); - let mut i = 0; - while i < items.len() { - let input = format!("input{}", i); - let output = format!("input{}", i + 1); - let prompt_str; - if i == 0 { - prompt_str = - "请根据以下要求,帮我生成对应的文案。 {{".to_owned() + &input + "}}"; - } else { - prompt_str = "请根据以下内容和额外要求,帮我生成对应的文案。内容: {{".to_owned() - + &input - + "}}, 额外要求: " - + &items.get(i).unwrap().prompt; - } - - let prompt = HumanMessagePromptTemplate::new(template_jinja2!(prompt_str, input)); - let c = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .output_key(output) - .build() - .unwrap(); - // chains.push(c); - seq_chain_builder = seq_chain_builder.add_chain(c); - i += 1; - } - - let seq_chain = seq_chain_builder.build(); - return ( - Some(Box::new(seq_chain)), - Some(items.first().unwrap().prompt.clone()), - ); - } - - (None, None) -} - -/// TODO: 暂时sql和文件问答不支持顺序链 -async fn items_to_chain_with_plugins( - items: &Vec<&TemplateItem>, - llm: OpenAI, -) -> (Option>, Option) { - if items.is_empty() { - return (None, None); - } - - if items.len() == 1 { - let mut extra_content = "".to_owned(); - let item = items.get(0).unwrap(); - // sql - - // file - if item.attr_type == AttributeType::File { - let file_content = get_file_content(item.extra.clone().unwrap_or("".to_owned())).await; - match file_content { - Ok(_f) => { - extra_content = _f; - } - Err(_e) => { - println!("[rust-error] file content is None"); - return (None, None); - } - } - } - - // 返回一般的LLMChain - let prompt = HumanMessagePromptTemplate::new(PromptTemplate::new( - items.first().unwrap().prompt.clone() + &extra_content, - vec![], - TemplateFormat::FString, - )); - let normal_chain = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .build() - .unwrap(); - return (Some(Box::new(normal_chain)), None); - } - - if items.len() > 1 { - // let mut chains: Vec = Vec::new(); - let mut seq_chain_builder = SequentialChainBuilder::new(); - let mut i = 0; - while i < items.len() { - let input = format!("input{}", i); - let output = format!("input{}", i + 1); - let prompt_str; - if i == 0 { - prompt_str = - "请根据以下要求,帮我生成对应的文案。 {{".to_owned() + &input + "}}"; - } else { - prompt_str = "请根据以下内容和额外要求,帮我生成对应的文案。内容: {{".to_owned() - + &input - + "}}, 额外要求: " - + &items.get(i).unwrap().prompt; - } - - let prompt = HumanMessagePromptTemplate::new(template_jinja2!(prompt_str, input)); - let c = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .output_key(output) - .build() - .unwrap(); - // chains.push(c); - seq_chain_builder = seq_chain_builder.add_chain(c); - i += 1; - } - - let seq_chain = seq_chain_builder.build(); - return ( - Some(Box::new(seq_chain)), - Some(items.first().unwrap().prompt.clone()), - ); - } - - (None, None) } -#[allow(unused_imports)] -mod tests { - use std::{ - any::{Any, TypeId}, - collections::HashMap, - }; - - use futures::StreamExt; - use langchain_rust::{ - chain::LLMChain, - llm::{OpenAI, OpenAIConfig}, - prompt_args, - }; - - use crate::llm::{app_flowy_model::AttributeType, template::items_to_chain}; - - use super::{AppFlowyTemplate, TemplateItem}; - - #[tokio::test] - async fn test_item_to_chain() { - let mut app_flowy_template = AppFlowyTemplate { - items: vec![ - TemplateItem { - prompt: "请帮我生成一份rust学习计划".to_string(), - index: 1, - next: Some(2), - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "请帮我分析学习计划中的难点".to_string(), - index: 2, - next: Some(3), - attr_type: AttributeType::Prompt, - extra: None, - }, - ], - }; - - let separated_vecs = app_flowy_template.into_multiple(); - - println!("length {:?}", separated_vecs.len()); - if separated_vecs.len() > 0 { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let llm = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - let s = items_to_chain(separated_vecs.first().unwrap(), llm); - - if let Some(c) = s.0 { - // if let Some(_nc) = c.downcast_ref::(){} - // let type_id = (*c).type_id(); - // if type_id == TypeId::of::() { - - // let out = - // } - if let Some(p) = s.1 { - let output = c - .execute(prompt_args! { - "input0" => p - }) - .await - .unwrap(); - - println!("{:?}", output); - - let mut index = 0; - let mut map: HashMap = HashMap::new(); - // map.insert("input0".to_owned(), p.clone()); - while index < separated_vecs.get(0).unwrap().len() { - let key = format!("input{}", index + 1); - let value = output.get(&key).unwrap(); - map.insert( - separated_vecs - .get(0) - .unwrap() - .get(index) - .unwrap() - .prompt - .clone(), - value.to_string(), - ); - index += 1; - } - - println!("map {:?}", map); - } - } - } - } - - #[tokio::test] - async fn test_item_to_chain_2() { - let mut app_flowy_template = AppFlowyTemplate { - items: vec![TemplateItem { - prompt: "请帮我生成一份rust学习计划".to_string(), - index: 1, - next: None, - attr_type: AttributeType::Prompt, - extra: None, - }], - }; - - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let llm = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - let separated_vecs = app_flowy_template.into_multiple(); - - println!("length {:?}", separated_vecs.len()); - - for i in separated_vecs { - println!("[rust] chain length {}", i.len()); - let s = items_to_chain(&i, llm.clone()); - if let Some(c) = s.0 { - if let Some(p) = s.1 { - let output = c - .execute(prompt_args! { - "input0" => p - }) - .await - .unwrap(); - - println!("{:?}", output); - } else { - let mut stream = c.stream(HashMap::new()).await.unwrap(); - - while let Some(result) = stream.next().await { - match result { - Ok(value) => value.to_stdout().unwrap(), - Err(e) => panic!("Error invoking LLMChain: {:?}", e), - } - } - } - } - } - } - - #[test] - fn test_flow() { - println!("app_flowy_template"); - let mut app_flowy_template = AppFlowyTemplate { - items: vec![ - TemplateItem { - prompt: "First".to_string(), - index: 1, - next: Some(2), - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "Second".to_string(), - index: 2, - next: Some(3), - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "Third".to_string(), - index: 3, - next: None, - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "4".to_string(), - index: 4, - next: Some(5), - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "5".to_string(), - index: 5, - next: None, - attr_type: AttributeType::Prompt, - extra: None, - }, - TemplateItem { - prompt: "6".to_string(), - index: 6, - next: None, - attr_type: AttributeType::Prompt, - extra: None, - }, - ], - }; - - println!("here we go"); - - let separated_vecs = app_flowy_template.into_multiple(); - - println!("length {:?}", separated_vecs.len()); - - // 打印结果 - for (i, vec) in separated_vecs.iter().enumerate() { - println!("Sequence {}: {:?}", i + 1, vec); - } - } -} +// /// TODO: 暂时sql和文件问答不支持顺序链 +// async fn items_to_chain_with_plugins( +// items: &Vec<&TemplateItem>, +// llm: OpenAI, +// ) -> (Option>, Option) { +// if items.is_empty() { +// return (None, None); +// } + +// if items.len() == 1 { +// let mut extra_content = "".to_owned(); +// let item = items.get(0).unwrap(); +// // sql + +// // file +// if item.attr_type == AttributeType::File { +// let file_content = get_file_content(item.extra.clone().unwrap_or("".to_owned())).await; +// match file_content { +// Ok(_f) => { +// extra_content = _f; +// } +// Err(_e) => { +// println!("[rust-error] file content is None"); +// return (None, None); +// } +// } +// } + +// // 返回一般的LLMChain +// let prompt = HumanMessagePromptTemplate::new(PromptTemplate::new( +// items.first().unwrap().prompt.clone() + &extra_content, +// vec![], +// TemplateFormat::FString, +// )); +// let normal_chain = LLMChainBuilder::new() +// .prompt(prompt) +// .llm(llm.clone()) +// .build() +// .unwrap(); +// return (Some(Box::new(normal_chain)), None); +// } + +// if items.len() > 1 { +// // let mut chains: Vec = Vec::new(); +// let mut seq_chain_builder = SequentialChainBuilder::new(); +// let mut i = 0; +// while i < items.len() { +// let input = format!("input{}", i); +// let output = format!("input{}", i + 1); +// let prompt_str; +// if i == 0 { +// prompt_str = +// "请根据以下要求,帮我生成对应的文案。 {{".to_owned() + &input + "}}"; +// } else { +// prompt_str = "请根据以下内容和额外要求,帮我生成对应的文案。内容: {{".to_owned() +// + &input +// + "}}, 额外要求: " +// + &items.get(i).unwrap().prompt; +// } + +// let prompt = HumanMessagePromptTemplate::new(template_jinja2!(prompt_str, input)); +// let c = LLMChainBuilder::new() +// .prompt(prompt) +// .llm(llm.clone()) +// .output_key(output) +// .build() +// .unwrap(); +// // chains.push(c); +// seq_chain_builder = seq_chain_builder.add_chain(c); +// i += 1; +// } + +// let seq_chain = seq_chain_builder.build(); +// return ( +// Some(Box::new(seq_chain)), +// Some(items.first().unwrap().prompt.clone()), +// ); +// } + +// (None, None) +// } diff --git a/rust/src/llm/tests.rs b/rust/src/llm/tests.rs deleted file mode 100644 index c03f99b..0000000 --- a/rust/src/llm/tests.rs +++ /dev/null @@ -1,263 +0,0 @@ -#[allow(unused_imports)] -mod tests { - use std::io::Write; - - use futures::StreamExt; - use langchain_rust::{ - chain::{builder::ConversationalChainBuilder, Chain, LLMChainBuilder}, - fmt_message, fmt_template, - language_models::llm::LLM, - llm::{OpenAI, OpenAIConfig}, - memory::SimpleMemory, - message_formatter, - prompt::HumanMessagePromptTemplate, - prompt_args, - schemas::Message, - sequential_chain, template_fstring, template_jinja2, - }; - - use crate::llm::{models::ChainIOes, sequential_chain_builder::CustomSequentialChain}; - - #[test] - fn uuid_test() { - let u = uuid::Uuid::new_v4().to_string(); - println!("uuid : {:?}", u); - } - - #[tokio::test] - async fn test() { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let open_ai = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - let response = open_ai.invoke("how can langsmith help with testing?").await; - println!("{:?}", response); - } - - #[tokio::test] - async fn test_stream() { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - let binding = "".to_string(); - println!("name {:?}", name); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let open_ai = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - let mut stream = open_ai - .stream(&[ - Message::new_human_message("你是一个私有化AI助理。"), - Message::new_human_message("请问如何使用rust实现链表。"), - ]) - .await - .unwrap(); - - while let Some(result) = stream.next().await { - match result { - Ok(value) => value.to_stdout().unwrap(), - Err(e) => panic!("Error invoking LLMChain: {:?}", e), - } - } - } - - #[tokio::test] - async fn test_chain() { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let open_ai = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - let memory = SimpleMemory::new(); - let chain = ConversationalChainBuilder::new() - .llm(open_ai) - //IF YOU WANT TO ADD A CUSTOM PROMPT YOU CAN UN COMMENT THIS: - // .prompt(message_formatter![ - // fmt_message!(Message::new_system_message("You are a helpful assistant")), - // fmt_template!(HumanMessagePromptTemplate::new( - // template_fstring!(" - // The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. - // - // Current conversation: - // {history} - // Human: {input} - // AI: - // ", - // "input","history"))) - // - // ]) - .memory(memory.into()) - .build() - .expect("Error building ConversationalChain"); - - let input_variables = prompt_args! { - "input" => "我来自江苏常州。", - }; - - let mut stream = chain.stream(input_variables).await.unwrap(); - while let Some(result) = stream.next().await { - match result { - Ok(data) => { - //If you junt want to print to stdout, you can use data.to_stdout().unwrap(); - print!("{}", data.content); - std::io::stdout().flush().unwrap(); - } - Err(e) => { - println!("Error: {:?}", e); - } - } - } - - let input_variables = prompt_args! { - "input" => "常州有什么特产或者好玩的地方?", - }; - match chain.invoke(input_variables).await { - Ok(result) => { - println!("\n"); - println!("Result: {:?}", result); - } - Err(e) => panic!("Error invoking LLMChain: {:?}", e), - } - } - - #[tokio::test] - async fn sequential_chain_test() { - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let llm = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - let prompt = HumanMessagePromptTemplate::new(template_jinja2!( - "给我一个卖东西的商店起个有创意的名字: {{producto}}", - "producto" - )); - - let get_name_chain = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .output_key("name") - .build() - .unwrap(); - - let prompt = HumanMessagePromptTemplate::new(template_jinja2!( - "给我一个响亮的口号: {{name}}", - "name" - )); - let get_slogan_chain = LLMChainBuilder::new() - .prompt(prompt) - .llm(llm.clone()) - .output_key("slogan") - .build() - .unwrap(); - - let sequential_chain = sequential_chain!(get_name_chain, get_slogan_chain); - - print!("Please enter a product: "); - std::io::stdout().flush().unwrap(); // Display prompt to terminal - - let mut product = String::new(); - std::io::stdin().read_line(&mut product).unwrap(); // Get product from terminal input - - let product = product.trim(); - let output = sequential_chain - .execute(prompt_args! { - "producto" => product - }) - .await - .unwrap(); - - println!("Name: {}", output["name"]); - println!("Slogan: {}", output["slogan"]); - } - - #[tokio::test] - async fn json_test() -> anyhow::Result<()> { - let json_data = r#" - { - "items":[ - { - "input_key":"producto", - "output_key":"name", - "prompt":"给我一个卖东西的商店起个有创意的名字: {{placeholder}}" - }, - { - "input_key":"name", - "output_key":"slogan", - "prompt":"给我一个下一个名字的口号: {{placeholder}}" - } - ] - } - "#; - - let map = crate::llm::env_parse("env".to_owned()).unwrap(); - - let base = map.get("LLM_BASE").unwrap(); - println!("base {:?}", base); - let name = map.get("LLM_MODEL_NAME").unwrap(); - println!("name {:?}", name); - let binding = "".to_string(); - let sk = map.get("LLM_SK").unwrap_or(&binding); - println!("sk {:?}", sk); - - let llm = OpenAI::default() - .with_config(OpenAIConfig::new().with_api_base(base).with_api_key(sk)) - .with_model(name); - - let items: ChainIOes = serde_json::from_str(json_data)?; - let seq = CustomSequentialChain { - chains: items.items, - }; - - let seq_chain = seq.build(llm); - - match seq_chain { - Some(_seq) => { - let output = _seq - .execute(prompt_args! { - "producto" => "shoe" - }) - .await - .unwrap(); - println!("Name: {}", output["name"]); - println!("Slogan: {}", output["slogan"]); - } - None => { - println!("none"); - } - } - - anyhow::Ok(()) - } -} From b12f30bf0ad5078ca199cdba2f3a6cf73a872689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A3=B9=E9=9B=B6?= Date: Mon, 27 May 2024 17:54:45 +0800 Subject: [PATCH 08/16] update model --- langchain_lib/lib/models/appflowy_model.dart | 74 +++++++++++++ .../lib/models/appflowy_model.g.dart | 78 ++++++++++++++ langchain_lib/pubspec.yaml | 4 + lib/llm/editor/compose_screen.dart | 30 +++++- .../components/load_template_dialog.dart | 102 ++++++++++++++++++ lib/llm/global/components/template_item.dart | 90 ++++++++++++++++ .../notifiers/template_select_notifier.dart | 21 ++++ .../components/chain_flow.dart | 2 +- .../chain_flow_state.dart | 58 +++++++++- .../models/editor_template.dart | 52 +++++++++ .../notifiers/chain_flow_notifier.dart | 2 +- .../notifiers/template_notifier.dart | 12 ++- lib/llm/template_editor/template_editor.dart | 62 ++++++++--- 13 files changed, 565 insertions(+), 22 deletions(-) create mode 100644 langchain_lib/lib/models/appflowy_model.dart create mode 100644 langchain_lib/lib/models/appflowy_model.g.dart create mode 100644 lib/llm/global/components/load_template_dialog.dart create mode 100644 lib/llm/global/components/template_item.dart create mode 100644 lib/llm/global/notifiers/template_select_notifier.dart rename lib/llm/template_editor/{notifiers => models}/chain_flow_state.dart (58%) create mode 100644 lib/llm/template_editor/models/editor_template.dart diff --git a/langchain_lib/lib/models/appflowy_model.dart b/langchain_lib/lib/models/appflowy_model.dart new file mode 100644 index 0000000..54532be --- /dev/null +++ b/langchain_lib/lib/models/appflowy_model.dart @@ -0,0 +1,74 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'appflowy_model.g.dart'; + +@JsonSerializable() +class Root { + final Document document; + + Root({required this.document}); + + factory Root.fromJson(Map json) => _$RootFromJson(json); + Map toJson() => _$RootToJson(this); +} + +@JsonSerializable() +class Document { + final String typeField; + final List children; + + Document({required this.typeField, required this.children}); + + factory Document.fromJson(Map json) => + _$DocumentFromJson(json); + Map toJson() => _$DocumentToJson(this); +} + +@JsonSerializable() +class Children { + final String typeField; + final Data data; + + Children({required this.typeField, required this.data}); + + factory Children.fromJson(Map json) => + _$ChildrenFromJson(json); + Map toJson() => _$ChildrenToJson(this); +} + +@JsonSerializable() +class Data { + final int? level; + final List delta; + final String? align; + + Data({this.level, required this.delta, this.align}); + + factory Data.fromJson(Map json) => _$DataFromJson(json); + Map toJson() => _$DataToJson(this); +} + +@JsonSerializable() +class Delum { + final String insert; + final Attributes? attributes; + + Delum({required this.insert, this.attributes}); + + factory Delum.fromJson(Map json) => _$DelumFromJson(json); + Map toJson() => _$DelumToJson(this); +} + +@JsonSerializable() +class Attributes { + final bool? bold; + final bool? italic; + final String? file; + final String? sql; + + Attributes({this.bold, this.italic, this.file, this.sql}); + + factory Attributes.fromJson(Map json) => + _$AttributesFromJson(json); + Map toJson() => _$AttributesToJson(this); +} diff --git a/langchain_lib/lib/models/appflowy_model.g.dart b/langchain_lib/lib/models/appflowy_model.g.dart new file mode 100644 index 0000000..e27a141 --- /dev/null +++ b/langchain_lib/lib/models/appflowy_model.g.dart @@ -0,0 +1,78 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'appflowy_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Root _$RootFromJson(Map json) => Root( + document: Document.fromJson(json['document'] as Map), + ); + +Map _$RootToJson(Root instance) => { + 'document': instance.document, + }; + +Document _$DocumentFromJson(Map json) => Document( + typeField: json['typeField'] as String, + children: (json['children'] as List) + .map((e) => Children.fromJson(e as Map)) + .toList(), + ); + +Map _$DocumentToJson(Document instance) => { + 'typeField': instance.typeField, + 'children': instance.children, + }; + +Children _$ChildrenFromJson(Map json) => Children( + typeField: json['typeField'] as String, + data: Data.fromJson(json['data'] as Map), + ); + +Map _$ChildrenToJson(Children instance) => { + 'typeField': instance.typeField, + 'data': instance.data, + }; + +Data _$DataFromJson(Map json) => Data( + level: (json['level'] as num?)?.toInt(), + delta: (json['delta'] as List) + .map((e) => Delum.fromJson(e as Map)) + .toList(), + align: json['align'] as String?, + ); + +Map _$DataToJson(Data instance) => { + 'level': instance.level, + 'delta': instance.delta, + 'align': instance.align, + }; + +Delum _$DelumFromJson(Map json) => Delum( + insert: json['insert'] as String, + attributes: json['attributes'] == null + ? null + : Attributes.fromJson(json['attributes'] as Map), + ); + +Map _$DelumToJson(Delum instance) => { + 'insert': instance.insert, + 'attributes': instance.attributes, + }; + +Attributes _$AttributesFromJson(Map json) => Attributes( + bold: json['bold'] as bool?, + italic: json['italic'] as bool?, + file: json['file'] as String?, + sql: json['sql'] as String?, + ); + +Map _$AttributesToJson(Attributes instance) => + { + 'bold': instance.bold, + 'italic': instance.italic, + 'file': instance.file, + 'sql': instance.sql, + }; diff --git a/langchain_lib/pubspec.yaml b/langchain_lib/pubspec.yaml index 0d90d2b..98a05c1 100644 --- a/langchain_lib/pubspec.yaml +++ b/langchain_lib/pubspec.yaml @@ -10,13 +10,17 @@ environment: dependencies: flutter: sdk: flutter + json_annotation: ^4.9.0 langchain: ^0.7.1 langchain_openai: ^0.6.1+1 + dev_dependencies: + build_runner: ^2.4.10 flutter_test: sdk: flutter flutter_lints: ^3.0.0 + json_serializable: ^6.8.0 flutter: diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index b197aa5..d10d42f 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -3,8 +3,10 @@ import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; import 'package:all_in_one/isar/llm_history.dart'; +import 'package:all_in_one/isar/llm_template.dart'; import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; +import 'package:all_in_one/llm/global/components/load_template_dialog.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; @@ -97,7 +99,33 @@ class _ComposeScreenState extends ConsumerState { SidemenuButton( icon: EvaIcons.file_text, title: "Load Template", - onTap: () {}, + onTap: () async { + final LlmTemplate? template = await showGeneralDialog( + barrierColor: Colors.transparent, + barrierDismissible: true, + barrierLabel: "load-template", + context: context, + pageBuilder: (c, _, __) { + return const Center( + child: LoadTemplateDialog(), + ); + }); + + if (template != null) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, + content: template.template), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + }); + } + }, ), if (isTemplateLoaded) SidemenuButton( diff --git a/lib/llm/global/components/load_template_dialog.dart b/lib/llm/global/components/load_template_dialog.dart new file mode 100644 index 0000000..fa470b9 --- /dev/null +++ b/lib/llm/global/components/load_template_dialog.dart @@ -0,0 +1,102 @@ +import 'package:all_in_one/llm/global/components/template_item.dart'; +import 'package:all_in_one/llm/global/notifiers/template_select_notifier.dart'; +import 'package:all_in_one/llm/template_editor/notifiers/template_notifier.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +class LoadTemplateDialog extends ConsumerStatefulWidget { + const LoadTemplateDialog({super.key}); + + @override + ConsumerState createState() => _LoadTemplateDialogState(); +} + +class _LoadTemplateDialogState extends ConsumerState { + @override + Widget build(BuildContext context) { + final state = ref.watch(templateNotifierProvider); + + return Material( + elevation: 10, + borderRadius: BorderRadius.circular(20), + child: Container( + padding: const EdgeInsets.all(20), + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)), + child: state.when( + data: (v) { + if (v.isEmpty) { + return const Center( + child: Text("There is no template created."), + ); + } + + return Column( + children: [ + const SizedBox( + height: 50, + child: Row( + children: [ + SizedBox( + width: 50, + ), + Expanded( + flex: 1, + child: Text("name"), + ), + Expanded( + flex: 2, + child: Text("content"), + ) + ], + ), + ), + Expanded( + child: ListView.builder( + itemBuilder: (c, i) { + return TemplateItem( + template: v[i], + onTemplateSelected: (index) { + // print(index); + ref + .read(templateSelectProvider.notifier) + .changeState(index); + }); + }, + itemCount: v.length, + )), + SizedBox( + height: 50, + child: Row( + children: [ + const Expanded(child: SizedBox()), + ElevatedButton( + onPressed: () { + if (ref.read(templateSelectProvider) == -1) { + return; + } + Navigator.of(context).pop(v + .where((i) => + i.id == ref.read(templateSelectProvider)) + .first); + }, + child: const Text("Apply")) + ], + ), + ) + ], + ); + }, + error: (_, s) { + return Center( + child: Text(s.toString()), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(), + )), + ), + ); + } +} diff --git a/lib/llm/global/components/template_item.dart b/lib/llm/global/components/template_item.dart new file mode 100644 index 0000000..15cb477 --- /dev/null +++ b/lib/llm/global/components/template_item.dart @@ -0,0 +1,90 @@ +import 'package:all_in_one/isar/llm_template.dart'; +import 'package:all_in_one/llm/global/notifiers/template_select_notifier.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +typedef OnTemplateSelected = void Function(int); + +class TemplateItem extends ConsumerStatefulWidget { + const TemplateItem( + {super.key, required this.template, required this.onTemplateSelected}); + final LlmTemplate template; + final OnTemplateSelected onTemplateSelected; + + @override + ConsumerState createState() => _TemplateItemState(); +} + +class _TemplateItemState extends ConsumerState { + bool isHovering = false; + + @override + Widget build(BuildContext context) { + // print(ref.watch(templateSelectProvider)); + final state = ref.watch(templateSelectProvider); + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (event) { + setState(() { + isHovering = true; + }); + }, + onExit: (event) { + setState(() { + isHovering = false; + }); + }, + child: GestureDetector( + onTap: () { + widget.onTemplateSelected(widget.template.id); + }, + child: Container( + height: 40, + decoration: BoxDecoration( + color: isHovering + ? const Color.fromARGB(255, 197, 195, 227).withAlpha(100) + : Colors.transparent, + borderRadius: BorderRadius.circular(5)), + child: Row( + children: [ + SizedBox( + width: 50, + child: Center( + child: Icon( + Icons.check_box, + color: state == widget.template.id + ? Colors.blue + : Colors.grey, + ), + )), + Expanded( + flex: 1, + child: Text( + widget.template.name, + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: state == widget.template.id + ? Colors.blue + : Colors.grey), + ), + ), + Expanded( + flex: 2, + child: Text(widget.template.template, + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: state == widget.template.id + ? Colors.blue + : Colors.grey)), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/llm/global/notifiers/template_select_notifier.dart b/lib/llm/global/notifiers/template_select_notifier.dart new file mode 100644 index 0000000..156db22 --- /dev/null +++ b/lib/llm/global/notifiers/template_select_notifier.dart @@ -0,0 +1,21 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +class TemplateSelectNotifier extends AutoDisposeNotifier { + @override + int build() { + return -1; + } + + changeState(int i) { + if (state != i) { + state = i; + } else { + state = -1; + } + } +} + +final templateSelectProvider = + AutoDisposeNotifierProvider( + () => TemplateSelectNotifier(), +); diff --git a/lib/llm/template_editor/components/chain_flow.dart b/lib/llm/template_editor/components/chain_flow.dart index ffc6276..36a9eca 100644 --- a/lib/llm/template_editor/components/chain_flow.dart +++ b/lib/llm/template_editor/components/chain_flow.dart @@ -5,7 +5,7 @@ import 'dart:ui'; import 'package:all_in_one/llm/template_editor/components/connector_painter.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; -import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_state.dart'; +import 'package:all_in_one/llm/template_editor/models/chain_flow_state.dart'; import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; import 'package:all_in_one/styles/app_style.dart'; diff --git a/lib/llm/template_editor/notifiers/chain_flow_state.dart b/lib/llm/template_editor/models/chain_flow_state.dart similarity index 58% rename from lib/llm/template_editor/notifiers/chain_flow_state.dart rename to lib/llm/template_editor/models/chain_flow_state.dart index 5d0e47f..617a3fb 100644 --- a/lib/llm/template_editor/notifiers/chain_flow_state.dart +++ b/lib/llm/template_editor/models/chain_flow_state.dart @@ -1,6 +1,6 @@ import 'dart:ui'; -import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; +import 'package:langchain_lib/models/template_item.dart'; class ChainFlowState { final String content; @@ -14,6 +14,12 @@ class ChainFlowState { } } +extension Eval on ChainFlowItem { + Future> eval() async { + return {}; + } +} + extension Group on ChainFlowItem { List> getBounds() { if (connections.isEmpty) { @@ -57,6 +63,28 @@ class ChainFlowItem { final Set flowItems; final List<(String, String)> connections; + Map toJson() => { + 'connections': connections.map((e) => {e.$1: e.$2}).toList(), + 'flowItems': flowItems.map((e) => e.toJson()).toList(), + }; + + factory ChainFlowItem.fromJson(Map json) { + late Set s = {}; + if (json['flowItems'] != null) { + json['flowItems'].forEach((v) { + s.add(FlowItem.fromJson(v)); + }); + } + late List<(String, String)> c = []; + if (json['connections'] != null) { + json['connections'].forEach((v) { + // s.add(FlowItem.fromJson(v)); + c.add((v.key, v.value)); + }); + } + return ChainFlowItem(flowItems: s, connections: c); + } + ChainFlowItem({this.connections = const [], this.flowItems = const {}}); } @@ -87,6 +115,34 @@ class FlowItem { return other.content == content && uuid == other.uuid; } + Map toJson() => { + 'content': content, + 'uuid': uuid, + 'type': type.toJson(), + 'extra': extra, + 'index': index, + }; + + factory FlowItem.fromJson(Map json) { + return FlowItem( + content: json['content'] ?? '', + uuid: json['uuid'] ?? '', + type: attrFromJson(json['type']), + extra: json['extra'], + index: json['index'] ?? 0, + ); + } + @override int get hashCode => content.hashCode ^ uuid.hashCode; } + +extension AttrExtension on AttributeType { + int toJson() { + return AttributeType.values.indexOf(this); + } +} + +AttributeType attrFromJson(int index) { + return AttributeType.values[index]; +} diff --git a/lib/llm/template_editor/models/editor_template.dart b/lib/llm/template_editor/models/editor_template.dart new file mode 100644 index 0000000..e2c8a57 --- /dev/null +++ b/lib/llm/template_editor/models/editor_template.dart @@ -0,0 +1,52 @@ +import 'package:langchain_lib/models/template_item.dart'; + +class EditorTemplate { + final List items; + EditorTemplate({required this.items}); + + List> intoMultiple() { + items.sort((a, b) => a.index.compareTo(b.index)); + var vecs = >[]; + var saved = []; + + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (saved.contains(item.index)) { + continue; + } + + var subVec = [item]; + i++; + + if (item.next == null) { + saved.add(item.index); + vecs.add(subVec); + } else { + bool foundNext = false; + for (var next in items) { + if (saved.contains(next.index)) { + continue; + } + + if (item.next == null || foundNext) { + // The condition seems to be incorrect in the original logic. + // Assuming the intention was to break after finding all 'next'. + saved.add(item.index); + // Removed redundant comment and logic. + break; + } + + if (next.index == item.next!) { + subVec.add(next); + saved.add(next.index); + item = next; + foundNext = true; + } + } + + vecs.add(subVec); + } + } + return vecs; + } +} diff --git a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart index 9d92aef..e266b6b 100644 --- a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart +++ b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart @@ -1,7 +1,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:langchain_lib/models/template_item.dart'; -import 'chain_flow_state.dart'; +import '../models/chain_flow_state.dart'; class ChainFlowNotifier extends Notifier { @override diff --git a/lib/llm/template_editor/notifiers/template_notifier.dart b/lib/llm/template_editor/notifiers/template_notifier.dart index 8d077a6..2d6949f 100644 --- a/lib/llm/template_editor/notifiers/template_notifier.dart +++ b/lib/llm/template_editor/notifiers/template_notifier.dart @@ -12,16 +12,22 @@ class TemplateNotifier extends AutoDisposeAsyncNotifier> { return templates; } - Future addTemplate(LlmTemplate template) async { + Future addTemplate(LlmTemplate template, {int id = 0}) async { state = const AsyncLoading(); + if (id != 0) { + template.id = id; + } + state = await AsyncValue.guard(() async { await isarDatabase.isar!.writeTxn(() async { await isarDatabase.isar!.llmTemplates.put(template); }); - final l = state.value!..add(template); + final l = List.from(state.value!)..add(template); return l; }); + + return template.id; } removeTemplate(LlmTemplate template) async { @@ -30,7 +36,7 @@ class TemplateNotifier extends AutoDisposeAsyncNotifier> { await isarDatabase.isar!.writeTxn(() async { await isarDatabase.isar!.llmTemplates.delete(template.id); }); - final l = state.value!..remove(template); + final l = List.from(state.value!)..remove(template); return l; }); } diff --git a/lib/llm/template_editor/template_editor.dart b/lib/llm/template_editor/template_editor.dart index cece195..0d8a1ff 100644 --- a/lib/llm/template_editor/template_editor.dart +++ b/lib/llm/template_editor/template_editor.dart @@ -2,6 +2,7 @@ import 'dart:convert'; +import 'package:all_in_one/common/toast_utils.dart'; import 'package:all_in_one/isar/llm_template.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; @@ -39,6 +40,8 @@ class _TemplateEditorState extends ConsumerState { late EditorState _editorState; late String _jsonString; late WidgetBuilder _widgetBuilder; + late int currentTemplateId = 0; + late String currentTemplateName = ""; // final stream = templateMessageStream(); @@ -289,24 +292,53 @@ class _TemplateEditorState extends ConsumerState { icon: EvaIcons.save, title: "Save Template", onTap: () async { - final String? r = await showGeneralDialog( - context: context, - barrierDismissible: true, - barrierColor: Colors.transparent, - barrierLabel: "new-template", - pageBuilder: (c, _, __) { - return const Center( - child: NewTemplateDialog(), - ); - }); + // print(jsonEncode(ref.read(chainFlowProvider).items.toJson())); + final itemStr = + jsonEncode(ref.read(chainFlowProvider).items.toJson()); - if (r != null) { + if (currentTemplateId != 0) { ref .read(templateNotifierProvider.notifier) - .addTemplate(LlmTemplate() - ..template = - jsonEncode(_editorState.document.toJson()) - ..name = r); + .addTemplate( + LlmTemplate() + ..chains = itemStr + ..template = + jsonEncode(_editorState.document.toJson()) + ..name = currentTemplateName, + id: currentTemplateId) + .then((v) { + currentTemplateId = v; + currentTemplateName = currentTemplateName; + ToastUtils.sucess(context, title: "Template created!"); + }); + } else { + final String? r = await showGeneralDialog( + context: context, + barrierDismissible: true, + barrierColor: Colors.transparent, + barrierLabel: "new-template", + pageBuilder: (c, _, __) { + return const Center( + child: NewTemplateDialog(), + ); + }); + + if (r != null) { + ref + .read(templateNotifierProvider.notifier) + .addTemplate( + LlmTemplate() + ..chains = itemStr + ..template = + jsonEncode(_editorState.document.toJson()) + ..name = r, + id: currentTemplateId) + .then((v) { + currentTemplateId = v; + currentTemplateName = r; + ToastUtils.sucess(context, title: "Template created!"); + }); + } } }, ), From b88e0939d4263ddf665b44b6987c550207cd0731 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Mon, 27 May 2024 20:48:06 +0800 Subject: [PATCH 09/16] refactor: remove all langchain-rs codes --- langchain_lib/lib/models/appflowy_model.dart | 8 +- .../lib/models/appflowy_model.g.dart | 8 +- langchain_lib/lib/models/template_item.dart | 40 ++++ .../components/chain_flow.dart | 16 +- lib/src/rust/api/llm_plugin_api.dart | 6 - lib/src/rust/frb_generated.dart | 152 ++------------ lib/src/rust/frb_generated.io.dart | 36 ---- lib/src/rust/frb_generated.web.dart | 36 ---- rust/src/api/llm_plugin_api.rs | 11 - rust/src/frb_generated.rs | 194 ++---------------- rust/src/lib.rs | 1 + rust/src/llm/app_flowy_model.rs | 117 ----------- rust/src/llm/mod.rs | 59 ------ rust/src/llm/plugins/chat_file.rs | 69 +++---- rust/src/llm/plugins/mod.rs | 8 + rust/src/llm/template.rs | 175 ---------------- 16 files changed, 127 insertions(+), 809 deletions(-) delete mode 100644 rust/src/llm/app_flowy_model.rs delete mode 100644 rust/src/llm/template.rs diff --git a/langchain_lib/lib/models/appflowy_model.dart b/langchain_lib/lib/models/appflowy_model.dart index 54532be..58461be 100644 --- a/langchain_lib/lib/models/appflowy_model.dart +++ b/langchain_lib/lib/models/appflowy_model.dart @@ -14,10 +14,10 @@ class Root { @JsonSerializable() class Document { - final String typeField; + final String type; final List children; - Document({required this.typeField, required this.children}); + Document({required this.type, required this.children}); factory Document.fromJson(Map json) => _$DocumentFromJson(json); @@ -26,10 +26,10 @@ class Document { @JsonSerializable() class Children { - final String typeField; + final String type; final Data data; - Children({required this.typeField, required this.data}); + Children({required this.type, required this.data}); factory Children.fromJson(Map json) => _$ChildrenFromJson(json); diff --git a/langchain_lib/lib/models/appflowy_model.g.dart b/langchain_lib/lib/models/appflowy_model.g.dart index e27a141..7318dd0 100644 --- a/langchain_lib/lib/models/appflowy_model.g.dart +++ b/langchain_lib/lib/models/appflowy_model.g.dart @@ -15,24 +15,24 @@ Map _$RootToJson(Root instance) => { }; Document _$DocumentFromJson(Map json) => Document( - typeField: json['typeField'] as String, + type: json['type'] as String, children: (json['children'] as List) .map((e) => Children.fromJson(e as Map)) .toList(), ); Map _$DocumentToJson(Document instance) => { - 'typeField': instance.typeField, + 'type': instance.type, 'children': instance.children, }; Children _$ChildrenFromJson(Map json) => Children( - typeField: json['typeField'] as String, + type: json['type'] as String, data: Data.fromJson(json['data'] as Map), ); Map _$ChildrenToJson(Children instance) => { - 'typeField': instance.typeField, + 'type': instance.type, 'data': instance.data, }; diff --git a/langchain_lib/lib/models/template_item.dart b/langchain_lib/lib/models/template_item.dart index 748e9be..230b34b 100644 --- a/langchain_lib/lib/models/template_item.dart +++ b/langchain_lib/lib/models/template_item.dart @@ -1,3 +1,7 @@ +import 'dart:convert'; + +import 'package:langchain_lib/models/appflowy_model.dart'; + class TemplateItem { final String prompt; final int index; @@ -19,3 +23,39 @@ enum AttributeType { File, Sql, } + +List<(String, AttributeType, String?)>? getAllCandidates(String s) { + final v = <(String, AttributeType, String?)>[]; + final doc = Root.fromJson(jsonDecode(s)); + final re = RegExp(r'\{\{(.*?)\}\}'); + final children = doc.document.children; + + for (final i in children) { + if (i.data.delta.isNotEmpty) { + for (final d in i.data.delta) { + for (final match in re.allMatches(d.insert)) { + print('Matched text: ${match.group(0)}'); + v.add((match.group(0)!, AttributeType.Prompt, null)); + } + + // Since the structure of `d.attributes` isn't defined, assuming it's a Map + final Attributes? attributes = d.attributes; + + if (attributes != null && attributes.sql != null) { + v.add((d.insert, AttributeType.Sql, attributes.sql)); + } + + if (attributes != null && attributes.file != null) { + v.add((d.insert, AttributeType.File, attributes.file)); + } + } + } + } + + return v; +} + +List<(String, AttributeType, String?)> templateToPrompts( + {required String template}) { + return getAllCandidates(template) ?? []; +} diff --git a/lib/llm/template_editor/components/chain_flow.dart b/lib/llm/template_editor/components/chain_flow.dart index 36a9eca..c46ed9d 100644 --- a/lib/llm/template_editor/components/chain_flow.dart +++ b/lib/llm/template_editor/components/chain_flow.dart @@ -6,8 +6,8 @@ import 'dart:ui'; import 'package:all_in_one/llm/template_editor/components/connector_painter.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; import 'package:all_in_one/llm/template_editor/models/chain_flow_state.dart'; -import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; -import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; +// import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; +// import 'package:all_in_one/src/rust/llm/app_flowy_model.dart'; import 'package:all_in_one/styles/app_style.dart'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:collection/collection.dart'; @@ -15,6 +15,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_flow_chart/flutter_flow_chart.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_tags_x/flutter_tags_x.dart'; +import 'package:langchain_lib/models/template_item.dart'; // import 'package:langchain_lib/models/template_item.dart'; class ChainFlow extends ConsumerStatefulWidget { @@ -33,8 +34,7 @@ class _ChainFlowState extends ConsumerState { List<(String, AttributeType, String?)> items = []; init() async { - items = - await templateToPrompts(template: ref.read(chainFlowProvider).content); + items = templateToPrompts(template: ref.read(chainFlowProvider).content); childrenHeight = items.length * 50; } @@ -210,11 +210,11 @@ class _ChainFlowDesignerState extends ConsumerState { /* extra, sql,path */ String? )> items = []; - init() async { + init() { final flowItems = ref.read(chainFlowProvider).items.flowItems; final extractedItems = - await templateToPrompts(template: ref.read(chainFlowProvider).content); + templateToPrompts(template: ref.read(chainFlowProvider).content); // print("extractedItems.length ${extractedItems.length}"); for (int i = 0; i < extractedItems.length; i++) { final element = FlowElement( @@ -278,7 +278,9 @@ class _ChainFlowDesignerState extends ConsumerState { @override void initState() { super.initState(); - init(); + Future( + () => init(), + ); } @override diff --git a/lib/src/rust/api/llm_plugin_api.dart b/lib/src/rust/api/llm_plugin_api.dart index 11c4f39..0d4e5fe 100644 --- a/lib/src/rust/api/llm_plugin_api.dart +++ b/lib/src/rust/api/llm_plugin_api.dart @@ -4,7 +4,6 @@ // ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import import '../frb_generated.dart'; -import '../llm/app_flowy_model.dart'; import '../llm/plugins/chat_db.dart'; import '../llm/plugins/chat_db/mysql.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; @@ -21,8 +20,3 @@ Future?> eval( dynamic hint}) => RustLib.instance.api.crateApiLlmPluginApiEval( sqlStr: sqlStr, db: db, keys: keys, hint: hint); - -Future> templateToPrompts( - {required String template, dynamic hint}) => - RustLib.instance.api - .crateApiLlmPluginApiTemplateToPrompts(template: template, hint: hint); diff --git a/lib/src/rust/frb_generated.dart b/lib/src/rust/frb_generated.dart index de6dd5e..0a954d4 100644 --- a/lib/src/rust/frb_generated.dart +++ b/lib/src/rust/frb_generated.dart @@ -13,7 +13,6 @@ import 'dart:async'; import 'dart:convert'; import 'errors.dart'; import 'frb_generated.io.dart' if (dart.library.html) 'frb_generated.web.dart'; -import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; @@ -67,7 +66,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.0.0-dev.35'; @override - int get rustContentHash => -576783616; + int get rustContentHash => 1321894874; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -87,10 +86,6 @@ abstract class RustLibApi extends BaseApi { Future>> crateApiLlmPluginApiGetMysqlTableInfo( {required DatabaseInfo s, dynamic hint}); - Future> - crateApiLlmPluginApiTemplateToPrompts( - {required String template, dynamic hint}); - Future> crateApiProcessPortMapperApiGetProcessPortMappers({dynamic hint}); @@ -205,35 +200,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["s"], ); - @override - Future> - crateApiLlmPluginApiTemplateToPrompts( - {required String template, dynamic hint}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(template, serializer); - pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 3, port: port_); - }, - codec: SseCodec( - decodeSuccessData: - sse_decode_list_record_string_attribute_type_opt_string, - decodeErrorData: null, - ), - constMeta: kCrateApiLlmPluginApiTemplateToPromptsConstMeta, - argValues: [template], - apiImpl: this, - hint: hint, - )); - } - - TaskConstMeta get kCrateApiLlmPluginApiTemplateToPromptsConstMeta => - const TaskConstMeta( - debugName: "template_to_prompts", - argNames: ["template"], - ); - @override Future> crateApiProcessPortMapperApiGetProcessPortMappers({dynamic hint}) { @@ -241,7 +207,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 4, port: port_); + funcId: 3, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_process_port_mapper, @@ -267,7 +233,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(name, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 5)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -291,7 +257,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 6, port: port_); + funcId: 5, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -316,7 +282,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_rust_error_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 7)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 6)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -345,7 +311,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_64(id, serializer); sse_encode_String(name, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 12, port: port_); + funcId: 11, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -371,7 +337,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 9, port: port_); + funcId: 8, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_software, @@ -398,7 +364,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_list_record_i_64_string(items, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 8, port: port_); + funcId: 7, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -425,7 +391,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_i_64(id, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 13, port: port_); + funcId: 12, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -453,7 +419,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_list_prim_i_64_strict_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 10)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 9)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -485,7 +451,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_record_list_prim_i_64_strict_string_Sse( s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 11)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 10)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -513,7 +479,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 14, port: port_); + funcId: 13, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -541,7 +507,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( data, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 15, port: port_); + funcId: 14, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -566,7 +532,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 17, port: port_); + funcId: 16, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -593,7 +559,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_monitor_info_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 16)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 15)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -685,12 +651,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw as String; } - @protected - AttributeType dco_decode_attribute_type(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return AttributeType.values[raw as int]; - } - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -819,15 +779,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_record_i_64_string).toList(); } - @protected - List<(String, AttributeType, String?)> - dco_decode_list_record_string_attribute_type_opt_string(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List) - .map(dco_decode_record_string_attribute_type_opt_string) - .toList(); - } - @protected List<(String, CellType)> dco_decode_list_record_string_cell_type( dynamic raw) { @@ -998,21 +949,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - (String, AttributeType, String?) - dco_decode_record_string_attribute_type_opt_string(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) { - throw Exception('Expected 3 elements, got ${arr.length}'); - } - return ( - dco_decode_String(arr[0]), - dco_decode_attribute_type(arr[1]), - dco_decode_opt_String(arr[2]), - ); - } - @protected (String, CellType) dco_decode_record_string_cell_type(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1202,13 +1138,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return utf8.decoder.convert(inner); } - @protected - AttributeType sse_decode_attribute_type(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var inner = sse_decode_i_32(deserializer); - return AttributeType.values[inner]; - } - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -1373,21 +1302,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List<(String, AttributeType, String?)> - sse_decode_list_record_string_attribute_type_opt_string( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = <(String, AttributeType, String?)>[]; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add( - sse_decode_record_string_attribute_type_opt_string(deserializer)); - } - return ans_; - } - @protected List<(String, CellType)> sse_decode_list_record_string_cell_type( SseDeserializer deserializer) { @@ -1628,17 +1542,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (var_field0, var_field1); } - @protected - (String, AttributeType, String?) - sse_decode_record_string_attribute_type_opt_string( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_field0 = sse_decode_String(deserializer); - var var_field1 = sse_decode_attribute_type(deserializer); - var var_field2 = sse_decode_opt_String(deserializer); - return (var_field0, var_field1, var_field2); - } - @protected (String, CellType) sse_decode_record_string_cell_type( SseDeserializer deserializer) { @@ -1829,12 +1732,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_list_prim_u_8_strict(utf8.encoder.convert(self), serializer); } - @protected - void sse_encode_attribute_type(AttributeType self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.index, serializer); - } - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -1977,16 +1874,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_record_string_attribute_type_opt_string( - List<(String, AttributeType, String?)> self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_record_string_attribute_type_opt_string(item, serializer); - } - } - @protected void sse_encode_list_record_string_cell_type( List<(String, CellType)> self, SseSerializer serializer) { @@ -2186,15 +2073,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.$2, serializer); } - @protected - void sse_encode_record_string_attribute_type_opt_string( - (String, AttributeType, String?) self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.$1, serializer); - sse_encode_attribute_type(self.$2, serializer); - sse_encode_opt_String(self.$3, serializer); - } - @protected void sse_encode_record_string_cell_type( (String, CellType) self, SseSerializer serializer) { diff --git a/lib/src/rust/frb_generated.io.dart b/lib/src/rust/frb_generated.io.dart index 952a952..8691c44 100644 --- a/lib/src/rust/frb_generated.io.dart +++ b/lib/src/rust/frb_generated.io.dart @@ -14,7 +14,6 @@ import 'dart:convert'; import 'dart:ffi' as ffi; import 'errors.dart'; import 'frb_generated.dart'; -import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart'; @@ -68,9 +67,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String dco_decode_String(dynamic raw); - @protected - AttributeType dco_decode_attribute_type(dynamic raw); - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw); @@ -127,10 +123,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List<(int, String)> dco_decode_list_record_i_64_string(dynamic raw); - @protected - List<(String, AttributeType, String?)> - dco_decode_list_record_string_attribute_type_opt_string(dynamic raw); - @protected List<(String, CellType)> dco_decode_list_record_string_cell_type(dynamic raw); @@ -192,10 +184,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (Int64List, String) dco_decode_record_list_prim_i_64_strict_string( dynamic raw); - @protected - (String, AttributeType, String?) - dco_decode_record_string_attribute_type_opt_string(dynamic raw); - @protected (String, CellType) dco_decode_record_string_cell_type(dynamic raw); @@ -269,9 +257,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String sse_decode_String(SseDeserializer deserializer); - @protected - AttributeType sse_decode_attribute_type(SseDeserializer deserializer); - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer); @@ -332,11 +317,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List<(int, String)> sse_decode_list_record_i_64_string( SseDeserializer deserializer); - @protected - List<(String, AttributeType, String?)> - sse_decode_list_record_string_attribute_type_opt_string( - SseDeserializer deserializer); - @protected List<(String, CellType)> sse_decode_list_record_string_cell_type( SseDeserializer deserializer); @@ -407,11 +387,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (Int64List, String) sse_decode_record_list_prim_i_64_strict_string( SseDeserializer deserializer); - @protected - (String, AttributeType, String?) - sse_decode_record_string_attribute_type_opt_string( - SseDeserializer deserializer); - @protected (String, CellType) sse_decode_record_string_cell_type( SseDeserializer deserializer); @@ -490,9 +465,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_String(String self, SseSerializer serializer); - @protected - void sse_encode_attribute_type(AttributeType self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer); @@ -558,10 +530,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_record_i_64_string( List<(int, String)> self, SseSerializer serializer); - @protected - void sse_encode_list_record_string_attribute_type_opt_string( - List<(String, AttributeType, String?)> self, SseSerializer serializer); - @protected void sse_encode_list_record_string_cell_type( List<(String, CellType)> self, SseSerializer serializer); @@ -637,10 +605,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_record_list_prim_i_64_strict_string( (Int64List, String) self, SseSerializer serializer); - @protected - void sse_encode_record_string_attribute_type_opt_string( - (String, AttributeType, String?) self, SseSerializer serializer); - @protected void sse_encode_record_string_cell_type( (String, CellType) self, SseSerializer serializer); diff --git a/lib/src/rust/frb_generated.web.dart b/lib/src/rust/frb_generated.web.dart index 807af59..cbe09cd 100644 --- a/lib/src/rust/frb_generated.web.dart +++ b/lib/src/rust/frb_generated.web.dart @@ -13,7 +13,6 @@ import 'dart:async'; import 'dart:convert'; import 'errors.dart'; import 'frb_generated.dart'; -import 'llm/app_flowy_model.dart'; import 'llm/plugins/chat_db.dart'; import 'llm/plugins/chat_db/mysql.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart'; @@ -67,9 +66,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String dco_decode_String(dynamic raw); - @protected - AttributeType dco_decode_attribute_type(dynamic raw); - @protected CpuInfo dco_decode_box_autoadd_cpu_info(dynamic raw); @@ -126,10 +122,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List<(int, String)> dco_decode_list_record_i_64_string(dynamic raw); - @protected - List<(String, AttributeType, String?)> - dco_decode_list_record_string_attribute_type_opt_string(dynamic raw); - @protected List<(String, CellType)> dco_decode_list_record_string_cell_type(dynamic raw); @@ -191,10 +183,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (Int64List, String) dco_decode_record_list_prim_i_64_strict_string( dynamic raw); - @protected - (String, AttributeType, String?) - dco_decode_record_string_attribute_type_opt_string(dynamic raw); - @protected (String, CellType) dco_decode_record_string_cell_type(dynamic raw); @@ -268,9 +256,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String sse_decode_String(SseDeserializer deserializer); - @protected - AttributeType sse_decode_attribute_type(SseDeserializer deserializer); - @protected CpuInfo sse_decode_box_autoadd_cpu_info(SseDeserializer deserializer); @@ -331,11 +316,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { List<(int, String)> sse_decode_list_record_i_64_string( SseDeserializer deserializer); - @protected - List<(String, AttributeType, String?)> - sse_decode_list_record_string_attribute_type_opt_string( - SseDeserializer deserializer); - @protected List<(String, CellType)> sse_decode_list_record_string_cell_type( SseDeserializer deserializer); @@ -406,11 +386,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { (Int64List, String) sse_decode_record_list_prim_i_64_strict_string( SseDeserializer deserializer); - @protected - (String, AttributeType, String?) - sse_decode_record_string_attribute_type_opt_string( - SseDeserializer deserializer); - @protected (String, CellType) sse_decode_record_string_cell_type( SseDeserializer deserializer); @@ -489,9 +464,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_String(String self, SseSerializer serializer); - @protected - void sse_encode_attribute_type(AttributeType self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_cpu_info(CpuInfo self, SseSerializer serializer); @@ -557,10 +529,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_list_record_i_64_string( List<(int, String)> self, SseSerializer serializer); - @protected - void sse_encode_list_record_string_attribute_type_opt_string( - List<(String, AttributeType, String?)> self, SseSerializer serializer); - @protected void sse_encode_list_record_string_cell_type( List<(String, CellType)> self, SseSerializer serializer); @@ -636,10 +604,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_record_list_prim_i_64_strict_string( (Int64List, String) self, SseSerializer serializer); - @protected - void sse_encode_record_string_attribute_type_opt_string( - (String, AttributeType, String?) self, SseSerializer serializer); - @protected void sse_encode_record_string_cell_type( (String, CellType) self, SseSerializer serializer); diff --git a/rust/src/api/llm_plugin_api.rs b/rust/src/api/llm_plugin_api.rs index 4ae4187..f9d1174 100644 --- a/rust/src/api/llm_plugin_api.rs +++ b/rust/src/api/llm_plugin_api.rs @@ -1,4 +1,3 @@ -use crate::llm::app_flowy_model::AttributeType; use crate::llm::plugins::chat_db::mysql::CellType; use crate::llm::plugins::chat_db::DatabaseInfo; use crate::llm::plugins::chat_db::TableInfo; @@ -34,13 +33,3 @@ pub fn eval( } } } - -pub fn template_to_prompts(template: String) -> Vec<(String, AttributeType, Option)> { - let r = crate::llm::app_flowy_model::get_all_cadidates(template); - if let Ok(_r) = r { - return _r; - } else { - println!("template_to_prompts error {:?}", r.err()); - } - return vec![]; -} diff --git a/rust/src/frb_generated.rs b/rust/src/frb_generated.rs index 089e205..d681979 100644 --- a/rust/src/frb_generated.rs +++ b/rust/src/frb_generated.rs @@ -33,7 +33,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.0.0-dev.35"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -576783616; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1321894874; // Section: executor @@ -115,40 +115,6 @@ fn wire__crate__api__llm_plugin_api__get_mysql_table_info_impl( }, ) } -fn wire__crate__api__llm_plugin_api__template_to_prompts_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "template_to_prompts", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_template = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| { - transform_result_sse((move || { - Result::<_, ()>::Ok(crate::api::llm_plugin_api::template_to_prompts( - api_template, - )) - })()) - } - }, - ) -} fn wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -692,19 +658,6 @@ impl SseDecode for String { } } -impl SseDecode for crate::llm::app_flowy_model::AttributeType { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return match inner { - 0 => crate::llm::app_flowy_model::AttributeType::Prompt, - 1 => crate::llm::app_flowy_model::AttributeType::File, - 2 => crate::llm::app_flowy_model::AttributeType::Sql, - _ => unreachable!("Invalid variant for AttributeType: {}", inner), - }; - } -} - impl SseDecode for crate::llm::plugins::chat_db::mysql::CellType { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -885,28 +838,6 @@ impl SseDecode for Vec<(i64, String)> { } } -impl SseDecode - for Vec<( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - )> -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = vec![]; - for idx_ in 0..len_ { - ans_.push(<( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - )>::sse_decode(deserializer)); - } - return ans_; - } -} - impl SseDecode for Vec<(String, crate::llm::plugins::chat_db::mysql::CellType)> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1172,22 +1103,6 @@ impl SseDecode for (Vec, String) { } } -impl SseDecode - for ( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - ) -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_field0 = ::sse_decode(deserializer); - let mut var_field1 = ::sse_decode(deserializer); - let mut var_field2 = >::sse_decode(deserializer); - return (var_field0, var_field1, var_field2); - } -} - impl SseDecode for (String, crate::llm::plugins::chat_db::mysql::CellType) { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -1331,51 +1246,45 @@ fn pde_ffi_dispatcher_primary_impl( rust_vec_len, data_len, ), - 3 => wire__crate__api__llm_plugin_api__template_to_prompts_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 4 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( + 3 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( port, ptr, rust_vec_len, data_len, ), - 6 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), - 12 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( + 5 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), + 11 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 9 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( + 8 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( port, ptr, rust_vec_len, data_len, ), - 8 => wire__crate__api__software_monitor_api__init_monitor_impl( + 7 => wire__crate__api__software_monitor_api__init_monitor_impl( port, ptr, rust_vec_len, data_len, ), - 13 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( + 12 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 14 => wire__crate__api__sub_window_api__create_event_loop_impl( + 13 => wire__crate__api__sub_window_api__create_event_loop_impl( port, ptr, rust_vec_len, data_len, ), - 15 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), - 17 => wire__crate__api__system_monitor_api__start_system_monitor_impl( + 14 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), + 16 => wire__crate__api__system_monitor_api__start_system_monitor_impl( port, ptr, rust_vec_len, @@ -1393,11 +1302,11 @@ fn pde_ffi_dispatcher_sync_impl( ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 5 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), -7 => wire__crate__api__simple__rust_error_stream_impl(ptr, rust_vec_len, data_len), -10 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), -11 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), -16 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), + 4 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), +6 => wire__crate__api__simple__rust_error_stream_impl(ptr, rust_vec_len, data_len), +9 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), +10 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), +15 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -1424,27 +1333,6 @@ impl flutter_rust_bridge::IntoIntoDart flutter_rust_bridge::for_generated::DartAbi { - match self { - Self::Prompt => 0.into_dart(), - Self::File => 1.into_dart(), - Self::Sql => 2.into_dart(), - } - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::llm::app_flowy_model::AttributeType -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::llm::app_flowy_model::AttributeType -{ - fn into_into_dart(self) -> crate::llm::app_flowy_model::AttributeType { - self - } -} // Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::llm::plugins::chat_db::mysql::CellType { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { @@ -1817,23 +1705,6 @@ impl SseEncode for String { } } -impl SseEncode for crate::llm::app_flowy_model::AttributeType { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode( - match self { - crate::llm::app_flowy_model::AttributeType::Prompt => 0, - crate::llm::app_flowy_model::AttributeType::File => 1, - crate::llm::app_flowy_model::AttributeType::Sql => 2, - _ => { - unimplemented!(""); - } - }, - serializer, - ); - } -} - impl SseEncode for crate::llm::plugins::chat_db::mysql::CellType { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -1993,26 +1864,6 @@ impl SseEncode for Vec<(i64, String)> { } } -impl SseEncode - for Vec<( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - )> -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - <( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - )>::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec<(String, crate::llm::plugins::chat_db::mysql::CellType)> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -2212,21 +2063,6 @@ impl SseEncode for (Vec, String) { } } -impl SseEncode - for ( - String, - crate::llm::app_flowy_model::AttributeType, - Option, - ) -{ - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.0, serializer); - ::sse_encode(self.1, serializer); - >::sse_encode(self.2, serializer); - } -} - impl SseEncode for (String, crate::llm::plugins::chat_db::mysql::CellType) { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 45e797e..88c14f4 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -1,6 +1,7 @@ pub mod api; mod errors; mod frb_generated; +#[allow(dead_code)] mod llm; mod software_monitor; pub mod system_monitor; diff --git a/rust/src/llm/app_flowy_model.rs b/rust/src/llm/app_flowy_model.rs deleted file mode 100644 index a176591..0000000 --- a/rust/src/llm/app_flowy_model.rs +++ /dev/null @@ -1,117 +0,0 @@ -use regex::Regex; -use serde::Deserialize; -use serde::Serialize; - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Root { - pub document: Document, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Document { - #[serde(rename = "type")] - pub type_field: String, - pub children: Vec, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Children { - #[serde(rename = "type")] - pub type_field: String, - pub data: Data, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Data { - pub level: Option, - pub delta: Vec, - pub align: Option, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Delum { - pub insert: String, - pub attributes: Option, -} - -#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Attributes { - pub bold: Option, - pub italic: Option, - pub file: Option, - pub sql: Option, -} - -pub fn str_to_doc(s: String) -> anyhow::Result { - let v: Root = serde_json::from_str(&s)?; - anyhow::Ok(v) -} - -pub fn doc_to_str(doc: &Root) -> anyhow::Result { - let s = serde_json::to_string(doc)?; - anyhow::Ok(s) -} - -#[derive(Debug, Clone, PartialEq)] -pub enum AttributeType { - Prompt, - File, - Sql, -} - -pub fn get_all_cadidates( - s: String, -) -> anyhow::Result< - Vec<( - /*prompt*/ String, - /*type*/ AttributeType, - /*sql,filepath,...*/ Option, - )>, -> { - let mut v: Vec<(String, AttributeType, Option)> = Vec::new(); - // println!("{:?}", s); - let root = str_to_doc(s)?; - let re = Regex::new(r"\{\{(.*?)\}\}").unwrap(); - let doc = root.document; - let children = doc.children; - for i in children { - if !i.data.delta.is_empty() { - for d in i.data.delta { - for cap in re.captures_iter(&d.insert.clone()) { - if let Some(matched) = cap.get(0) { - println!("Matched text: {}", matched.as_str()); - v.push((matched.as_str().to_string(), AttributeType::Prompt, None)); - } - } - - // println!("{:?}", d.attributes); - - if d.attributes.is_some() { - if d.attributes.clone().unwrap().sql.is_some() { - v.push(( - d.insert.clone(), - AttributeType::Sql, - d.attributes.clone().unwrap().sql, - )); - } - - if d.attributes.clone().unwrap().file.is_some() { - v.push(( - d.insert.clone(), - AttributeType::File, - d.attributes.clone().unwrap().file, - )); - } - } - } - } - } - - anyhow::Ok(v) -} diff --git a/rust/src/llm/mod.rs b/rust/src/llm/mod.rs index 7532819..8e60224 100644 --- a/rust/src/llm/mod.rs +++ b/rust/src/llm/mod.rs @@ -1,61 +1,2 @@ -pub mod app_flowy_model; pub mod internal_prompts; pub mod plugins; -pub mod template; - -use once_cell::sync::Lazy; -use std::collections::HashMap; -use std::fs::File; -use std::io::{BufRead, BufReader}; -use std::sync::RwLock; - -use crate::frb_generated::StreamSink; - -pub static ENV_PARAMS: Lazy>> = Lazy::new(|| RwLock::new(None)); - -#[derive(Debug, Clone)] -pub struct EnvParams { - pub base: String, - pub name: String, - pub chat_base: String, - pub sk: Option, -} - -pub static LLM_MESSAGE_SINK: RwLock>> = RwLock::new(None); - -#[derive(Debug, Clone)] -pub struct LLMMessage { - pub uuid: String, - pub content: String, - pub _type: u8, // 0 human,1 system,2 ai, 3 tool, -} - -impl LLMMessage { - pub fn default() -> Self { - LLMMessage { - uuid: "".to_owned(), - content: "".to_owned(), - _type: 2, - } - } -} - -pub fn env_parse(path: String) -> anyhow::Result> { - let mut res = HashMap::new(); - let file = File::open(path)?; - let reader = BufReader::new(file); - let lines = reader.lines(); - - for i in lines { - let _line = i?; - let sep = _line.split("=").collect::>(); - if sep.len() == 2 { - res.insert( - sep.first().unwrap().trim().to_owned(), - sep.last().unwrap().trim().to_owned(), - ); - } - } - - anyhow::Ok(res) -} diff --git a/rust/src/llm/plugins/chat_file.rs b/rust/src/llm/plugins/chat_file.rs index 02f11ea..787f7dd 100644 --- a/rust/src/llm/plugins/chat_file.rs +++ b/rust/src/llm/plugins/chat_file.rs @@ -4,7 +4,7 @@ use reqwest::{multipart, Client}; use serde::Deserialize; use serde::Serialize; -use crate::llm::ENV_PARAMS; +use super::EnvParams; // kimi #[derive(Serialize, Deserialize)] @@ -31,8 +31,7 @@ struct FileContentResponse { } // kimi -pub async fn get_file_content(p: String) -> anyhow::Result { - let params = ENV_PARAMS.read().unwrap(); +pub async fn get_file_content(p: String, params: EnvParams) -> anyhow::Result { let kind = infer::get_from_path(p.clone())?; let mine_str; let file_type; @@ -43,42 +42,36 @@ pub async fn get_file_content(p: String) -> anyhow::Result { mine_str = "text/plain"; file_type = "txt"; } - // println!("mine_str {:?}",mine_str); - match params.clone() { - Some(_p) => { - let client = Client::new(); - let mut file = File::open(p)?; - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer)?; - let form = multipart::Form::new().text("purpose", "file-extract").part( - "file", - multipart::Part::bytes(buffer) - .file_name(format!("file.{}", file_type)) - .mime_str(mine_str)?, - ); + let client = Client::new(); + let mut file = File::open(p)?; + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer)?; + let form = multipart::Form::new().text("purpose", "file-extract").part( + "file", + multipart::Part::bytes(buffer) + .file_name(format!("file.{}", file_type)) + .mime_str(mine_str)?, + ); - let response = client - .post(_p.base.clone() + "/files") - .header( - "Authorization", - format!("Bearer {}", _p.sk.clone().unwrap()), - ) - .multipart(form) - .send() - .await?; + let response = client + .post(params.base.clone() + "/files") + .header( + "Authorization", + format!("Bearer {}", params.sk.clone().unwrap()), + ) + .multipart(form) + .send() + .await?; - let res: UploadFileResponse = response.json().await?; - let file_content_response = client - .get(_p.base + "/files/" + &res.id.clone() + "/content") - .header("Authorization", format!("Bearer {}", _p.sk.unwrap())) - .send() - .await?; + let res: UploadFileResponse = response.json().await?; + let file_content_response = client + .get(params.base + "/files/" + &res.id.clone() + "/content") + .header("Authorization", format!("Bearer {}", params.sk.unwrap())) + .send() + .await?; - return Ok(file_content_response - .json::() - .await? - .content); - } - None => anyhow::bail!("open ai client is None"), - } + return Ok(file_content_response + .json::() + .await? + .content); } diff --git a/rust/src/llm/plugins/mod.rs b/rust/src/llm/plugins/mod.rs index 98d28a7..e9c8910 100644 --- a/rust/src/llm/plugins/mod.rs +++ b/rust/src/llm/plugins/mod.rs @@ -1,2 +1,10 @@ pub mod chat_db; pub mod chat_file; + +#[derive(Debug, Clone)] +pub struct EnvParams { + pub base: String, + pub name: String, + pub chat_base: String, + pub sk: Option, +} diff --git a/rust/src/llm/template.rs b/rust/src/llm/template.rs deleted file mode 100644 index da19e5a..0000000 --- a/rust/src/llm/template.rs +++ /dev/null @@ -1,175 +0,0 @@ -use super::app_flowy_model::AttributeType; - -pub struct AppFlowyTemplate { - pub items: Vec, -} - -#[derive(Debug, Clone)] -pub struct TemplateItem { - pub prompt: String, - pub index: u32, - pub next: Option, - pub attr_type: AttributeType, - pub extra: Option, -} - -impl TemplateItem { - pub fn from(i: (String, u32, Option, AttributeType, Option)) -> Self { - Self { - prompt: i.0, - index: i.1, - next: i.2, - attr_type: i.3, - extra: i.4, - } - } -} - -pub fn generate_template_items_from_list( - list: Vec<(String, u32, Option, AttributeType, Option)>, -) -> Vec { - let mut v = Vec::new(); - for i in list { - v.push(TemplateItem::from(i)); - } - - v -} - -#[derive(Debug, Clone)] -pub struct TemplateResult { - pub prompt: String, - pub index: u32, - pub response: String, -} - -impl AppFlowyTemplate { - pub fn from(v: Vec) -> Self { - Self { items: v } - } - - pub fn into_multiple(&mut self) -> Vec> { - self.items.sort_by(|a, b| a.index.cmp(&b.index)); - let mut vecs: Vec> = Vec::new(); - let mut saved: Vec = Vec::new(); - - let mut i = 0; - while i < self.items.len() { - let mut item = self.items.get(i).unwrap(); - if saved.contains(&item.index) { - i += 1; - continue; - } - - let mut sub_vec = Vec::new(); - sub_vec.push(item); - i = i + 1; - if item.next == None { - saved.push(item.index); - vecs.push(sub_vec); - } else { - for next in &self.items { - if saved.contains(&next.index) { - continue; - } - if item.next == None { - saved.push(item.index); - // vecs.push(sub_vec); - break; - } - - if next.index == item.next.unwrap() { - sub_vec.push(next); - saved.push(next.index); - item = next; - } - } - - vecs.push(sub_vec); - } - } - vecs - } -} - -// /// TODO: 暂时sql和文件问答不支持顺序链 -// async fn items_to_chain_with_plugins( -// items: &Vec<&TemplateItem>, -// llm: OpenAI, -// ) -> (Option>, Option) { -// if items.is_empty() { -// return (None, None); -// } - -// if items.len() == 1 { -// let mut extra_content = "".to_owned(); -// let item = items.get(0).unwrap(); -// // sql - -// // file -// if item.attr_type == AttributeType::File { -// let file_content = get_file_content(item.extra.clone().unwrap_or("".to_owned())).await; -// match file_content { -// Ok(_f) => { -// extra_content = _f; -// } -// Err(_e) => { -// println!("[rust-error] file content is None"); -// return (None, None); -// } -// } -// } - -// // 返回一般的LLMChain -// let prompt = HumanMessagePromptTemplate::new(PromptTemplate::new( -// items.first().unwrap().prompt.clone() + &extra_content, -// vec![], -// TemplateFormat::FString, -// )); -// let normal_chain = LLMChainBuilder::new() -// .prompt(prompt) -// .llm(llm.clone()) -// .build() -// .unwrap(); -// return (Some(Box::new(normal_chain)), None); -// } - -// if items.len() > 1 { -// // let mut chains: Vec = Vec::new(); -// let mut seq_chain_builder = SequentialChainBuilder::new(); -// let mut i = 0; -// while i < items.len() { -// let input = format!("input{}", i); -// let output = format!("input{}", i + 1); -// let prompt_str; -// if i == 0 { -// prompt_str = -// "请根据以下要求,帮我生成对应的文案。 {{".to_owned() + &input + "}}"; -// } else { -// prompt_str = "请根据以下内容和额外要求,帮我生成对应的文案。内容: {{".to_owned() -// + &input -// + "}}, 额外要求: " -// + &items.get(i).unwrap().prompt; -// } - -// let prompt = HumanMessagePromptTemplate::new(template_jinja2!(prompt_str, input)); -// let c = LLMChainBuilder::new() -// .prompt(prompt) -// .llm(llm.clone()) -// .output_key(output) -// .build() -// .unwrap(); -// // chains.push(c); -// seq_chain_builder = seq_chain_builder.add_chain(c); -// i += 1; -// } - -// let seq_chain = seq_chain_builder.build(); -// return ( -// Some(Box::new(seq_chain)), -// Some(items.first().unwrap().prompt.clone()), -// ); -// } - -// (None, None) -// } From a51cbbd97b71da599c655840a18e2208110a2d7d Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Mon, 27 May 2024 22:10:46 +0800 Subject: [PATCH 10/16] refactor: chains --- langchain_lib/lib/client/openai_client.dart | 10 ++- langchain_lib/lib/models/template_item.dart | 2 +- lib/llm/editor/compose_screen.dart | 72 +++++++++---------- .../langchain/components/seq_chain_flow.dart | 17 +++-- .../models/chain_flow_state.dart | 59 +++++++++++++-- .../notifiers/chain_flow_notifier.dart | 37 ---------- 6 files changed, 104 insertions(+), 93 deletions(-) diff --git a/langchain_lib/lib/client/openai_client.dart b/langchain_lib/lib/client/openai_client.dart index b734826..e0a82fc 100644 --- a/langchain_lib/lib/client/openai_client.dart +++ b/langchain_lib/lib/client/openai_client.dart @@ -110,10 +110,16 @@ class OpenaiClient extends Client { Future> invokeChainWithTemplateItems( List items) async { final chain = intoChain(items); + final result = {}; if (chain != null) { - return invokeChain(chain, items.length, items.first.prompt); + final chainResult = + await invokeChain(chain, items.length, items.first.prompt); + + for (int i = 0; i < chainResult.length; i++) { + result[items[i].prompt] = chainResult.values.elementAt(i); + } } - return {}; + return result; } } diff --git a/langchain_lib/lib/models/template_item.dart b/langchain_lib/lib/models/template_item.dart index 230b34b..3f06298 100644 --- a/langchain_lib/lib/models/template_item.dart +++ b/langchain_lib/lib/models/template_item.dart @@ -5,7 +5,7 @@ import 'package:langchain_lib/models/appflowy_model.dart'; class TemplateItem { final String prompt; final int index; - final int? next; + int? next; final AttributeType attrType; final String? extra; diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index d10d42f..a0de0b5 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -1,4 +1,6 @@ // ignore: unused_import +// ignore_for_file: avoid_init_to_null + import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; @@ -14,6 +16,7 @@ import 'package:all_in_one/llm/plugins/mind_map.dart'; import 'package:all_in_one/llm/plugins/models/mind_map_model.dart'; import 'package:all_in_one/llm/plugins/record/record_utils.dart'; import 'package:all_in_one/llm/template_editor/extension.dart'; +import 'package:all_in_one/llm/template_editor/models/chain_flow_state.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; import 'package:appflowy_editor/appflowy_editor.dart'; import 'package:flutter/material.dart'; @@ -40,6 +43,7 @@ class _ComposeScreenState extends ConsumerState { late String result = ""; bool isTemplateLoaded = false; final AiClient aiClient = AiClient(); + late LlmTemplate? template = null; // late Stream toMapStream = mindMapStream(); @@ -100,7 +104,7 @@ class _ComposeScreenState extends ConsumerState { icon: EvaIcons.file_text, title: "Load Template", onTap: () async { - final LlmTemplate? template = await showGeneralDialog( + template = await showGeneralDialog( barrierColor: Colors.transparent, barrierDismissible: true, barrierLabel: "load-template", @@ -117,12 +121,13 @@ class _ComposeScreenState extends ConsumerState { // jsonString: Future(() => _jsonString), datasource: Datasource( type: DatasourceType.json, - content: template.template), + content: template!.template), onEditorStateChange: (editorState) { _editorState = editorState; }, showTemplateFeatures: false, ); + isTemplateLoaded = true; }); } }, @@ -139,41 +144,34 @@ class _ComposeScreenState extends ConsumerState { } ref.read(chainFlowProvider.notifier).changeContent( jsonEncode(_editorState.document.toJson())); - // final l = await ref.read(chainFlowProvider.notifier).toRust(); - - // showGeneralDialog( - // barrierDismissible: false, - // barrierColor: Colors.transparent, - // // ignore: use_build_context_synchronously - // context: context, - // pageBuilder: (c, _, __) { - // return const LoadingDialog(); - // }).then((_) async { - // if (widget.enablePlugin) { - // // 存一份数据 - // RecordUtils.putNewMessage( - // MessageType.response, _editorState.toStr()); - // } - // }); - - // generateFromTemplate(v: l, enablePlugin: true) - // .then((value) async { - // final md = await optimizeDoc(s: _editorState.toStr()); - // setState( - // () { - // _widgetBuilder = (context) => Editor( - // datasource: Datasource( - // type: DatasourceType.markdown, - // content: md, - // ), - // onEditorStateChange: (editorState) { - // _editorState = editorState; - // }, - // showTemplateFeatures: true, - // ); - // }, - // ); - // }); + ChainFlowItem item = + ChainFlowItem.fromJson(jsonDecode(template!.chains)); + item.eval(aiClient).then((v) { + for (final event in v.entries) { + for (final i in _editorState.document.root.children) { + if ((i.attributes['delta'] as List).isNotEmpty) { + // Node? existsNode = null; + Map? map = null; + for (int j = 0; + j < i.attributes['delta'].length; + j++) { + if (i.attributes['delta'][j]["insert"] != null && + i.attributes['delta'][j]["insert"] + .contains(event.key)) { + map = i.attributes; + map['delta'][j]['insert'] = + event.key + event.value.toString(); + } + } + if (map != null) { + i.updateAttributes(map); + } + } + } + } + // print("============================="); + // print(_editorState.toStr()); + }); }, ), SidemenuDivider(), diff --git a/lib/llm/langchain/components/seq_chain_flow.dart b/lib/llm/langchain/components/seq_chain_flow.dart index 7699cdd..96fa285 100644 --- a/lib/llm/langchain/components/seq_chain_flow.dart +++ b/lib/llm/langchain/components/seq_chain_flow.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'package:all_in_one/llm/langchain/extension.dart'; import 'package:all_in_one/llm/langchain/models/chains.dart'; import 'package:all_in_one/llm/langchain/notifiers/chain_notifier.dart'; @@ -13,6 +11,7 @@ import 'package:star_menu/star_menu.dart'; import 'modify_chain_dialog.dart'; +/// TODO 可能后续会删除整个页面,暂时没有什么用处 class FlowScreen extends ConsumerStatefulWidget { const FlowScreen({super.key}); @@ -86,13 +85,13 @@ class _FlowScreenState extends ConsumerState { heroTag: null, child: const Icon(Icons.save), onPressed: () { - final r = ref.read(chainProvider.notifier).validate(); - if (r) { - Chains chains = - Chains(items: ref.read(chainProvider.notifier).items); - final jsonStr = jsonEncode(chains.toJson()); - // sequentialChainChat(jsonStr: jsonStr, query: "shoe"); - } + // final r = ref.read(chainProvider.notifier).validate(); + // if (r) { + // Chains chains = + // Chains(items: ref.read(chainProvider.notifier).items); + // final jsonStr = jsonEncode(chains.toJson()); + // // sequentialChainChat(jsonStr: jsonStr, query: "shoe"); + // } }, ), FloatingActionButton.small( diff --git a/lib/llm/template_editor/models/chain_flow_state.dart b/lib/llm/template_editor/models/chain_flow_state.dart index 617a3fb..6975300 100644 --- a/lib/llm/template_editor/models/chain_flow_state.dart +++ b/lib/llm/template_editor/models/chain_flow_state.dart @@ -1,5 +1,6 @@ import 'dart:ui'; +import 'package:all_in_one/llm/ai_client.dart'; import 'package:langchain_lib/models/template_item.dart'; class ChainFlowState { @@ -15,8 +16,48 @@ class ChainFlowState { } extension Eval on ChainFlowItem { - Future> eval() async { - return {}; + Future> eval(AiClient client) async { + List items = []; + + List flattened = []; + for (final i in connections) { + flattened.addAll([i.$1, i.$2]); + } + + List> chains = []; + + for (int i = 0; i < flowItems.length; i++) { + final template = TemplateItem( + attrType: flowItems.elementAt(i).type, + prompt: flowItems.elementAt(i).content, + index: flowItems.elementAt(i).index, + extra: flowItems.elementAt(i).extra); + + if (flattened.contains(flowItems.elementAt(i).uuid)) { + items.add(template); + } else { + chains.add([template]); + } + } + + for (final i in connections) { + final first = flowItems.where((v) => v.uuid == i.$1).first; + final firstItem = items.where((v) => v.index == first.index).first; + final second = flowItems.where((v) => v.uuid == i.$2).first; + final secondItem = items.where((v) => v.index == second.index).first; + firstItem.next = second.index; + + chains.add([firstItem, secondItem]); + } + + Map result = {}; + + // print(chains); + for (final i in chains) { + result.addAll(await client.client!.invokeChainWithTemplateItems(i)); + } + + return result; } } @@ -76,11 +117,15 @@ class ChainFlowItem { }); } late List<(String, String)> c = []; - if (json['connections'] != null) { - json['connections'].forEach((v) { - // s.add(FlowItem.fromJson(v)); - c.add((v.key, v.value)); - }); + if (json['connections'] != null && json['connections'].isNotEmpty) { + // print(json['connections']); + // json['connections'].forEach((Map v) { + // // s.add(FlowItem.fromJson(v)); + // c.add((v.entries.first.key, v.entries.first.value)); + // }); + for (Map v in json['connections']) { + c.add((v.entries.first.key, v.entries.first.value)); + } } return ChainFlowItem(flowItems: s, connections: c); } diff --git a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart index e266b6b..84000f4 100644 --- a/lib/llm/template_editor/notifiers/chain_flow_notifier.dart +++ b/lib/llm/template_editor/notifiers/chain_flow_notifier.dart @@ -1,5 +1,4 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:langchain_lib/models/template_item.dart'; import '../models/chain_flow_state.dart'; @@ -62,42 +61,6 @@ class ChainFlowNotifier extends Notifier { connections: connections, flowItems: state.items.flowItems), state.content); } - - Future> toRust() async { - List<(String, int, int?, AttributeType, String?)> result = []; - // final items = await templateToPrompts(template: state.content); - // final itemTuple = items - // .mapIndexed( - // (index, element) => ((index, element.$1, element.$2, element.$3))) - // .toList(); - - // List ids = []; - // for (final i in state.items) { - // ids.addAll(i.ids); - // for (int j = 0; j < i.ids.length; j++) { - // if (j < i.ids.length - 1) { - // result.add(( - // i.contents[j], - // i.ids[j], - // ids[j + 1], - // AttributeType.prompt, - // null - // )); - // } else { - // result - // .add((i.contents[j], i.ids[j], null, AttributeType.prompt, null)); - // } - // } - // } - - // itemTuple.retainWhere((element) => !ids.contains(element.$1)); - - // for (final t in itemTuple) { - // result.add((t.$2, t.$1, null, t.$3, t.$4)); - // } - - return result; - } } final chainFlowProvider = NotifierProvider( From 4859152d3df4db604a72e709b888193cfa0ce7b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A3=B9=E9=9B=B6?= Date: Tue, 28 May 2024 13:30:27 +0800 Subject: [PATCH 11/16] WIP: api reach RPM bug --- langchain_lib/lib/client/client.dart | 2 + langchain_lib/lib/client/load_env.dart | 8 +- langchain_lib/lib/client/openai_client.dart | 41 ++++++---- langchain_lib/test/test_example.dart | 8 +- langchain_lib/test/test_openai_client.dart | 9 +-- langchain_lib/test/test_seq_chain.dart | 9 +-- langchain_lib/test/test_seq_chain2.dart | 9 +-- lib/llm/ai_client.dart | 32 +++++++- lib/llm/editor/compose_screen.dart | 50 +++++++++++++ lib/llm/global/components/loading_dialog.dart | 68 +++++++++++++++++ .../notifiers/loading_dialog_notifier.dart | 21 ++++++ .../components/loading_dialog.dart | 74 ------------------- 12 files changed, 220 insertions(+), 111 deletions(-) create mode 100644 lib/llm/global/components/loading_dialog.dart create mode 100644 lib/llm/global/notifiers/loading_dialog_notifier.dart delete mode 100644 lib/llm/template_editor/components/loading_dialog.dart diff --git a/langchain_lib/lib/client/client.dart b/langchain_lib/lib/client/client.dart index 3adde31..38c8060 100644 --- a/langchain_lib/lib/client/client.dart +++ b/langchain_lib/lib/client/client.dart @@ -2,6 +2,8 @@ import 'package:langchain/langchain.dart'; import 'package:langchain_lib/models/template_item.dart'; abstract class Client { + int maxTryTimes = 60; // kimi没充值的情况下每分钟请求3个 + Future invoke(List history); Stream stream(List history); diff --git a/langchain_lib/lib/client/load_env.dart b/langchain_lib/lib/client/load_env.dart index d8dd1fe..1417919 100644 --- a/langchain_lib/lib/client/load_env.dart +++ b/langchain_lib/lib/client/load_env.dart @@ -1,11 +1,11 @@ import 'dart:io'; -List loadEnv(String path) { +Map loadEnv(String path) { File f = File(path); if (f.existsSync()) { final lines = f.readAsLinesSync(); // return f.readAsLinesSync(); - final List result = []; + final Map result = {}; for (final i in lines) { if (i.startsWith('#')) { continue; @@ -15,13 +15,13 @@ List loadEnv(String path) { if (s[0].trim() == "LLM_BASE" || s[0].trim() == "LLM_MODEL_NAME" || s[0].trim() == "LLM_SK") { - result.add(s[1].trim()); + result[s[0].trim()] = s[1].trim(); } } } return result; } else { - return []; + return {}; } } diff --git a/langchain_lib/lib/client/openai_client.dart b/langchain_lib/lib/client/openai_client.dart index e0a82fc..8f56f9e 100644 --- a/langchain_lib/lib/client/openai_client.dart +++ b/langchain_lib/lib/client/openai_client.dart @@ -37,7 +37,10 @@ class OpenaiClient extends Client { return OpenaiClient(baseUrl: ""); } - return OpenaiClient(baseUrl: envs[0], apiKey: envs[2], modelName: envs[1]); + return OpenaiClient( + baseUrl: envs["LLM_BASE"] ?? "", + apiKey: envs["LLM_SK"] ?? "", + modelName: envs["LLM_MODEL_NAME"] ?? ""); } @override @@ -82,25 +85,37 @@ class OpenaiClient extends Client { @override Future> invokeChain( BaseChain chain, int chainLength, String input) async { - final dynamic result; + final Future> fResult; + if (chainLength == 1) { - result = (await chain.call(input))['output'].content; + fResult = chain.call(input); } else { - result = await chain.call({"input0": input}, returnOnlyOutputs: false); + fResult = chain.call({"input0": input}, returnOnlyOutputs: false); } + + int tryTimes = 0; Map r = {}; - if (result is Map) { - for (int i = 0; i < chainLength; i++) { - if (result["input${i + 1}"] != null) { - if (result["input${i + 1}"] is AIChatMessage) { - r["input${i + 1}"] = result["input${i + 1}"].content; - } else { - r["input${i + 1}"] = result["input${i + 1}"]; + while (tryTimes < super.maxTryTimes) { + tryTimes += 1; + try { + final result = await fResult; + if (result.length == 1) { + r["input$chainLength"] = result['output'].content.toString(); + } else { + for (int i = 0; i < chainLength; i++) { + if (result["input${i + 1}"] != null) { + if (result["input${i + 1}"] is AIChatMessage) { + r["input${i + 1}"] = result["input${i + 1}"].content; + } else { + r["input${i + 1}"] = result["input${i + 1}"]; + } + } } } + break; + } catch (e) { + await Future.delayed(const Duration(seconds: 1)); } - } else { - r["input$chainLength"] = result.toString(); } return r; diff --git a/langchain_lib/test/test_example.dart b/langchain_lib/test/test_example.dart index 7a96d3f..16be17c 100644 --- a/langchain_lib/test/test_example.dart +++ b/langchain_lib/test/test_example.dart @@ -3,14 +3,14 @@ import 'package:langchain_lib/client/load_env.dart'; import 'package:langchain_openai/langchain_openai.dart'; void main() async { - List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + Map envs = loadEnv(r"D:\github_repo\all_in_one\env"); if (envs.length != 3) { return; } final llm = ChatOpenAI( - apiKey: envs[2], - baseUrl: envs[0], - defaultOptions: ChatOpenAIOptions(model: envs[1])); + apiKey: envs["LLM_SK"], + baseUrl: envs["LLM_BASE"], + defaultOptions: ChatOpenAIOptions(model: envs["LLM_MODEL_NAME"])); // This is an LLMChain to write a synopsis given a title of a play const synopsisTemplate = ''' diff --git a/langchain_lib/test/test_openai_client.dart b/langchain_lib/test/test_openai_client.dart index 4de05e4..663c47e 100644 --- a/langchain_lib/test/test_openai_client.dart +++ b/langchain_lib/test/test_openai_client.dart @@ -5,16 +5,15 @@ import 'package:langchain_lib/client/openai_client.dart'; import 'package:langchain_lib/client/load_env.dart'; void main() async { - List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + Map envs = loadEnv(r"D:\github_repo\all_in_one\env"); if (envs.length != 3) { return; } final client = OpenaiClient( - baseUrl: envs[0], - apiKey: envs[2], - modelName: envs[1], - ); + baseUrl: envs["LLM_BASE"] ?? "", + apiKey: envs["LLM_SK"] ?? "", + modelName: envs["LLM_MODEL_NAME"] ?? ""); await client.invoke([ ChatMessage.system( diff --git a/langchain_lib/test/test_seq_chain.dart b/langchain_lib/test/test_seq_chain.dart index 99ae3c4..28dcdef 100644 --- a/langchain_lib/test/test_seq_chain.dart +++ b/langchain_lib/test/test_seq_chain.dart @@ -3,15 +3,14 @@ import 'package:langchain_lib/langchain_lib.dart'; import 'package:langchain_lib/models/template_item.dart'; void main() { - List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + Map envs = loadEnv(r"D:\github_repo\all_in_one\env"); if (envs.length != 3) { return; } final client = OpenaiClient( - baseUrl: envs[0], - apiKey: envs[2], - modelName: envs[1], - ); + baseUrl: envs["LLM_BASE"] ?? "", + apiKey: envs["LLM_SK"] ?? "", + modelName: envs["LLM_MODEL_NAME"] ?? ""); BaseChain? chain = client.intoChain([ TemplateItem( diff --git a/langchain_lib/test/test_seq_chain2.dart b/langchain_lib/test/test_seq_chain2.dart index 7088b99..7c44bb5 100644 --- a/langchain_lib/test/test_seq_chain2.dart +++ b/langchain_lib/test/test_seq_chain2.dart @@ -3,15 +3,14 @@ import 'package:langchain_lib/langchain_lib.dart'; import 'package:langchain_lib/models/template_item.dart'; void main() { - List envs = loadEnv(r"D:\github_repo\all_in_one\env"); + Map envs = loadEnv(r"D:\github_repo\all_in_one\env"); if (envs.length != 3) { return; } final client = OpenaiClient( - baseUrl: envs[0], - apiKey: envs[2], - modelName: envs[1], - ); + baseUrl: envs["LLM_BASE"] ?? "", + apiKey: envs["LLM_SK"] ?? "", + modelName: envs["LLM_MODEL_NAME"] ?? ""); BaseChain? chain = client.intoChain([ TemplateItem( diff --git a/lib/llm/ai_client.dart b/lib/llm/ai_client.dart index 9515038..b13c88c 100644 --- a/lib/llm/ai_client.dart +++ b/lib/llm/ai_client.dart @@ -1,3 +1,4 @@ +import 'package:all_in_one/common/logger.dart'; import 'package:langchain_lib/client/client.dart'; import 'package:langchain_lib/langchain_lib.dart'; @@ -13,7 +14,7 @@ class AiClient { client = OpenaiClient.fromEnv(path); } - Stream optimizeDoc(String doc) { + Stream optimizeDocStream(String doc) { final history = [ MessageUtil.createSystemMessage( "你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), @@ -25,6 +26,35 @@ class AiClient { return client!.stream(history); } + Future optimizeDoc(String doc) async { + final history = [ + MessageUtil.createSystemMessage( + "你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), + MessageUtil.createHumanMessage( + "请帮我改写优化以下文章。注意:1.进行文章改写时请尽量使用简体中文。\n2.只改写优化 标签中的部分。\n3.保留 标签中的内容。\n4.最终结果中删除 标签。"), + MessageUtil.createHumanMessage(doc) + ]; + int tryTimes = 0; + // ignore: avoid_init_to_null + late ChatResult? result = null; + + while (tryTimes < client!.maxTryTimes) { + tryTimes += 1; + // print(tryTimes); + logger.info( + "Retrying $tryTimes times, remaining ${client!.maxTryTimes - tryTimes} times"); + try { + result = await client!.invoke(history); + break; + } catch (e) { + // logger.severe(e.toString()); + await Future.delayed(const Duration(seconds: 1)); + } + } + + return result; + } + Stream textToMindMap(String text) { final history = [ MessageUtil.createSystemMessage("你是一个专业的分析师,善于整理思维导图。"), diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index a0de0b5..0dd67d2 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -9,8 +9,10 @@ import 'package:all_in_one/isar/llm_template.dart'; import 'package:all_in_one/llm/ai_client.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; import 'package:all_in_one/llm/global/components/load_template_dialog.dart'; +import 'package:all_in_one/llm/global/components/loading_dialog.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; +import 'package:all_in_one/llm/global/notifiers/loading_dialog_notifier.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:all_in_one/llm/plugins/mind_map.dart'; import 'package:all_in_one/llm/plugins/models/mind_map_model.dart'; @@ -142,10 +144,25 @@ class _ComposeScreenState extends ConsumerState { RecordUtils.putNewMessage( MessageType.query, _editorState.toStr()); } + ref + .read(loadingDialogProvider.notifier) + .changeState(LoadingDialogState.format); + showGeneralDialog( + barrierDismissible: true, + barrierColor: Colors.transparent, + barrierLabel: "loading-dialog", + context: context, + pageBuilder: (c, _, __) { + return const Center(child: LoadingDialog()); + }); + ref.read(chainFlowProvider.notifier).changeContent( jsonEncode(_editorState.document.toJson())); ChainFlowItem item = ChainFlowItem.fromJson(jsonDecode(template!.chains)); + ref + .read(loadingDialogProvider.notifier) + .changeState(LoadingDialogState.eval); item.eval(aiClient).then((v) { for (final event in v.entries) { for (final i in _editorState.document.root.children) { @@ -169,8 +186,41 @@ class _ComposeScreenState extends ConsumerState { } } } + // print("============================="); // print(_editorState.toStr()); + }).then((_) async { + // print("============================="); + ref + .read(loadingDialogProvider.notifier) + .changeState(LoadingDialogState.optimize); + + final result = + await aiClient.optimizeDoc(_editorState.toStr()); + + // print(result.outputAsString); + + if (result != null) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.markdown, + content: result.outputAsString), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + }); + } else { + // ignore: use_build_context_synchronously + ToastUtils.error(context, title: "Try later"); + } + }).then((_) { + ref + .read(loadingDialogProvider.notifier) + .changeState(LoadingDialogState.done); }); }, ), diff --git a/lib/llm/global/components/loading_dialog.dart b/lib/llm/global/components/loading_dialog.dart new file mode 100644 index 0000000..85c030e --- /dev/null +++ b/lib/llm/global/components/loading_dialog.dart @@ -0,0 +1,68 @@ +import 'package:all_in_one/layout/styles.dart'; +import 'package:all_in_one/llm/global/notifiers/loading_dialog_notifier.dart'; +import 'package:blurrycontainer/blurrycontainer.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +// ignore: must_be_immutable +class LoadingDialog extends ConsumerWidget { + const LoadingDialog({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final state = ref.watch(loadingDialogProvider); + + WidgetsBinding.instance.addPostFrameCallback((v) async { + await Future.delayed(const Duration(milliseconds: 500)); + if (ref.read(loadingDialogProvider) == LoadingDialogState.done) { + // ignore: use_build_context_synchronously + Navigator.of(context).pop(); + } + }); + String stateStr = ""; + // print(state); + + switch (state) { + case LoadingDialogState.done: + stateStr = "done"; + break; + case LoadingDialogState.eval: + stateStr = "evaluating..."; + break; + case LoadingDialogState.optimize: + stateStr = "optimizing..."; + break; + case LoadingDialogState.format: + stateStr = "formating..."; + break; + default: + stateStr = "evaluating..."; + } + + return Align( + alignment: Alignment.centerRight, + child: BlurryContainer( + width: MediaQuery.of(context).size.width - + LayoutStyle.sidebarCollapse - + 10, + height: MediaQuery.of(context).size.height, + blur: 5, + elevation: 0, + color: Colors.transparent, + padding: const EdgeInsets.all(8), + borderRadius: const BorderRadius.all(Radius.circular(0)), + child: Center( + child: Card( + child: SizedBox( + width: 200, + height: 200, + child: Center( + child: Text(stateStr), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/llm/global/notifiers/loading_dialog_notifier.dart b/lib/llm/global/notifiers/loading_dialog_notifier.dart new file mode 100644 index 0000000..44a2929 --- /dev/null +++ b/lib/llm/global/notifiers/loading_dialog_notifier.dart @@ -0,0 +1,21 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +enum LoadingDialogState { eval, format, optimize, done } + +class LoadingDialogNotifier extends Notifier { + @override + LoadingDialogState build() { + return LoadingDialogState.format; + } + + changeState(LoadingDialogState s) { + if (state != s) { + state = s; + } + } +} + +final loadingDialogProvider = + NotifierProvider( + () => LoadingDialogNotifier(), +); diff --git a/lib/llm/template_editor/components/loading_dialog.dart b/lib/llm/template_editor/components/loading_dialog.dart deleted file mode 100644 index 09c4c5d..0000000 --- a/lib/llm/template_editor/components/loading_dialog.dart +++ /dev/null @@ -1,74 +0,0 @@ -import 'package:all_in_one/layout/styles.dart'; -import 'package:blurrycontainer/blurrycontainer.dart'; -import 'package:flutter/material.dart'; - -class LoadingDialog extends StatefulWidget { - const LoadingDialog({super.key}); - - @override - State createState() => _LoadingDialogState(); -} - -class _LoadingDialogState extends State { - // final stateStream = templateStateStream(); - String state = "evaluating..."; - - @override - void initState() { - super.initState(); - // stateStream.listen((event) { - // if (mounted) { - // switch (event) { - // case TemplateRunningStage.format: - // setState(() { - // state = "formating..."; - // }); - // case TemplateRunningStage.eval: - // setState(() { - // state = "evaluating..."; - // }); - // case TemplateRunningStage.optimize: - // setState(() { - // state = "optimizing..."; - // }); - // case TemplateRunningStage.done: - // setState(() { - // state = "done"; - // }); - // Future.delayed(const Duration(milliseconds: 500), () { - // Navigator.of(context).pop(); - // }); - // } - // } - // }); - } - - @override - Widget build(BuildContext context) { - return Align( - alignment: Alignment.centerRight, - child: BlurryContainer( - width: MediaQuery.of(context).size.width - - LayoutStyle.sidebarCollapse - - 10, - height: MediaQuery.of(context).size.height, - blur: 5, - elevation: 0, - color: Colors.transparent, - padding: const EdgeInsets.all(8), - borderRadius: const BorderRadius.all(Radius.circular(0)), - child: Center( - child: Card( - child: SizedBox( - width: 200, - height: 200, - child: Center( - child: Text(state), - ), - ), - ), - ), - ), - ); - } -} From 7c4d3d2f51a05681ad3c8d5e5a0fba25d74cfbcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A3=B9=E9=9B=B6?= Date: Tue, 28 May 2024 15:55:16 +0800 Subject: [PATCH 12/16] feat: internal prompts --- lib/llm/ai_client.dart | 41 ++++++++--- lib/main.dart | 2 + lib/src/rust/api/llm_plugin_api.dart | 9 +++ lib/src/rust/frb_generated.dart | 90 ++++++++++++++++++++---- rust/src/api/llm_plugin_api.rs | 18 +++++ rust/src/frb_generated.rs | 101 +++++++++++++++++++++++---- 6 files changed, 220 insertions(+), 41 deletions(-) diff --git a/lib/llm/ai_client.dart b/lib/llm/ai_client.dart index b13c88c..2aecf16 100644 --- a/lib/llm/ai_client.dart +++ b/lib/llm/ai_client.dart @@ -1,4 +1,5 @@ import 'package:all_in_one/common/logger.dart'; +import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:langchain_lib/client/client.dart'; import 'package:langchain_lib/langchain_lib.dart'; @@ -15,11 +16,16 @@ class AiClient { } Stream optimizeDocStream(String doc) { + final role = + getPromptByName(key: "role-define", module: "template-optimize") ?? + "you are a good writer"; + final insPrompt = getPromptByName( + key: "instruction-define", module: "template-optimize") ?? + "Rewrite this article in chinese"; + final history = [ - MessageUtil.createSystemMessage( - "你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), - MessageUtil.createHumanMessage( - "请帮我改写优化以下文章。注意:1.进行文章改写时请尽量使用简体中文。\n2.只改写优化 标签中的部分。\n3.保留 标签中的内容。\n4.最终结果中删除 标签。"), + MessageUtil.createSystemMessage(role), + MessageUtil.createHumanMessage(insPrompt), MessageUtil.createHumanMessage(doc) ]; @@ -27,11 +33,19 @@ class AiClient { } Future optimizeDoc(String doc) async { + final role = + getPromptByName(key: "role-define", module: "template-optimize"); + if (role == null) { + return null; + } + final insPrompt = + getPromptByName(key: "instruction-define", module: "template-optimize"); + if (insPrompt == null) { + return null; + } final history = [ - MessageUtil.createSystemMessage( - "你是一个专业的作家,适合优化文章脉络和措辞,使得文章表达更加详实、具体,观点清晰。"), - MessageUtil.createHumanMessage( - "请帮我改写优化以下文章。注意:1.进行文章改写时请尽量使用简体中文。\n2.只改写优化 标签中的部分。\n3.保留 标签中的内容。\n4.最终结果中删除 标签。"), + MessageUtil.createSystemMessage(role), + MessageUtil.createHumanMessage(insPrompt), MessageUtil.createHumanMessage(doc) ]; int tryTimes = 0; @@ -56,10 +70,15 @@ class AiClient { } Stream textToMindMap(String text) { + final role = getPromptByName(key: "role-define", module: "conversion") ?? + "you are a good analyst"; + final insPrompt = getPromptByName( + key: "convert-file-to-mind-map", module: "conversion") ?? + "convert this article to json"; + final history = [ - MessageUtil.createSystemMessage("你是一个专业的分析师,善于整理思维导图。"), - MessageUtil.createHumanMessage( - "请帮我将以下内容转为思维导图json格式。注意:1.只需要返回json。2. json格式参考 { \"subject\":\"string\",\"subNodes\":[ { \"node\":\"string\",\" description \":\"string\",\"subNodes\":[ { \"node\":\"string\",\" description \":\"string\" } ] } ] } 。3. json不需要换行。"), + MessageUtil.createSystemMessage(role), + MessageUtil.createHumanMessage(insPrompt), MessageUtil.createHumanMessage(text) ]; return client!.stream(history); diff --git a/lib/main.dart b/lib/main.dart index e6f1464..f4060ff 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,6 +6,7 @@ import 'package:all_in_one/common/dev_utils.dart'; import 'package:all_in_one/isar/database.dart'; import 'package:all_in_one/isar/software.dart'; import 'package:all_in_one/llm/ai_client.dart'; +import 'package:all_in_one/src/rust/api/llm_plugin_api.dart'; import 'package:all_in_one/src/rust/api/software_monitor_api.dart' as smapi; import 'package:all_in_one/src/rust/api/sub_window_api.dart' as sw; import 'package:all_in_one/src/rust/api/system_monitor_api.dart' as sm; @@ -32,6 +33,7 @@ Future main() async { AiClient aiClient = AiClient(); aiClient.initOpenAi(DevUtils.env); + await readPromptsFile(path: DevUtils.prompt); IsarDatabase database = IsarDatabase(); await database.initialDatabase(); diff --git a/lib/src/rust/api/llm_plugin_api.dart b/lib/src/rust/api/llm_plugin_api.dart index 0d4e5fe..8fd01e9 100644 --- a/lib/src/rust/api/llm_plugin_api.dart +++ b/lib/src/rust/api/llm_plugin_api.dart @@ -20,3 +20,12 @@ Future?> eval( dynamic hint}) => RustLib.instance.api.crateApiLlmPluginApiEval( sqlStr: sqlStr, db: db, keys: keys, hint: hint); + +Future readPromptsFile({required String path, dynamic hint}) => + RustLib.instance.api + .crateApiLlmPluginApiReadPromptsFile(path: path, hint: hint); + +String? getPromptByName( + {required String key, required String module, dynamic hint}) => + RustLib.instance.api.crateApiLlmPluginApiGetPromptByName( + key: key, module: module, hint: hint); diff --git a/lib/src/rust/frb_generated.dart b/lib/src/rust/frb_generated.dart index 0a954d4..7f73808 100644 --- a/lib/src/rust/frb_generated.dart +++ b/lib/src/rust/frb_generated.dart @@ -66,7 +66,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.0.0-dev.35'; @override - int get rustContentHash => 1321894874; + int get rustContentHash => 512926006; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -86,6 +86,12 @@ abstract class RustLibApi extends BaseApi { Future>> crateApiLlmPluginApiGetMysqlTableInfo( {required DatabaseInfo s, dynamic hint}); + String? crateApiLlmPluginApiGetPromptByName( + {required String key, required String module, dynamic hint}); + + Future crateApiLlmPluginApiReadPromptsFile( + {required String path, dynamic hint}); + Future> crateApiProcessPortMapperApiGetProcessPortMappers({dynamic hint}); @@ -200,6 +206,60 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["s"], ); + @override + String? crateApiLlmPluginApiGetPromptByName( + {required String key, required String module, dynamic hint}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(key, serializer); + sse_encode_String(module, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_opt_String, + decodeErrorData: null, + ), + constMeta: kCrateApiLlmPluginApiGetPromptByNameConstMeta, + argValues: [key, module], + apiImpl: this, + hint: hint, + )); + } + + TaskConstMeta get kCrateApiLlmPluginApiGetPromptByNameConstMeta => + const TaskConstMeta( + debugName: "get_prompt_by_name", + argNames: ["key", "module"], + ); + + @override + Future crateApiLlmPluginApiReadPromptsFile( + {required String path, dynamic hint}) { + return handler.executeNormal(NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(path, serializer); + pdeCallFfi(generalizedFrbRustBinding, serializer, + funcId: 3, port: port_); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: null, + ), + constMeta: kCrateApiLlmPluginApiReadPromptsFileConstMeta, + argValues: [path], + apiImpl: this, + hint: hint, + )); + } + + TaskConstMeta get kCrateApiLlmPluginApiReadPromptsFileConstMeta => + const TaskConstMeta( + debugName: "read_prompts_file", + argNames: ["path"], + ); + @override Future> crateApiProcessPortMapperApiGetProcessPortMappers({dynamic hint}) { @@ -207,7 +267,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 3, port: port_); + funcId: 5, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_process_port_mapper, @@ -233,7 +293,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(name, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 6)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -257,7 +317,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 5, port: port_); + funcId: 7, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -282,7 +342,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_rust_error_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 6)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 8)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -311,7 +371,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_64(id, serializer); sse_encode_String(name, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 11, port: port_); + funcId: 13, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -337,7 +397,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 8, port: port_); + funcId: 10, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_list_software, @@ -364,7 +424,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_list_record_i_64_string(items, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 7, port: port_); + funcId: 9, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -391,7 +451,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_i_64(id, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 12, port: port_); + funcId: 14, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -419,7 +479,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_list_prim_i_64_strict_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 9)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 11)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -451,7 +511,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_record_list_prim_i_64_strict_string_Sse( s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 10)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 12)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -479,7 +539,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 13, port: port_); + funcId: 15, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -507,7 +567,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerrust_simple_notify_libPinWindowItem( data, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 14, port: port_); + funcId: 16, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -532,7 +592,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 16, port: port_); + funcId: 18, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -559,7 +619,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_StreamSink_monitor_info_Sse(s, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 15)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 17)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, diff --git a/rust/src/api/llm_plugin_api.rs b/rust/src/api/llm_plugin_api.rs index f9d1174..2e4c49c 100644 --- a/rust/src/api/llm_plugin_api.rs +++ b/rust/src/api/llm_plugin_api.rs @@ -1,3 +1,6 @@ +use flutter_rust_bridge::frb; + +use crate::llm::internal_prompts::INERTNAL_PROMPTS; use crate::llm::plugins::chat_db::mysql::CellType; use crate::llm::plugins::chat_db::DatabaseInfo; use crate::llm::plugins::chat_db::TableInfo; @@ -33,3 +36,18 @@ pub fn eval( } } } + +pub fn read_prompts_file(path: String) { + crate::llm::internal_prompts::read_prompts_file(path); +} + +#[frb(sync)] +pub fn get_prompt_by_name(key: String, module: String) -> Option { + let prompts = INERTNAL_PROMPTS.read().unwrap(); + match prompts.clone() { + Some(_p) => { + return _p.get_by_name(key, module); + } + None => None, + } +} diff --git a/rust/src/frb_generated.rs b/rust/src/frb_generated.rs index d681979..11502db 100644 --- a/rust/src/frb_generated.rs +++ b/rust/src/frb_generated.rs @@ -33,7 +33,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.0.0-dev.35"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1321894874; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 512926006; // Section: executor @@ -115,6 +115,70 @@ fn wire__crate__api__llm_plugin_api__get_mysql_table_info_impl( }, ) } +fn wire__crate__api__llm_plugin_api__get_prompt_by_name_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "get_prompt_by_name", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_key = ::sse_decode(&mut deserializer); + let api_module = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse((move || { + Result::<_, ()>::Ok(crate::api::llm_plugin_api::get_prompt_by_name( + api_key, api_module, + )) + })()) + }, + ) +} +fn wire__crate__api__llm_plugin_api__read_prompts_file_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "read_prompts_file", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_path = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse((move || { + Result::<_, ()>::Ok(crate::api::llm_plugin_api::read_prompts_file(api_path)) + })()) + } + }, + ) +} fn wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -1246,45 +1310,51 @@ fn pde_ffi_dispatcher_primary_impl( rust_vec_len, data_len, ), - 3 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( + 3 => wire__crate__api__llm_plugin_api__read_prompts_file_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 5 => wire__crate__api__process_port_mapper_api__get_process_port_mappers_impl( port, ptr, rust_vec_len, data_len, ), - 5 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), - 11 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( + 7 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), + 13 => wire__crate__api__software_monitor_api__add_to_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 8 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( + 10 => wire__crate__api__software_monitor_api__get_installed_softwares_impl( port, ptr, rust_vec_len, data_len, ), - 7 => wire__crate__api__software_monitor_api__init_monitor_impl( + 9 => wire__crate__api__software_monitor_api__init_monitor_impl( port, ptr, rust_vec_len, data_len, ), - 12 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( + 14 => wire__crate__api__software_monitor_api__remove_from_watching_list_impl( port, ptr, rust_vec_len, data_len, ), - 13 => wire__crate__api__sub_window_api__create_event_loop_impl( + 15 => wire__crate__api__sub_window_api__create_event_loop_impl( port, ptr, rust_vec_len, data_len, ), - 14 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), - 16 => wire__crate__api__system_monitor_api__start_system_monitor_impl( + 16 => wire__crate__api__sub_window_api__show_todos_impl(port, ptr, rust_vec_len, data_len), + 18 => wire__crate__api__system_monitor_api__start_system_monitor_impl( port, ptr, rust_vec_len, @@ -1302,11 +1372,12 @@ fn pde_ffi_dispatcher_sync_impl( ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 4 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), -6 => wire__crate__api__simple__rust_error_stream_impl(ptr, rust_vec_len, data_len), -9 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), -10 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), -15 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), + 4 => wire__crate__api__llm_plugin_api__get_prompt_by_name_impl(ptr, rust_vec_len, data_len), +6 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), +8 => wire__crate__api__simple__rust_error_stream_impl(ptr, rust_vec_len, data_len), +11 => wire__crate__api__software_monitor_api__software_watching_message_stream_impl(ptr, rust_vec_len, data_len), +12 => wire__crate__api__software_monitor_api__software_watching_with_foreground_message_stream_impl(ptr, rust_vec_len, data_len), +17 => wire__crate__api__system_monitor_api__system_monitor_message_stream_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } From a9198259d20c91df7f4ac65aaa56d1f050f68c87 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Tue, 28 May 2024 21:12:26 +0800 Subject: [PATCH 13/16] fix: load template twice not work --- lib/isar/llm_template.dart | 9 + lib/isar/llm_template.g.dart | 300 ++++++++++++++++++- lib/llm/editor/compose_screen.dart | 21 +- lib/llm/editor/models/datasource.dart | 11 + lib/llm/global/components/template_item.dart | 2 +- lib/llm/template_editor/template_editor.dart | 3 + 6 files changed, 336 insertions(+), 10 deletions(-) diff --git a/lib/isar/llm_template.dart b/lib/isar/llm_template.dart index 84b5bf5..b05f90e 100644 --- a/lib/isar/llm_template.dart +++ b/lib/isar/llm_template.dart @@ -8,5 +8,14 @@ class LlmTemplate { int createAt = DateTime.now().millisecondsSinceEpoch; late String name; late String template; + late String templateContent = ""; late String chains = ""; + + @override + bool operator ==(Object other) { + return other is LlmTemplate && other.id == id && other.template == template; + } + + @override + int get hashCode => template.hashCode; } diff --git a/lib/isar/llm_template.g.dart b/lib/isar/llm_template.g.dart index 98c23f7..aaa1172 100644 --- a/lib/isar/llm_template.g.dart +++ b/lib/isar/llm_template.g.dart @@ -27,15 +27,25 @@ const LlmTemplateSchema = CollectionSchema( name: r'createAt', type: IsarType.long, ), - r'name': PropertySchema( + r'hashCode': PropertySchema( id: 2, + name: r'hashCode', + type: IsarType.long, + ), + r'name': PropertySchema( + id: 3, name: r'name', type: IsarType.string, ), r'template': PropertySchema( - id: 3, + id: 4, name: r'template', type: IsarType.string, + ), + r'templateContent': PropertySchema( + id: 5, + name: r'templateContent', + type: IsarType.string, ) }, estimateSize: _llmTemplateEstimateSize, @@ -61,6 +71,7 @@ int _llmTemplateEstimateSize( bytesCount += 3 + object.chains.length * 3; bytesCount += 3 + object.name.length * 3; bytesCount += 3 + object.template.length * 3; + bytesCount += 3 + object.templateContent.length * 3; return bytesCount; } @@ -72,8 +83,10 @@ void _llmTemplateSerialize( ) { writer.writeString(offsets[0], object.chains); writer.writeLong(offsets[1], object.createAt); - writer.writeString(offsets[2], object.name); - writer.writeString(offsets[3], object.template); + writer.writeLong(offsets[2], object.hashCode); + writer.writeString(offsets[3], object.name); + writer.writeString(offsets[4], object.template); + writer.writeString(offsets[5], object.templateContent); } LlmTemplate _llmTemplateDeserialize( @@ -86,8 +99,9 @@ LlmTemplate _llmTemplateDeserialize( object.chains = reader.readString(offsets[0]); object.createAt = reader.readLong(offsets[1]); object.id = id; - object.name = reader.readString(offsets[2]); - object.template = reader.readString(offsets[3]); + object.name = reader.readString(offsets[3]); + object.template = reader.readString(offsets[4]); + object.templateContent = reader.readString(offsets[5]); return object; } @@ -103,9 +117,13 @@ P _llmTemplateDeserializeProp

( case 1: return (reader.readLong(offset)) as P; case 2: - return (reader.readString(offset)) as P; + return (reader.readLong(offset)) as P; case 3: return (reader.readString(offset)) as P; + case 4: + return (reader.readString(offset)) as P; + case 5: + return (reader.readString(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } @@ -393,6 +411,61 @@ extension LlmTemplateQueryFilter }); } + QueryBuilder hashCodeEqualTo( + int value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'hashCode', + value: value, + )); + }); + } + + QueryBuilder + hashCodeGreaterThan( + int value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'hashCode', + value: value, + )); + }); + } + + QueryBuilder + hashCodeLessThan( + int value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'hashCode', + value: value, + )); + }); + } + + QueryBuilder hashCodeBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'hashCode', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + )); + }); + } + QueryBuilder idEqualTo( Id value) { return QueryBuilder.apply(this, (query) { @@ -711,6 +784,142 @@ extension LlmTemplateQueryFilter )); }); } + + QueryBuilder + templateContentEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'templateContent', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'templateContent', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'templateContent', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + templateContentIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'templateContent', + value: '', + )); + }); + } + + QueryBuilder + templateContentIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'templateContent', + value: '', + )); + }); + } } extension LlmTemplateQueryObject @@ -745,6 +954,18 @@ extension LlmTemplateQuerySortBy }); } + QueryBuilder sortByHashCode() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hashCode', Sort.asc); + }); + } + + QueryBuilder sortByHashCodeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hashCode', Sort.desc); + }); + } + QueryBuilder sortByName() { return QueryBuilder.apply(this, (query) { return query.addSortBy(r'name', Sort.asc); @@ -768,6 +989,19 @@ extension LlmTemplateQuerySortBy return query.addSortBy(r'template', Sort.desc); }); } + + QueryBuilder sortByTemplateContent() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'templateContent', Sort.asc); + }); + } + + QueryBuilder + sortByTemplateContentDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'templateContent', Sort.desc); + }); + } } extension LlmTemplateQuerySortThenBy @@ -796,6 +1030,18 @@ extension LlmTemplateQuerySortThenBy }); } + QueryBuilder thenByHashCode() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hashCode', Sort.asc); + }); + } + + QueryBuilder thenByHashCodeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hashCode', Sort.desc); + }); + } + QueryBuilder thenById() { return QueryBuilder.apply(this, (query) { return query.addSortBy(r'id', Sort.asc); @@ -831,6 +1077,19 @@ extension LlmTemplateQuerySortThenBy return query.addSortBy(r'template', Sort.desc); }); } + + QueryBuilder thenByTemplateContent() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'templateContent', Sort.asc); + }); + } + + QueryBuilder + thenByTemplateContentDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'templateContent', Sort.desc); + }); + } } extension LlmTemplateQueryWhereDistinct @@ -848,6 +1107,12 @@ extension LlmTemplateQueryWhereDistinct }); } + QueryBuilder distinctByHashCode() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'hashCode'); + }); + } + QueryBuilder distinctByName( {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { @@ -861,6 +1126,14 @@ extension LlmTemplateQueryWhereDistinct return query.addDistinctBy(r'template', caseSensitive: caseSensitive); }); } + + QueryBuilder distinctByTemplateContent( + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'templateContent', + caseSensitive: caseSensitive); + }); + } } extension LlmTemplateQueryProperty @@ -883,6 +1156,12 @@ extension LlmTemplateQueryProperty }); } + QueryBuilder hashCodeProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'hashCode'); + }); + } + QueryBuilder nameProperty() { return QueryBuilder.apply(this, (query) { return query.addPropertyName(r'name'); @@ -894,4 +1173,11 @@ extension LlmTemplateQueryProperty return query.addPropertyName(r'template'); }); } + + QueryBuilder + templateContentProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'templateContent'); + }); + } } diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 0dd67d2..4c2014a 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -122,8 +122,7 @@ class _ComposeScreenState extends ConsumerState { _widgetBuilder = (context) => Editor( // jsonString: Future(() => _jsonString), datasource: Datasource( - type: DatasourceType.json, - content: template!.template), + type: DatasourceType.json, content: ""), onEditorStateChange: (editorState) { _editorState = editorState; }, @@ -131,6 +130,24 @@ class _ComposeScreenState extends ConsumerState { ); isTemplateLoaded = true; }); + + Future.delayed(const Duration(milliseconds: 200)).then( + (value) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, + content: template!.template), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + isTemplateLoaded = true; + }); + }, + ); } }, ), diff --git a/lib/llm/editor/models/datasource.dart b/lib/llm/editor/models/datasource.dart index a2588a1..56f2884 100644 --- a/lib/llm/editor/models/datasource.dart +++ b/lib/llm/editor/models/datasource.dart @@ -12,6 +12,14 @@ class Datasource { late String data; + @override + bool operator ==(Object other) { + return other is Datasource && + other.type == type && + other.filepath == filepath && + other.content == content; + } + Datasource( {this.type = DatasourceType.markdown, this.filepath, this.content}) { assert(filepath != null || content != null); @@ -30,4 +38,7 @@ class Datasource { return markdownToDocument(data); } } + + @override + int get hashCode => filepath.hashCode ^ content.hashCode ^ type.hashCode; } diff --git a/lib/llm/global/components/template_item.dart b/lib/llm/global/components/template_item.dart index 15cb477..807a7c1 100644 --- a/lib/llm/global/components/template_item.dart +++ b/lib/llm/global/components/template_item.dart @@ -72,7 +72,7 @@ class _TemplateItemState extends ConsumerState { ), Expanded( flex: 2, - child: Text(widget.template.template, + child: Text(widget.template.templateContent, maxLines: 1, softWrap: true, overflow: TextOverflow.ellipsis, diff --git a/lib/llm/template_editor/template_editor.dart b/lib/llm/template_editor/template_editor.dart index 0d8a1ff..144b21b 100644 --- a/lib/llm/template_editor/template_editor.dart +++ b/lib/llm/template_editor/template_editor.dart @@ -9,6 +9,7 @@ import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; import 'package:all_in_one/llm/template_editor/components/chain_flow.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; +import 'package:all_in_one/llm/template_editor/extension.dart'; import 'package:all_in_one/llm/template_editor/notifiers/chain_flow_notifier.dart'; import 'package:all_in_one/llm/template_editor/notifiers/template_notifier.dart'; // import 'package:all_in_one/src/rust/api/llm_api.dart'; @@ -301,6 +302,7 @@ class _TemplateEditorState extends ConsumerState { .read(templateNotifierProvider.notifier) .addTemplate( LlmTemplate() + ..templateContent = _editorState.toStr2() ..chains = itemStr ..template = jsonEncode(_editorState.document.toJson()) @@ -328,6 +330,7 @@ class _TemplateEditorState extends ConsumerState { .read(templateNotifierProvider.notifier) .addTemplate( LlmTemplate() + ..templateContent = _editorState.toStr2() ..chains = itemStr ..template = jsonEncode(_editorState.document.toJson()) From 39eb92223da09375466b45d49341301ffba99da4 Mon Sep 17 00:00:00 2001 From: xiaoshuyui <528490652@qq.com> Date: Tue, 28 May 2024 22:18:17 +0800 Subject: [PATCH 14/16] feat: change mind map item --- lib/llm/editor/compose_screen.dart | 2 + lib/llm/plugins/mind_map.dart | 61 ++++------------------ lib/llm/plugins/models/mind_map_model.dart | 4 +- pubspec.lock | 4 +- pubspec.yaml | 2 +- 5 files changed, 17 insertions(+), 56 deletions(-) diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 4c2014a..8e053fc 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -286,6 +286,8 @@ class _ComposeScreenState extends ConsumerState { startOffset: 0, endOffset: 0); _editorState.insertImageNode(p0); + ToastUtils.sucess(context, + title: "image added"); }, ), ); diff --git a/lib/llm/plugins/mind_map.dart b/lib/llm/plugins/mind_map.dart index b4a5206..da4f7e1 100644 --- a/lib/llm/plugins/mind_map.dart +++ b/lib/llm/plugins/mind_map.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; @@ -10,8 +11,8 @@ import 'dart:ui' as ui; import 'package:path_provider/path_provider.dart'; import 'package:uuid/uuid.dart'; -const elementSize = Size(200, 50); -const elementKind = ElementKind.rectangle; +const elementSize = Size(200, 100); +const elementKind = ElementKind.mindMap; const elementFontSize = 14.0; const Offset rootOffset = Offset(100, 100); @@ -24,10 +25,14 @@ extension ToMindMap on Dashboard { for (final i in flattenedOffset) { final felement = FlowElement( - text: i['value'] ?? "unknow", + text: jsonEncode({ + "node": i['value'] ?? "unknow subject", + "description": i['description'] ?? "invalid description" + }), textSize: elementFontSize, size: elementSize, kind: elementKind, + handlers: [Handler.leftCenter, Handler.rightCenter], position: i['offset'] ?? rootOffset); felement.setId(i["uuid"]); addElement(felement); @@ -72,8 +77,6 @@ class DashboardFromMap extends StatefulWidget { class _DashboardFromMapState extends State { Dashboard dashboard = Dashboard(); - // ignore: avoid_init_to_null - OverlayEntry? _overlayEntry = null; late List<(String, String)> descs; @@ -85,39 +88,6 @@ class _DashboardFromMapState extends State { }); } - @override - void dispose() { - _removeOverlay(); - super.dispose(); - } - - void _showOverlay(Offset offset, String content) { - _overlayEntry = OverlayEntry(builder: (ctx) { - return Positioned( - left: offset.dx, - top: offset.dy, - child: Material( - elevation: 10, - borderRadius: BorderRadius.circular(10), - child: FittedBox( - child: Container( - width: 300, - padding: const EdgeInsets.all(20), - decoration: - BoxDecoration(borderRadius: BorderRadius.circular(10)), - child: Text(content), - ), - ), - )); - }); - Overlay.of(context).insert(_overlayEntry!); - } - - void _removeOverlay() { - _overlayEntry?.remove(); - _overlayEntry = null; - } - @override Widget build(BuildContext context) { return Stack( @@ -133,20 +103,7 @@ class _DashboardFromMapState extends State { constraints: const BoxConstraints.expand(), child: FlowChart( dashboard: dashboard, - onDashboardTapped: ((context, position) { - _removeOverlay(); - }), - onElementPressed: (context, position, element) { - final s = descs - .where( - (e) => e.$1 == element.id, - ) - .firstOrNull; - if (s == null || s.$2 == "") { - return; - } - _showOverlay(position, s.$2); - }, + onDashboardTapped: ((context, position) {}), ), ), ), diff --git a/lib/llm/plugins/models/mind_map_model.dart b/lib/llm/plugins/models/mind_map_model.dart index 86e0a6b..7e8b33d 100644 --- a/lib/llm/plugins/models/mind_map_model.dart +++ b/lib/llm/plugins/models/mind_map_model.dart @@ -2,7 +2,7 @@ import 'dart:ui'; import 'package:uuid/uuid.dart'; -const nodeHeight = 50.0; +const nodeHeight = 100.0; const nodeWidth = 300.0; const gap = 20.0; @@ -58,6 +58,7 @@ class MindMapData { "parentUuid": parentUuid }); if (node.subNodes != null) { + /// FIXME 有时候element会有重叠的情况 for (int i = 0; i < node.subNodes!.length; i++) { Offset childOffset = Offset(currentOffset.dx + nodeWidth * (1), currentOffset.dy + (gap + nodeHeight) * (i + 1)); @@ -79,6 +80,7 @@ class MindMapData { }); // 检查是否有子节点且不为空,若有则继续递归;若无,则已到达叶子节点,停止递归 if (node.subNodes != null && node.subNodes!.isNotEmpty) { + /// FIXME 有时候element会有重叠的情况 for (int i = 0; i < node.subNodes!.length; i++) { Offset childOffset = Offset(currentOffset.dx + nodeWidth * (1), currentOffset.dy + (gap + nodeHeight) * (i + 1)); diff --git a/pubspec.lock b/pubspec.lock index 5ad9c26..c67be38 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -537,8 +537,8 @@ packages: dependency: "direct main" description: path: "." - ref: connection-listener - resolved-ref: "62f997459a5458578cdd34569e84d19e92b1079a" + ref: "v0.0.1" + resolved-ref: "942d7aa0787c669e6899e03e44ff0ff69dfb4e90" url: "https://github.com/guchengxi1994/flutter_flow_chart" source: git version: "3.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index e01f4de..b64f23e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -38,7 +38,7 @@ dependencies: flutter_flow_chart: git: url: https://github.com/guchengxi1994/flutter_flow_chart - ref: connection-listener + ref: v0.0.1 flutter_layout_grid: ^2.0.6 flutter_math_fork: ^0.7.2 flutter_riverpod: ^2.5.1 From 7525ca4fd8b8d4a24edc705202a296a9c6f1e35e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A3=B9=E9=9B=B6?= Date: Wed, 29 May 2024 11:16:10 +0800 Subject: [PATCH 15/16] =?UTF-8?q?fix:=20=E6=9C=89=E6=97=B6=E5=80=99element?= =?UTF-8?q?=E4=BC=9A=E6=9C=89=E9=87=8D=E5=8F=A0=E7=9A=84=E6=83=85=E5=86=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + langchain_lib/test/.gitignore | 1 + lib/llm/plugins/models/mind_map_model.dart | 37 ++++++++++++++++++---- 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 langchain_lib/test/.gitignore diff --git a/README.md b/README.md index 54ef93b..7f0abf7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # all_in_one > this project is just for fun, a lot of features are not stable and not usable. +> only tested on `kimi` and `langchain` ### how to run diff --git a/langchain_lib/test/.gitignore b/langchain_lib/test/.gitignore new file mode 100644 index 0000000..7b467ff --- /dev/null +++ b/langchain_lib/test/.gitignore @@ -0,0 +1 @@ +test_local.dart \ No newline at end of file diff --git a/lib/llm/plugins/models/mind_map_model.dart b/lib/llm/plugins/models/mind_map_model.dart index 7e8b33d..f5fd413 100644 --- a/lib/llm/plugins/models/mind_map_model.dart +++ b/lib/llm/plugins/models/mind_map_model.dart @@ -46,6 +46,8 @@ class MindMapData { int parentIndex, Offset currentOffset, String parentUuid) { + Map levelIndexMap = {}; + if (node is MindMapData) { String nodeUuid = const Uuid().v4(); flatList.add({ @@ -57,11 +59,23 @@ class MindMapData { "uuid": nodeUuid, "parentUuid": parentUuid }); + if (levelIndexMap[level] == null) { + levelIndexMap[level] = 0; + } else { + levelIndexMap[level] = levelIndexMap[level]! + 1; + } + if (node.subNodes != null) { - /// FIXME 有时候element会有重叠的情况 for (int i = 0; i < node.subNodes!.length; i++) { - Offset childOffset = Offset(currentOffset.dx + nodeWidth * (1), - currentOffset.dy + (gap + nodeHeight) * (i + 1)); + if (levelIndexMap[level + 1] == null) { + levelIndexMap[level + 1] = 0; + } else { + levelIndexMap[level + 1] = levelIndexMap[level + 1]! + 1; + } + Offset childOffset = Offset( + currentOffset.dx + nodeWidth * (1), + currentOffset.dy + + (gap + nodeHeight) * (levelIndexMap[level + 1]! + 1)); _flattenWithOffsetAndIndex(node.subNodes![i], flatList, level + 1, i, childOffset - const Offset(0, (gap + nodeHeight)), nodeUuid); } @@ -78,12 +92,23 @@ class MindMapData { "uuid": nodeUuid, "parentUuid": parentUuid }); + if (levelIndexMap[level] == null) { + levelIndexMap[level] = 0; + } else { + levelIndexMap[level] = levelIndexMap[level]! + 1; + } // 检查是否有子节点且不为空,若有则继续递归;若无,则已到达叶子节点,停止递归 if (node.subNodes != null && node.subNodes!.isNotEmpty) { - /// FIXME 有时候element会有重叠的情况 + if (levelIndexMap[level + 1] == null) { + levelIndexMap[level + 1] = 0; + } else { + levelIndexMap[level + 1] = levelIndexMap[level + 1]! + 1; + } for (int i = 0; i < node.subNodes!.length; i++) { - Offset childOffset = Offset(currentOffset.dx + nodeWidth * (1), - currentOffset.dy + (gap + nodeHeight) * (i + 1)); + Offset childOffset = Offset( + currentOffset.dx + nodeWidth * (1), + currentOffset.dy + + (gap + nodeHeight) * (levelIndexMap[level + 1]! + 1)); _flattenWithOffsetAndIndex(node.subNodes![i], flatList, level + 1, i, childOffset - const Offset(0, (gap + nodeHeight)), nodeUuid); } From aa7536d51603e88a05a9377dba06655d9fce076a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A3=B9=E9=9B=B6?= Date: Wed, 29 May 2024 11:47:00 +0800 Subject: [PATCH 16/16] chore: remove some codes --- lib/llm/editor/components/article_item.dart | 74 ++++++ .../components/load_article_dialog.dart | 77 ++++++ lib/llm/editor/compose_screen.dart | 85 ++++++- .../editor/notifiers/article_notifier.dart | 31 +++ lib/llm/template_editor/template_editor.dart | 230 ++++-------------- pubspec.yaml | 2 +- 6 files changed, 310 insertions(+), 189 deletions(-) create mode 100644 lib/llm/editor/components/article_item.dart create mode 100644 lib/llm/editor/components/load_article_dialog.dart create mode 100644 lib/llm/editor/notifiers/article_notifier.dart diff --git a/lib/llm/editor/components/article_item.dart b/lib/llm/editor/components/article_item.dart new file mode 100644 index 0000000..f02d944 --- /dev/null +++ b/lib/llm/editor/components/article_item.dart @@ -0,0 +1,74 @@ +import 'package:all_in_one/isar/article.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +typedef OnArticleSelected = void Function(Article); + +class ArticleItem extends ConsumerStatefulWidget { + const ArticleItem( + {super.key, required this.article, required this.onArticleSelected}); + final Article article; + final OnArticleSelected onArticleSelected; + + @override + ConsumerState createState() => _ArticleItemState(); +} + +class _ArticleItemState extends ConsumerState { + bool isHovering = false; + + @override + Widget build(BuildContext context) { + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (event) { + setState(() { + isHovering = true; + }); + }, + onExit: (event) { + setState(() { + isHovering = false; + }); + }, + child: GestureDetector( + onTap: () { + widget.onArticleSelected(widget.article); + }, + child: Container( + height: 40, + decoration: BoxDecoration( + color: isHovering + ? const Color.fromARGB(255, 197, 195, 227).withAlpha(100) + : Colors.transparent, + borderRadius: BorderRadius.circular(5)), + child: Row( + children: [ + Expanded( + flex: 1, + child: Text( + widget.article.title, + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis, + ), + ), + Expanded( + flex: 1, + child: Text( + DateTime.fromMillisecondsSinceEpoch(widget.article.createAt) + .toString() + .split(".") + .first, + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/llm/editor/components/load_article_dialog.dart b/lib/llm/editor/components/load_article_dialog.dart new file mode 100644 index 0000000..4a57390 --- /dev/null +++ b/lib/llm/editor/components/load_article_dialog.dart @@ -0,0 +1,77 @@ +import 'package:all_in_one/llm/editor/components/article_item.dart'; +import 'package:all_in_one/llm/editor/notifiers/article_notifier.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +class LoadArticleDialog extends ConsumerStatefulWidget { + const LoadArticleDialog({super.key}); + + @override + ConsumerState createState() => _LoadArticleDialogState(); +} + +class _LoadArticleDialogState extends ConsumerState { + @override + Widget build(BuildContext context) { + final state = ref.watch(articleProvider); + + return Material( + elevation: 10, + borderRadius: BorderRadius.circular(20), + child: Container( + padding: const EdgeInsets.all(20), + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)), + child: state.when( + data: (v) { + if (v.isEmpty) { + return const Center( + child: Text("There is no template created."), + ); + } + + return Column( + children: [ + const SizedBox( + height: 50, + child: Row( + children: [ + Expanded( + flex: 1, + child: Text("name"), + ), + Expanded( + flex: 1, + child: Text("create at"), + ) + ], + ), + ), + Expanded( + child: ListView.builder( + itemBuilder: (c, i) { + return ArticleItem( + article: v[i], + onArticleSelected: (p0) { + Navigator.of(context).pop(p0); + }, + ); + }, + itemCount: v.length, + )), + ], + ); + }, + error: (_, s) { + return Center( + child: Text(s.toString()), + ); + }, + loading: () => const Center( + child: CircularProgressIndicator(), + )), + ), + ); + } +} diff --git a/lib/llm/editor/compose_screen.dart b/lib/llm/editor/compose_screen.dart index 8e053fc..62c70d9 100644 --- a/lib/llm/editor/compose_screen.dart +++ b/lib/llm/editor/compose_screen.dart @@ -4,10 +4,13 @@ import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; +import 'package:all_in_one/isar/article.dart'; import 'package:all_in_one/isar/llm_history.dart'; import 'package:all_in_one/isar/llm_template.dart'; import 'package:all_in_one/llm/ai_client.dart'; +import 'package:all_in_one/llm/editor/components/load_article_dialog.dart'; import 'package:all_in_one/llm/editor/models/datasource.dart'; +import 'package:all_in_one/llm/editor/notifiers/article_notifier.dart'; import 'package:all_in_one/llm/global/components/load_template_dialog.dart'; import 'package:all_in_one/llm/global/components/loading_dialog.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; @@ -93,12 +96,90 @@ class _ComposeScreenState extends ConsumerState { SidemenuButton( icon: Icons.file_open_outlined, title: "Load last", - onTap: () {}, + onTap: () async { + final Article? article = + await ref.read(articleProvider.notifier).getLast(); + if (article != null) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, content: ""), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + isTemplateLoaded = true; + }); + + Future.delayed(const Duration(milliseconds: 200)).then( + (value) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, + content: article.content), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + isTemplateLoaded = true; + }); + }, + ); + } + }, ), SidemenuButton( icon: Icons.file_open, title: "Load article...", - onTap: () {}, + onTap: () async { + final Article? article = await showGeneralDialog( + barrierColor: Colors.transparent, + barrierDismissible: true, + barrierLabel: "load-article", + context: context, + pageBuilder: (c, _, __) { + return const Center( + child: LoadArticleDialog(), + ); + }); + if (article != null) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, content: ""), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + isTemplateLoaded = true; + }); + + Future.delayed(const Duration(milliseconds: 200)).then( + (value) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, + content: article.content), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: false, + ); + isTemplateLoaded = true; + }); + }, + ); + } + }, ), SidemenuDivider(), SidemenuLabel(title: "Template"), diff --git a/lib/llm/editor/notifiers/article_notifier.dart b/lib/llm/editor/notifiers/article_notifier.dart new file mode 100644 index 0000000..595ff3d --- /dev/null +++ b/lib/llm/editor/notifiers/article_notifier.dart @@ -0,0 +1,31 @@ +import 'dart:async'; + +import 'package:all_in_one/isar/article.dart'; +import 'package:all_in_one/isar/database.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:isar/isar.dart'; + +class ArticleNotifier extends AutoDisposeAsyncNotifier> { + final IsarDatabase isarDatabase = IsarDatabase(); + + @override + FutureOr> build() async { + final articles = await isarDatabase.isar!.articles + .where() + .sortByCreateAtDesc() + .findAll(); + return articles; + } + + Future getLast() async { + return await isarDatabase.isar!.articles + .where() + .sortByCreateAtDesc() + .findFirst(); + } +} + +final articleProvider = + AutoDisposeAsyncNotifierProvider>(() { + return ArticleNotifier(); +}); diff --git a/lib/llm/template_editor/template_editor.dart b/lib/llm/template_editor/template_editor.dart index 144b21b..d821238 100644 --- a/lib/llm/template_editor/template_editor.dart +++ b/lib/llm/template_editor/template_editor.dart @@ -4,6 +4,7 @@ import 'dart:convert'; import 'package:all_in_one/common/toast_utils.dart'; import 'package:all_in_one/isar/llm_template.dart'; +import 'package:all_in_one/llm/global/components/load_template_dialog.dart'; import 'package:all_in_one/llm/global/components/sidemenu.dart'; import 'package:all_in_one/llm/global/components/sidemenu_widget.dart'; import 'package:all_in_one/llm/langchain/notifiers/tool_notifier.dart'; @@ -82,30 +83,6 @@ class _TemplateEditorState extends ConsumerState { }, showTemplateFeatures: true, ); - - /// FIXME - /// 返回的都是全文, - /// 如果是stream的返回方式 - /// 最好每次只返回最后的内容,不需要全文返回 - // stream.listen((event) { - // // print(event.response); - // for (final i in _editorState.document.root.children) { - // if ((i.attributes['delta'] as List).isNotEmpty) { - // // Node? existsNode = null; - // Map? map = null; - // for (int j = 0; j < i.attributes['delta'].length; j++) { - // if (i.attributes['delta'][j]["insert"] != null && - // i.attributes['delta'][j]["insert"].contains(event.prompt)) { - // map = i.attributes; - // map['delta'][j]['insert'] = event.prompt + event.response; - // } - // } - // if (map != null) { - // i.updateAttributes(map); - // } - // } - // } - // }); } final GlobalKey key = GlobalKey(); @@ -116,167 +93,6 @@ class _TemplateEditorState extends ConsumerState { return Scaffold( key: key, endDrawer: const ChainFlow(), - // floatingActionButtonLocation: ExpandableFab.location, - // floatingActionButton: ExpandableFab( - // distance: 50, - // type: ExpandableFabType.side, - // children: [ - // FloatingActionButton.small( - // tooltip: "chain viewer", - // heroTag: "", - // onPressed: () { - // if (ref.read(chainFlowProvider).items.flowItems.isEmpty) { - // return; - // } - - // if (key.currentState!.isEndDrawerOpen) { - // key.currentState!.closeEndDrawer(); - // } else { - // key.currentState!.openEndDrawer(); - // } - // }, - // child: const Icon(Bootstrap.view_list), - // ), - // FloatingActionButton.small( - // tooltip: "chain designer", - // heroTag: "", - // onPressed: () { - // ref - // .read(chainFlowProvider.notifier) - // .changeContent(jsonEncode(_editorState.document.toJson())); - - // showGeneralDialog( - // context: context, - // barrierColor: Colors.transparent, - // barrierLabel: "chain-flow", - // barrierDismissible: true, - // pageBuilder: (c, _, __) { - // return const Center( - // child: ChainFlowDesigner(), - // ); - // }); - // }, - // child: const Icon(Bootstrap.magic), - // ), - // FloatingActionButton.small( - // tooltip: "save template", - // heroTag: "", - // onPressed: () async { - // // print(_editorState.document.toJson()); - // final String? r = await showGeneralDialog( - // context: context, - // barrierDismissible: true, - // barrierColor: Colors.transparent, - // barrierLabel: "new-template", - // pageBuilder: (c, _, __) { - // return const Center( - // child: NewTemplateDialog(), - // ); - // }); - - // if (r != null) { - // ref - // .read(templateNotifierProvider.notifier) - // .addTemplate(LlmTemplate() - // ..template = jsonEncode(_editorState.document.toJson()) - // ..name = r); - // } - // }, - // child: const Icon(Bootstrap.download), - // ), - // FloatingActionButton.small( - // tooltip: "load template", - // heroTag: "", - // onPressed: () async {}, - // child: const Icon(Bootstrap.files), - // ), - // // FloatingActionButton.small( - // // tooltip: "generate from template", - // // heroTag: null, - // // child: const Icon(Bootstrap.file_word), - // // onPressed: () async { - // // if (widget.enablePlugin) { - // // // 存一份数据 - // // RecordUtils.putNewMessage( - // // MessageType.query, _editorState.toStr()); - // // } - // // ref - // // .read(chainFlowProvider.notifier) - // // .changeContent(jsonEncode(_editorState.document.toJson())); - // // final l = await ref.read(chainFlowProvider.notifier).toRust(); - - // // showGeneralDialog( - // // barrierDismissible: false, - // // barrierColor: Colors.transparent, - // // // ignore: use_build_context_synchronously - // // context: context, - // // pageBuilder: (c, _, __) { - // // return const LoadingDialog(); - // // }).then((_) async { - // // if (widget.enablePlugin) { - // // // 存一份数据 - // // RecordUtils.putNewMessage( - // // MessageType.response, _editorState.toStr()); - // // } - // // }); - - // // generateFromTemplate(v: l, enablePlugin: true) - // // .then((value) async { - // // final md = await optimizeDoc(s: _editorState.toStr()); - // // setState( - // // () { - // // _widgetBuilder = (context) => Editor( - // // datasource: Datasource( - // // type: DatasourceType.markdown, - // // content: md, - // // ), - // // onEditorStateChange: (editorState) { - // // _editorState = editorState; - // // }, - // // showTemplateFeatures: true, - // // ); - // // }, - // // ); - // // }); - // // }, - // // ), - // // FloatingActionButton.small( - // // tooltip: "test-chain", - // // heroTag: null, - // // child: const Icon(Bootstrap.activity), - // // onPressed: () async { - // // String s = jsonEncode(_editorState.document.toJson()); - // // if (widget.enablePlugin) { - // // // 存一份数据 - // // RecordUtils.putNewMessage( - // // MessageType.query, _editorState.toStr()); - // // } - // // final res = await templateRenderer(template: s); - // // if (res != null) { - // // _jsonString = jsonEncode(jsonDecode(res)); - - // // setState(() { - // // _editorState = - // // EditorState(document: Document.fromJson(jsonDecode(res))); - // // }); - // // if (widget.enablePlugin) { - // // // 存一份数据 - // // RecordUtils.putNewMessage( - // // MessageType.response, _editorState.toStr()); - // // } - // // } - // // }, - // // ), - // FloatingActionButton.small( - // tooltip: "back", - // heroTag: "", - // onPressed: () { - // ref.read(toolProvider.notifier).jumpTo(0); - // }, - // child: const Icon(Icons.chevron_left), - // ), - // ], - // ), extendBodyBehindAppBar: PlatformExtension.isDesktopOrWeb, body: SafeArea( child: Row( @@ -287,7 +103,49 @@ class _TemplateEditorState extends ConsumerState { SidemenuButton( icon: EvaIcons.file_text, title: "Load Template", - onTap: () {}, + onTap: () async { + final LlmTemplate? template = await showGeneralDialog( + barrierColor: Colors.transparent, + barrierDismissible: true, + barrierLabel: "load-template", + context: context, + pageBuilder: (c, _, __) { + return const Center( + child: LoadTemplateDialog(), + ); + }); + + if (template != null) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, content: ""), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: true, + ); + }); + + Future.delayed(const Duration(milliseconds: 200)).then( + (value) { + setState(() { + _widgetBuilder = (context) => Editor( + // jsonString: Future(() => _jsonString), + datasource: Datasource( + type: DatasourceType.json, + content: template.template), + onEditorStateChange: (editorState) { + _editorState = editorState; + }, + showTemplateFeatures: true, + ); + }); + }, + ); + } + }, ), SidemenuButton( icon: EvaIcons.save, diff --git a/pubspec.yaml b/pubspec.yaml index b64f23e..a447ab2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: all_in_one description: "A new Flutter project." publish_to: 'none' # Remove this line if you wish to publish to pub.dev -version: 0.0.9 +version: 0.0.10 environment: sdk: '>=3.3.0 <4.0.0'