优化ai userid和markdown

This commit is contained in:
mmc
2026-03-17 10:54:33 +08:00
parent 14df0bc041
commit f952756f40
6 changed files with 215 additions and 227 deletions

View File

@@ -4,13 +4,16 @@ import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import 'ai_state.dart';
import '../../data/models/chat_message.dart';
import '../../data/models/session.dart';
class AiCubit extends Cubit<AiState> {
AiCubit() : super(const AiState()) {
final AppUserCubit appUserCubit;
AiCubit({required this.appUserCubit}) : super(const AiState()) {
createNewSession();
fetchSessions();
}
@@ -18,7 +21,8 @@ class AiCubit extends Cubit<AiState> {
final Dio _dio = Dio();
final ImagePicker _picker = ImagePicker();
static const String BASE_URL = 'http://1.95.137.212:30009';
final String _userId = '1';
String get _userId => appUserCubit.state.user?.userId ?? '1';
//final String _userId = '1';
Future<void> fetchSessions() async {
try {
@@ -33,13 +37,15 @@ class AiCubit extends Cubit<AiState> {
}
void createNewSession() {
emit(AiState(
sessionId: DateTime.now().millisecondsSinceEpoch.toString(),
messages: [ChatMessage(text: "快来和我一起探讨吧!", isUserMessage: false)],
status: AiStatus.initial,
selectedImageFile: null, // Explicitly set to null
sessions: state.sessions, // Preserve existing sessions
));
emit(
AiState(
sessionId: DateTime.now().millisecondsSinceEpoch.toString(),
messages: [ChatMessage(text: "快来和我一起探讨吧!", isUserMessage: false)],
status: AiStatus.initial,
selectedImageFile: null, // Explicitly set to null
sessions: state.sessions, // Preserve existing sessions
),
);
}
Future<void> loadSessionHistory(String sessionId) async {
@@ -61,7 +67,7 @@ class AiCubit extends Cubit<AiState> {
}
} catch (e) {
emit(state.copyWith(status: AiStatus.failure, error: "Failed to load session history: $e"));
}
}
}
Future<void> analyze({String? prompt, File? image}) async {
@@ -72,7 +78,7 @@ class AiCubit extends Cubit<AiState> {
final bytes = await image.readAsBytes();
imageBase64 = 'data:image/png;base64,${base64Encode(bytes)}';
}
final userMessage = ChatMessage(text: prompt, image: image, isUserMessage: true);
final aiPlaceholder = ChatMessage(text: '', thinkingText: '', isUserMessage: false);
@@ -90,12 +96,7 @@ class AiCubit extends Cubit<AiState> {
try {
final response = await _dio.post(
'$BASE_URL/analyze',
data: {
'userId': _userId,
'sessionId': state.sessionId,
'userPrompt': prompt,
'imageBase64': imageBase64,
},
data: {'userId': _userId, 'sessionId': state.sessionId, 'userPrompt': prompt, 'imageBase64': imageBase64},
options: Options(responseType: ResponseType.stream),
);
@@ -126,13 +127,8 @@ class AiCubit extends Cubit<AiState> {
}
final updatedMessages = List<ChatMessage>.from(state.messages);
updatedMessages[0] = ChatMessage(
thinkingText: thinkingBuffer.toString(),
text: answerBuffer.toString(),
isUserMessage: false,
);
updatedMessages[0] = ChatMessage(thinkingText: thinkingBuffer.toString(), text: answerBuffer.toString(), isUserMessage: false);
emit(state.copyWith(messages: updatedMessages));
} catch (e) {
print("Error parsing stream data: $e");
}
@@ -144,18 +140,18 @@ class AiCubit extends Cubit<AiState> {
fetchSessions();
},
onError: (error) {
final updatedMessages = List<ChatMessage>.from(state.messages);
updatedMessages[0] = ChatMessage(text: "Error: $error", isUserMessage: false);
emit(state.copyWith(status: AiStatus.failure, messages: updatedMessages));
final updatedMessages = List<ChatMessage>.from(state.messages);
updatedMessages[0] = ChatMessage(text: "Error: $error", isUserMessage: false);
emit(state.copyWith(status: AiStatus.failure, messages: updatedMessages));
},
);
} catch (e) {
final updatedMessages = List<ChatMessage>.from(state.messages);
updatedMessages[0] = ChatMessage(text: "Failed to connect to the server: $e", isUserMessage: false);
emit(state.copyWith(status: AiStatus.failure, messages: updatedMessages));
final updatedMessages = List<ChatMessage>.from(state.messages);
updatedMessages[0] = ChatMessage(text: "Failed to connect to the server: $e", isUserMessage: false);
emit(state.copyWith(status: AiStatus.failure, messages: updatedMessages));
}
}
void selectImage(ImageSource source) async {
final pickedFile = await _picker.pickImage(source: source);
if (pickedFile != null) {
@@ -166,13 +162,15 @@ class AiCubit extends Cubit<AiState> {
void deselectImage() {
// Manually create a new state to ensure selectedImageFile is set to null,
// bypassing the limitation of the existing copyWith method.
emit(AiState(
status: state.status,
messages: state.messages,
sessions: state.sessions,
sessionId: state.sessionId,
error: state.error,
selectedImageFile: null, // This will now correctly clear the file.
));
emit(
AiState(
status: state.status,
messages: state.messages,
sessions: state.sessions,
sessionId: state.sessionId,
error: state.error,
selectedImageFile: null, // This will now correctly clear the file.
),
);
}
}

View File

@@ -1,12 +1,13 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import '../bloc/ai_cubit.dart';
import '../bloc/ai_state.dart';
@@ -21,7 +22,10 @@ class AiPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => AiCubit(),
create: (context) => AiCubit(
appUserCubit: context.read<AppUserCubit>(), // ✅ 这里传
),
child: const AiView(),
);
}
@@ -49,7 +53,7 @@ class _AiViewState extends State<AiView> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AI智能体'),
title: const Text('新能源光伏智能体'),
actions: [
PopupMenuButton<String>(
onSelected: (value) {
@@ -103,19 +107,11 @@ class _AiViewState extends State<AiView> {
mainAxisAlignment: isUserMessage ? MainAxisAlignment.end : MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (!isUserMessage)
const CircleAvatar(
backgroundImage: AssetImage('assets/images/app_logo_black.png'),
radius: 16,
),
if (!isUserMessage) const CircleAvatar(backgroundImage: AssetImage('assets/images/app_logo_black.png'), radius: 16),
const SizedBox(width: 10),
Flexible(
child: isUserMessage ? _buildUserMessageContent(context, message) : _buildAiMessageContent(context, message),
),
if (isUserMessage)
const SizedBox(width: 10), // <-- This was the missing part
if (isUserMessage)
const CircleAvatar(child: Icon(Icons.person, size: 20), radius: 16),
Flexible(child: isUserMessage ? _buildUserMessageContent(context, message) : _buildAiMessageContent(context, message)),
if (isUserMessage) const SizedBox(width: 10), // <-- This was the missing part
if (isUserMessage) const CircleAvatar(child: Icon(Icons.person, size: 20), radius: 16),
],
),
);
@@ -123,44 +119,45 @@ class _AiViewState extends State<AiView> {
Widget _buildUserMessageContent(BuildContext context, ChatMessage message) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 14.0),
decoration: BoxDecoration(color: Colors.black, borderRadius: BorderRadius.circular(18)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (message.image != null)
GestureDetector(
onTap: () => _showImagePreview(context, imageFile: message.image!),
child: ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.file(message.image!, width: 200, height: 200, fit: BoxFit.cover),
),
)
else if (message.imageBase64 != null)
ClipRRect(
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 14.0),
decoration: BoxDecoration(color: Colors.black, borderRadius: BorderRadius.circular(18)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (message.image != null)
GestureDetector(
onTap: () => _showImagePreview(context, imageFile: message.image!),
child: ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.memory(base64Decode(message.imageBase64!.split(',').last), width: 200, height: 200, fit: BoxFit.cover),
child: Image.file(message.image!, width: 200, height: 200, fit: BoxFit.cover),
),
if (message.text != null && message.text!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(message.text!, style: const TextStyle(color: Colors.white, fontSize: 16)),
),
],
));
)
else if (message.imageBase64 != null)
ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.memory(base64Decode(message.imageBase64!.split(',').last), width: 200, height: 200, fit: BoxFit.cover),
),
if (message.text != null && message.text!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(message.text!, style: const TextStyle(color: Colors.white, fontSize: 16)),
),
],
),
);
}
Widget _buildAiMessageContent(BuildContext context, ChatMessage message) {
final state = context.watch<AiCubit>().state;
final hasThinking = message.thinkingText != null && message.thinkingText!.isNotEmpty;
final hasAnswer = message.text != null && message.text!.isNotEmpty;
final showThinkingBlock = state.status == AiStatus.loading || hasThinking;
final showThinkingBlock = state.status == AiStatus.loading || !hasAnswer;
if (!showThinkingBlock && !hasAnswer) return const SizedBox.shrink();
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceVariant,
color: const Color(0xFFF5F7F9), // 更柔和的背景
borderRadius: BorderRadius.circular(18),
),
child: Column(
@@ -175,18 +172,76 @@ class _AiViewState extends State<AiView> {
iconColor: Colors.blue.shade700,
showSpinner: state.status == AiStatus.loading && !hasThinking,
),
if (showThinkingBlock && hasAnswer)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Divider(height: 1, color: Colors.grey.shade300),
),
// ========== 最终结论(带美化 Markdown)==========
if (hasAnswer)
_buildSection(
context,
icon: Icons.lightbulb_outline,
title: "最终结论",
content: message.text!,
iconColor: Colors.green.shade700,
Padding(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.lightbulb_outline, size: 20, color: Colors.green.shade700),
const SizedBox(width: 8),
const Text(
"最终结论",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Color(0xFF2D7D46)),
),
],
),
const SizedBox(height: 10),
// ========== Markdown 渲染(超好看样式)==========
Markdown(
data: message.text!,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
styleSheet: MarkdownStyleSheet(
// 正文
p: const TextStyle(fontSize: 15, height: 1.6, color: Color(0xFF262626)),
// 标题
h1: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, height: 1.5, color: Color(0xFF111111)),
h2: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold, height: 1.5, color: Color(0xFF111111)),
h3: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, height: 1.5, color: Color(0xFF111111)),
// 加粗
strong: const TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF000000)),
// 斜体
em: const TextStyle(fontStyle: FontStyle.italic, color: Color(0xFF444444)),
// 列表
listBullet: const TextStyle(fontSize: 15, height: 1.6, color: Color(0xFF262626)),
// 引用
blockquote: const TextStyle(fontSize: 15, color: Color(0xFF555555), height: 1.6),
blockquoteDecoration: BoxDecoration(
border: Border(left: BorderSide(color: Colors.green.shade300, width: 4)),
),
// 代码行
code: TextStyle(fontSize: 14, color: const Color(0xFFD32F2F), backgroundColor: Colors.grey.shade200, height: 1.6),
// 代码块
codeblockDecoration: BoxDecoration(color: Colors.grey.shade100, borderRadius: BorderRadius.circular(8)),
codeblockPadding: const EdgeInsets.all(10),
// 表格
tableBorder: TableBorder.all(color: Colors.grey.shade300, width: 1),
tableHead: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
tableBody: const TextStyle(fontSize: 14, height: 1.5),
),
),
],
),
),
],
),
@@ -199,15 +254,20 @@ class _AiViewState extends State<AiView> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(icon, size: 20, color: iconColor),
const SizedBox(width: 8),
Text(title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: iconColor)),
if (showSpinner) ...[
Row(
children: [
Icon(icon, size: 20, color: iconColor),
const SizedBox(width: 8),
SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2.0, color: iconColor)),
]
]),
Text(
title,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: iconColor),
),
if (showSpinner) ...[
const SizedBox(width: 8),
SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2.0, color: iconColor)),
],
],
),
if (content != null && content.isNotEmpty) ...[
const SizedBox(height: 8),
Text(content, style: const TextStyle(fontSize: 16, color: Colors.black87, height: 1.4)),
@@ -312,7 +372,7 @@ class _AiViewState extends State<AiView> {
children: <Widget>[
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text('Gallery'),
title: const Text('相册'),
onTap: () {
Navigator.of(context).pop();
context.read<AiCubit>().selectImage(ImageSource.gallery);
@@ -320,7 +380,7 @@ class _AiViewState extends State<AiView> {
),
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Camera'),
title: const Text('拍照'),
onTap: () {
Navigator.of(context).pop();
context.read<AiCubit>().selectImage(ImageSource.camera);
@@ -333,7 +393,6 @@ class _AiViewState extends State<AiView> {
);
}
void _showImagePreview(BuildContext context, {File? imageFile, String? imageBase64}) {
if (imageFile == null && imageBase64 == null) return;
Navigator.of(context).push(
@@ -349,7 +408,7 @@ class _AiViewState extends State<AiView> {
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: const Text('History'),
title: const Text('历史记录'),
content: SizedBox(
width: double.maxFinite,
child: BlocBuilder<AiCubit, AiState>(
@@ -371,9 +430,7 @@ class _AiViewState extends State<AiView> {
},
),
),
actions: [
TextButton(onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('Close')),
],
actions: [TextButton(onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('关闭'))],
);
},
);