-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatpage.dart
102 lines (94 loc) · 2.55 KB
/
chatpage.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
class ChatPage extends StatefulWidget {
const ChatPage({super.key});
@override
State<ChatPage> createState() => _ChatPageState();
}
const OPENAI_API_KEY = "<Enter your API key>";
class _ChatPageState extends State<ChatPage> {
final _openAI = OpenAI.instance.build(
token: OPENAI_API_KEY,
baseOption: HttpSetup(
receiveTimeout: const Duration(
seconds: 5,
),
),
enableLog: true,
);
final ChatUser _currentUser =
ChatUser(id: '1', firstName: 'User', lastName: '(You)';
final ChatUser _gptChatUser =
ChatUser(id: '2', firstName: 'Health', lastName: 'Bot');
List<ChatMessage> _messages = <ChatMessage>[];
List<ChatUser> _typingUsers = <ChatUser>[];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromRGBO(
0,
166,
126,
1,
),
title: const Text(
'GPT Chat',
style: TextStyle(
color: Colors.white,
),
),
),
body: DashChat(
currentUser: _currentUser,
typingUsers: _typingUsers,
messageOptions: const MessageOptions(
currentUserContainerColor: Colors.black,
containerColor: Color.fromRGBO(
0,
166,
126,
1,
),
textColor: Colors.white,
),
onSend: (ChatMessage m) {
getChatResponse(m);
},
messages: _messages),
);
}
Future<void> getChatResponse(ChatMessage m) async {
setState(() {
_messages.insert(0, m);
_typingUsers.add(_gptChatUser);
});
List<Messages> _messagesHistory = _messages.reversed.map((m) {
if (m.user == _currentUser) {
return Messages(role: Role.user, content: m.text);
} else {
return Messages(role: Role.assistant, content: m.text);
}
}).toList();
final request = ChatCompleteText(
model: GptTurbo0301ChatModel(),
messages: _messagesHistory,
maxToken: 200,
);
final response = await _openAI.onChatCompletion(request: request);
for (var element in response!.choices) {
if (element.message != null) {
setState(() {
_messages.insert(
0,
ChatMessage(
user: _gptChatUser,
createdAt: DateTime.now(),
text: element.message!.content),
);
});
}
}
setState(() {
_typingUsers.remove(_gptChatUser);
});
}
}