Skip to content

Commit

Permalink
optimize search
Browse files Browse the repository at this point in the history
  • Loading branch information
guanyiyao committed Feb 21, 2025
1 parent e8582de commit 2188011
Show file tree
Hide file tree
Showing 9 changed files with 275 additions and 70 deletions.
3 changes: 3 additions & 0 deletions lib/bloc/chat_message_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,9 @@ class ChatMessageBloc extends BlocExt<ChatMessageEvent, ChatMessageState> {
case 'reference-documents':
waitMessage.updateExtra({'reference-documents': cmd['data']});
break;
case 'search-results':
waitMessage.updateExtra({'search-results': cmd['data']});
break;
default:
}
} catch (e) {
Expand Down
5 changes: 4 additions & 1 deletion lib/lang/lang.dart
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ mixin AppLocale {
static const String startChat = 'start-chat';
static const String updateApp = 'update-app';
static const String notUpdateApp = 'not-update-app';
static const String searchedXWebPages = 'searched-x-web-pages';

static const Map<String, dynamic> zh = {
wechat: '微信',
Expand Down Expand Up @@ -681,6 +682,7 @@ mixin AppLocale {
startChat: '开始对话',
updateApp: '去更新',
notUpdateApp: '暂不更新',
searchedXWebPages: '已搜索到 %s 个网页',
};

static const Map<String, dynamic> en = {
Expand Down Expand Up @@ -721,7 +723,7 @@ mixin AppLocale {
text: 'Text',
uploading: 'Uploading...',
robotIsThinkingMessage: 'Thinking...',
thinkingProcess: 'Thinking, please be patient',
thinkingProcess: 'Deep thought',
robotHasSomeError: 'There seems to be something wrong, Do you want to resend the message?',
appName: 'AIdea',
chatAnywhere: 'Chat',
Expand Down Expand Up @@ -1019,6 +1021,7 @@ mixin AppLocale {
startChat: 'Start Chat',
updateApp: 'Update Now',
notUpdateApp: 'Not Update',
searchedXWebPages: 'Searched %s web pages',
};
}

Expand Down
10 changes: 5 additions & 5 deletions lib/page/admin/models_add.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class _AdminModelCreatePageState extends State<AdminModelCreatePage> {
/// 温度
double temperature = 0.0;
// 搜索结果数量
int searchCount = 0;
int searchCount = 3;

/// Tag
final TextEditingController tagController = TextEditingController();
Expand Down Expand Up @@ -934,10 +934,10 @@ class _AdminModelCreatePageState extends State<AdminModelCreatePage> {
children: [
Expanded(
child: Slider(
value: searchCount.toDouble(),
min: 0,
max: 5,
divisions: 5,
value: searchCount.toDouble() <= 3 ? 3.0 : searchCount.toDouble(),
min: 3,
max: 50,
divisions: 50 - 3,
label: '$searchCount',
activeColor: customColors.linkColor,
onChanged: (value) {
Expand Down
13 changes: 7 additions & 6 deletions lib/page/admin/models_edit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class _AdminModelEditPageState extends State<AdminModelEditPage> {
/// 温度
double temperature = 0.0;
// 搜索结果数量
int searchCount = 0;
int searchCount = 3;

/// Tag
final TextEditingController tagController = TextEditingController();
Expand Down Expand Up @@ -236,7 +236,8 @@ class _AdminModelEditPageState extends State<AdminModelEditPage> {
enableSearch = state.model.meta!.search ?? false;
enableReasoning = state.model.meta!.reasoning ?? false;
temperature = state.model.meta!.temperature ?? 0.0;
searchCount = state.model.meta!.searchCount ?? 0;
searchCount = state.model.meta!.searchCount ?? 3;
searchCount = searchCount <= 3 ? 3 : searchCount;

setState(() {});
}
Expand Down Expand Up @@ -1005,10 +1006,10 @@ class _AdminModelEditPageState extends State<AdminModelEditPage> {
children: [
Expanded(
child: Slider(
value: searchCount.toDouble(),
min: 0,
max: 5,
divisions: 5,
value: searchCount.toDouble() <= 3 ? 3.0 : searchCount.toDouble(),
min: 3,
max: 50,
divisions: 50 - 3,
label: '$searchCount',
activeColor: customColors.linkColor,
onChanged: (value) {
Expand Down
37 changes: 34 additions & 3 deletions lib/page/component/chat/chat_preview.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:askaide/page/component/chat/chat_share.dart';
import 'package:askaide/page/component/chat/enhanced_selectable_text.dart';
import 'package:askaide/page/component/chat/file_upload.dart';
import 'package:askaide/page/component/chat/message_state_manager.dart';
import 'package:askaide/page/component/chat/search_result.dart';
import 'package:askaide/page/component/chat/thinking_card.dart';
import 'package:askaide/page/component/dialog.dart';
import 'package:askaide/page/component/file_preview.dart';
Expand Down Expand Up @@ -215,6 +216,15 @@ class _ChatPreviewState extends State<ChatPreview> {
referenceDocuments = [];
}

var searchResults = <ReferenceDocument>[];
try {
final searchResultsData = extra != null ? extra['search-results'] ?? '[]' : '[]';
final List<dynamic> decodedDocs = jsonDecode(searchResultsData);
searchResults = decodedDocs.map((e) => ReferenceDocument.fromJson(e)).toList().cast<ReferenceDocument>();
} catch (e) {
print('------------> $e <-----------');
}

final stateWidgets = <Widget>[];

if (states.isNotEmpty) {
Expand Down Expand Up @@ -353,10 +363,18 @@ class _ChatPreviewState extends State<ChatPreview> {
if (message.role == Role.sender && message.statusIsFailed())
buildErrorIndicator(message, state, context, index),

// 搜索结果
if (searchResults.isNotEmpty)
Container(
margin: const EdgeInsets.only(left: 10, top: 10),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: SearchResult(searchResults: searchResults),
),

// 消息过程状态
if (states.isNotEmpty)
Container(
margin: const EdgeInsets.only(left: 10),
margin: EdgeInsets.only(left: 10, top: searchResults.isEmpty ? 10 : 0),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Column(
mainAxisSize: MainAxisSize.min,
Expand Down Expand Up @@ -441,6 +459,7 @@ class _ChatPreviewState extends State<ChatPreview> {
? Markdown(
data: text.trim(),
onUrlTap: (value) => onMarkdownUrlTap(value),
citations: searchResults.map((e) => e.source).toList(),
)
: SelectableText(
text,
Expand Down Expand Up @@ -1099,14 +1118,26 @@ class ReferenceDocument {
final String title;
final String source;
final String content;

ReferenceDocument({required this.title, required this.source, required this.content});
final String media;
final String icon;
final String index;

ReferenceDocument(
{required this.title,
required this.source,
required this.content,
required this.media,
required this.icon,
required this.index});

static fromJson(Map<String, dynamic> json) {
return ReferenceDocument(
title: json['title'] ?? '',
source: json['source'] ?? '',
content: json['content'] ?? '',
media: json['media'] ?? '',
icon: json['icon'] ?? '',
index: json['index'] ?? '',
);
}
}
Expand Down
25 changes: 9 additions & 16 deletions lib/page/component/chat/markdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ class Markdown extends StatelessWidget {
final TextStyle? textStyle;
final cacheManager = DefaultCacheManager();

final List<String> citations;

Markdown({
super.key,
required this.data,
this.onUrlTap,
this.textStyle,
this.citations = const [],
});

@override
Expand All @@ -45,6 +48,7 @@ class Markdown extends StatelessWidget {
return md.MarkdownBody(
shrinkWrap: true,
selectable: false,
softLineBreak: true,
styleSheetTheme: md.MarkdownStyleSheetBaseTheme.material,
styleSheet: md.MarkdownStyleSheet(
p: textStyle ?? TextStyle(fontSize: CustomSize.markdownTextSize, height: 1.5),
Expand All @@ -56,24 +60,12 @@ class Markdown extends StatelessWidget {
),
codeblockPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
codeblockDecoration: const BoxDecoration(borderRadius: CustomSize.borderRadiusAll),
tableBorder: TableBorder.all(
color: customColors.weakTextColor!.withOpacity(0.5),
width: 1,
),
tableBorder: TableBorder.all(color: customColors.weakTextColor!.withOpacity(0.5), width: 1),
tableColumnWidth: const FlexColumnWidth(),
blockquotePadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide(
color: customColors.weakTextColor!.withOpacity(0.4),
width: 4,
),
),
),
a: TextStyle(
color: customColors.linkColor,
decoration: TextDecoration.none,
),
border: Border(left: BorderSide(color: customColors.weakTextColor!.withOpacity(0.4), width: 4))),
a: TextStyle(color: customColors.weakLinkColor, decoration: TextDecoration.none),
),
onTapLink: (text, href, title) {
if (onUrlTap != null && href != null) onUrlTap!(href);
Expand All @@ -94,16 +86,17 @@ class Markdown extends StatelessWidget {
LatexBlockSyntax(),
],
<mm.InlineSyntax>[
CitationSyntax(citations: citations),
mm.EmojiSyntax(),
...mm.ExtensionSet.gitHubFlavored.inlineSyntaxes,
LatexInlineSyntax(),
CitationSyntax(),
],
),
data: data,
builders: {
'code': CodeElementBuilder(customColors),
'latex': LatexElementBuilder(),
'citation': CitationBuilder(onTap: onUrlTap),
},
);
}
Expand Down
79 changes: 45 additions & 34 deletions lib/page/component/chat/markdown/citation.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import 'package:askaide/page/component/theme/custom_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;

class CitationSyntax extends md.InlineSyntax {
CitationSyntax() : super('\\[citation:(\\d+)\\]');
final List<String> citations;

CitationSyntax({required this.citations}) : super('(?:\\[|【)\\s*citation\\s*:\\s*(\\d+)\\s*(?:\\]|】)');

@override
bool onMatch(md.InlineParser parser, Match match) {
final num = match[1]!;
parser.addNode(md.Text(' ${_getNumberEmoji(num)}'));
final node = md.Text(num);

try {
final el = md.Element('citation', [node]);
el.attributes['href'] = citations[int.parse(num) - 1];
parser.addNode(el);
} catch (e) {
parser.addNode(md.Element('citation', [node]));
}

return true;
}
Expand All @@ -28,45 +39,45 @@ class CitationBuilder extends MarkdownElementBuilder {
TextStyle? preferredStyle,
TextStyle? parentStyle,
) {
final customColors = Theme.of(context).extension<CustomColors>()!;
final String text = element.textContent;
if (text.isEmpty) {
return const SizedBox();
}

final href = element.attributes['href'];

if (citationPattern.hasMatch(text)) {
final num = text.replaceAll('citation:', '');
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () => onTap?.call(href!),
child: Text(_getNumberEmoji(num)),
),
);
}

return MouseRegion(
cursor: SystemMouseCursors.click,
child: InkWell(
onTap: () => onTap?.call(href!),
child: Text(text, style: preferredStyle),
return RichText(
text: TextSpan(
children: [
WidgetSpan(
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
if (href != null) {
onTap?.call(href);
}
},
child: Container(
margin: const EdgeInsets.only(left: 4),
decoration: BoxDecoration(
color: customColors.weakTextColorLess,
shape: BoxShape.circle,
),
padding: const EdgeInsets.all(4),
child: Text(
text,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
),
),
)
],
),
);
}
}

String _getNumberEmoji(String num) {
return switch (num) {
'1' => '①',
'2' => '②',
'3' => '③',
'4' => '④',
'5' => '⑤',
'6' => '⑥',
'7' => '⑦',
'8' => '⑧',
'9' => '⑨',
_ => num,
};
}
Loading

0 comments on commit 2188011

Please sign in to comment.