Merge pull request #57 from yaso-meth/QOL-Mzansi-AI-Chat-improvements

- Add visibile sign when settings is clicked.
This commit is contained in:
yaso-meth
2025-01-29 11:20:55 +02:00
committed by GitHub

View File

@@ -1,7 +1,10 @@
import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:Mzansi_Innovation_Hub/main.dart'; import 'package:Mzansi_Innovation_Hub/main.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_inputs_and_buttons/mih_button.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart'; import 'package:Mzansi_Innovation_Hub/mih_components/mih_inputs_and_buttons/mih_dropdown_input.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_inputs_and_buttons/mih_text_input.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_package/mih-app_tool_body.dart'; import 'package:Mzansi_Innovation_Hub/mih_components/mih_package/mih-app_tool_body.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_package/mih_app_window.dart'; import 'package:Mzansi_Innovation_Hub/mih_components/mih_package/mih_app_window.dart';
import 'package:Mzansi_Innovation_Hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart'; import 'package:Mzansi_Innovation_Hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
@@ -26,17 +29,20 @@ class AiChat extends StatefulWidget {
} }
class _AiChatState extends State<AiChat> { class _AiChatState extends State<AiChat> {
TextEditingController _modelCopntroller = TextEditingController(); final TextEditingController _modelCopntroller = TextEditingController();
final TextEditingController _fontSizeCopntroller = TextEditingController();
final ValueNotifier<bool> _showModelOptions = ValueNotifier(false); final ValueNotifier<bool> _showModelOptions = ValueNotifier(false);
List<types.Message> _messages = []; List<types.Message> _messages = [];
late types.User _user; late types.User _user;
late types.User _mihAI; late types.User _mihAI;
String systemPromt = String systemPromt =
"You are a helpful and friendly AI assistant. You are running on a system called MIH which was created by \"Mzansi Innovation Hub\" a South African based company."; "You are a helpful and friendly AI assistant. You are running on a system called MIH which was created by \"Mzansi Innovation Hub\" a South African based company.";
bool _aiThinking = false;
final client = ollama.OllamaClient( final client = ollama.OllamaClient(
baseUrl: "${AppEnviroment.baseAiUrl}/api", baseUrl: "${AppEnviroment.baseAiUrl}/api",
); );
List<ollama.Message> _chatHistory = []; List<ollama.Message> _chatHistory = [];
double _chatFrontSize = 17;
void _addMessage(types.Message message) { void _addMessage(types.Message message) {
setState(() { setState(() {
@@ -67,58 +73,44 @@ class _AiChatState extends State<AiChat> {
} }
void _handleMessageBack(String userMessage) async { void _handleMessageBack(String userMessage) async {
// types.TextMessage textMessage;
// String aiResponse = "";
// final aiResponseStream =
showDialog( showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return const Mihloadingcircle(); return const Mihloadingcircle();
}, },
); );
_generateChatCompletionWithHistoryStream(userMessage, client) Stream<String> aiChatStream =
.listen((response) { _generateChatCompletionWithHistoryStream(userMessage, client);
//aiResponse = response; //.split("</think>").last.trim();
});
Navigator.of(context).pop(); Navigator.of(context).pop();
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false,
builder: (context) { builder: (context) {
return responseWindow(); return responseWindow(aiChatStream);
}, },
); );
// setState(() {
// _chatHistory.add(
// ollama.Message(
// role: ollama.MessageRole.assistant,
// content: aiResponse,
// ),
// );
// });
// textMessage = types.TextMessage(
// author: _mihAI,
// createdAt: DateTime.now().millisecondsSinceEpoch,
// id: const Uuid().v4(),
// text: aiResponse //message.text,
// );
// _addMessage(textMessage);
// print(_chatHistory.toString());
// Navigator.of(context).pop();
} }
Widget responseWindow() { Widget responseWindow(
Stream<String> aiChatStream,
// StreamSubscription<String> aiChatSubscription,
) {
StreamSubscription<String> aiChatSubscription =
aiChatStream.listen((response) {});
types.TextMessage textMessage; types.TextMessage textMessage;
return StreamBuilder( return StreamBuilder(
stream: _generateChatCompletionWithHistoryStream("Hello", client), stream: _generateChatCompletionWithHistoryStream("", client),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.hasData) { if (snapshot.hasData) {
return MihAppWindow( return MihAppWindow(
fullscreen: false, fullscreen: false,
windowTitle: 'Mzansi AI Thoughts', windowTitle: 'Mzansi AI Thoughts',
windowTools: [ windowTools: const [],
IconButton( onWindowTapClose: () {
onPressed: () { if (_aiThinking) {
aiChatSubscription.cancel();
}
setState(() { setState(() {
_chatHistory.add( _chatHistory.add(
ollama.Message( ollama.Message(
@@ -136,19 +128,13 @@ class _AiChatState extends State<AiChat> {
// }, // },
text: snapshot.requireData text: snapshot.requireData
.replaceAll("<think>\n\n", "Thinking:\n") .replaceAll("<think>\n\n", "Thinking:\n")
.replaceAll( .replaceAll("<think>\n", "Thinking:\n")
"</think>\n\n", "Answer:\n"), //message.text, .replaceAll("</think>\n\n", "Answer:\n"), //message.text,
); );
_addMessage(textMessage); _addMessage(textMessage);
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
icon: const Icon(Icons.arrow_back),
),
],
onWindowTapClose: () {
Navigator.of(context).pop();
},
windowBody: [ windowBody: [
Text( Text(
snapshot.requireData, snapshot.requireData,
@@ -156,10 +142,47 @@ class _AiChatState extends State<AiChat> {
style: TextStyle( style: TextStyle(
color: color:
MzanziInnovationHub.of(context)!.theme.secondaryColor(), MzanziInnovationHub.of(context)!.theme.secondaryColor(),
fontSize: 12, fontSize: _chatFrontSize,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
const SizedBox(height: 15),
Visibility(
visible: _aiThinking == false,
child: MIHButton(
onTap: () {
setState(() {
_chatHistory.add(
ollama.Message(
role: ollama.MessageRole.assistant,
content: snapshot.requireData,
),
);
});
textMessage = types.TextMessage(
author: _mihAI,
createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(),
// metadata: <String, dynamic>{
// "thoughts": snapshot.requireData
// },
text: snapshot.requireData
.replaceAll("<think>\n\n", "Thinking:\n")
.replaceAll("<think>\n", "Thinking:\n")
.replaceAll(
"</think>\n\n", "Answer:\n"), //message.text,
);
_addMessage(textMessage);
Navigator.of(context).pop();
},
buttonText: "Continue",
buttonColor:
MzanziInnovationHub.of(context)!.theme.successColor(),
textColor:
MzanziInnovationHub.of(context)!.theme.primaryColor(),
),
),
], ],
); );
} else { } else {
@@ -190,19 +213,6 @@ class _AiChatState extends State<AiChat> {
}); });
} }
// Future<String> _generateChatCompletionWithHistory(
// String userMessage,
// final ollama.OllamaClient client,
// ) async {
// final generated = await client.generateChatCompletion(
// request: ollama.GenerateChatCompletionRequest(
// model: _modelCopntroller.text,
// messages: _chatHistory,
// ),
// );
// return generated.message.content;
// }
Stream<String> _generateChatCompletionWithHistoryStream( Stream<String> _generateChatCompletionWithHistoryStream(
String userMessage, String userMessage,
final ollama.OllamaClient client, final ollama.OllamaClient client,
@@ -214,10 +224,16 @@ class _AiChatState extends State<AiChat> {
), ),
); );
String text = ''; String text = '';
setState(() {
_aiThinking = true;
});
await for (final res in aiStream) { await for (final res in aiStream) {
text += (res.message.content); text += (res.message.content);
yield text; yield text;
} }
setState(() {
_aiThinking = false;
});
// print(text); // print(text);
} }
@@ -247,19 +263,19 @@ class _AiChatState extends State<AiChat> {
errorColor: MzanziInnovationHub.of(context)!.theme.errorColor(), errorColor: MzanziInnovationHub.of(context)!.theme.errorColor(),
sentMessageBodyTextStyle: TextStyle( sentMessageBodyTextStyle: TextStyle(
color: MzanziInnovationHub.of(context)!.theme.primaryColor(), color: MzanziInnovationHub.of(context)!.theme.primaryColor(),
fontSize: 17, fontSize: _chatFrontSize,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
fontFamily: 'Segoe UI', fontFamily: 'Segoe UI',
), ),
receivedMessageBodyTextStyle: TextStyle( receivedMessageBodyTextStyle: TextStyle(
color: MzanziInnovationHub.of(context)!.theme.primaryColor(), color: MzanziInnovationHub.of(context)!.theme.primaryColor(),
fontSize: 17, fontSize: _chatFrontSize,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
fontFamily: 'Segoe UI', fontFamily: 'Segoe UI',
), ),
emptyChatPlaceholderTextStyle: TextStyle( emptyChatPlaceholderTextStyle: TextStyle(
color: MzanziInnovationHub.of(context)!.theme.messageTextColor(), color: MzanziInnovationHub.of(context)!.theme.messageTextColor(),
fontSize: 17, fontSize: _chatFrontSize,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
fontFamily: 'Segoe UI', fontFamily: 'Segoe UI',
), ),
@@ -286,6 +302,7 @@ class _AiChatState extends State<AiChat> {
id: const Uuid().v4(), id: const Uuid().v4(),
); );
_modelCopntroller.text = 'deepseek-r1:1.5b'; _modelCopntroller.text = 'deepseek-r1:1.5b';
_fontSizeCopntroller.text = _chatFrontSize.ceil().toString();
// _chatHistory.add( // _chatHistory.add(
// ollama.Message( // ollama.Message(
// role: ollama.MessageRole.system, // role: ollama.MessageRole.system,
@@ -300,13 +317,20 @@ class _AiChatState extends State<AiChat> {
return MihAppToolBody( return MihAppToolBody(
borderOn: false, borderOn: false,
bodyItem: Column( bodyItem: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
children: [ children: [
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
IconButton( Expanded(
child: Container(
alignment: Alignment.centerLeft,
child: Row(
children: [
Visibility(
visible: _showModelOptions.value == false,
child: IconButton(
onPressed: () { onPressed: () {
if (_showModelOptions.value == true) { if (_showModelOptions.value == true) {
setState(() { setState(() {
@@ -320,6 +344,28 @@ class _AiChatState extends State<AiChat> {
}, },
icon: const Icon(Icons.settings), icon: const Icon(Icons.settings),
), ),
),
Visibility(
visible: _showModelOptions.value == true,
child: IconButton.filled(
onPressed: () {
if (_showModelOptions.value == true) {
setState(() {
_showModelOptions.value = false;
});
} else {
setState(() {
_showModelOptions.value = true;
});
}
},
icon: const Icon(Icons.settings),
),
),
],
),
),
),
Text( Text(
"Mzansi AI", "Mzansi AI",
textAlign: TextAlign.center, textAlign: TextAlign.center,
@@ -330,12 +376,17 @@ class _AiChatState extends State<AiChat> {
MzanziInnovationHub.of(context)!.theme.secondaryColor(), MzanziInnovationHub.of(context)!.theme.secondaryColor(),
), ),
), ),
IconButton( Expanded(
child: Container(
alignment: Alignment.centerRight,
child: IconButton(
onPressed: () { onPressed: () {
_resetChat(); _resetChat();
}, },
icon: const Icon(Icons.refresh), icon: const Icon(Icons.refresh),
), ),
),
),
], ],
), ),
ValueListenableBuilder( ValueListenableBuilder(
@@ -343,6 +394,8 @@ class _AiChatState extends State<AiChat> {
builder: (BuildContext context, bool value, Widget? child) { builder: (BuildContext context, bool value, Widget? child) {
return Visibility( return Visibility(
visible: value, visible: value,
child: Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: [
@@ -361,9 +414,63 @@ class _AiChatState extends State<AiChat> {
) )
], ],
), ),
),
); );
}, },
), ),
const SizedBox(height: 15),
ValueListenableBuilder(
valueListenable: _showModelOptions,
builder: (BuildContext context, bool value, Widget? child) {
return Visibility(
visible: value,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
IconButton.filled(
onPressed: () {
setState(() {
_chatFrontSize -= 1;
_fontSizeCopntroller.text =
_chatFrontSize.ceil().toString();
});
},
icon: const Icon(
Icons.remove,
),
),
const SizedBox(width: 10),
SizedBox(
width: 200,
child: MIHTextField(
controller: _fontSizeCopntroller,
hintText: "Chat Font Size",
editable: false,
required: true,
),
),
const SizedBox(width: 10),
IconButton.filled(
onPressed: () {
setState(() {
_chatFrontSize += 1;
_fontSizeCopntroller.text =
_chatFrontSize.ceil().toString();
});
},
icon: const Icon(
Icons.add,
),
),
],
),
),
);
},
),
const SizedBox(height: 5),
Expanded( Expanded(
child: Chat( child: Chat(
messages: _messages, messages: _messages,