forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_ai.dart
339 lines (312 loc) · 9.16 KB
/
google_ai.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright 2024 the Dart project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
import 'package:url_launcher/link.dart';
void main() {
runApp(const GenerativeAISample());
}
class GenerativeAISample extends StatelessWidget {
const GenerativeAISample({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter + Generative AI',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
brightness: Brightness.dark,
seedColor: const Color.fromARGB(255, 171, 222, 244),
),
useMaterial3: true,
),
home: const ChatScreen(title: 'Flutter + Generative AI'),
);
}
}
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key, required this.title});
final String title;
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
String? apiKey;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: switch (apiKey) {
final providedKey? => ChatWidget(apiKey: providedKey),
_ => ApiKeyWidget(onSubmitted: (key) {
setState(() => apiKey = key);
}),
},
);
}
}
class ApiKeyWidget extends StatelessWidget {
ApiKeyWidget({required this.onSubmitted, super.key});
final ValueChanged onSubmitted;
final TextEditingController _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'To use the Gemini API, you\'ll need an API key. '
'If you don\'t already have one, '
'create a key in Google AI Studio.',
),
const SizedBox(height: 8),
Link(
uri: Uri.https('makersuite.google.com', '/app/apikey'),
target: LinkTarget.blank,
builder: (context, followLink) => TextButton(
onPressed: followLink,
child: const Text('Get an API Key'),
),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
decoration:
textFieldDecoration(context, 'Enter your API key'),
controller: _textController,
onSubmitted: (value) {
onSubmitted(value);
},
),
),
const SizedBox(height: 8),
TextButton(
onPressed: () {
onSubmitted(_textController.value.text);
},
child: const Text('Submit'),
),
],
),
],
),
),
);
}
}
class ChatWidget extends StatefulWidget {
const ChatWidget({required this.apiKey, super.key});
final String apiKey;
@override
State<ChatWidget> createState() => _ChatWidgetState();
}
class _ChatWidgetState extends State<ChatWidget> {
late final GenerativeModel _model;
late final ChatSession _chat;
final ScrollController _scrollController = ScrollController();
final TextEditingController _textController = TextEditingController();
final FocusNode _textFieldFocus = FocusNode(debugLabel: 'TextField');
bool _loading = false;
@override
void initState() {
super.initState();
_model = GenerativeModel(
model: 'gemini-pro',
apiKey: widget.apiKey,
);
_chat = _model.startChat();
}
void _scrollDown() {
WidgetsBinding.instance.addPostFrameCallback(
(_) => _scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(
milliseconds: 750,
),
curve: Curves.easeOutCirc,
),
);
}
@override
Widget build(BuildContext context) {
final history = _chat.history.toList();
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
itemBuilder: (context, idx) {
final content = history[idx];
final text = content.parts
.whereType<TextPart>()
.map<String>((e) => e.text)
.join('');
return MessageWidget(
text: text,
isFromUser: content.role == 'user',
);
},
itemCount: history.length,
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 25,
horizontal: 15,
),
child: Row(
children: [
Expanded(
child: TextField(
autofocus: true,
focusNode: _textFieldFocus,
decoration:
textFieldDecoration(context, 'Enter a prompt...'),
controller: _textController,
onSubmitted: (String value) {
_sendChatMessage(value);
},
),
),
const SizedBox.square(dimension: 15),
if (!_loading)
IconButton(
onPressed: () async {
_sendChatMessage(_textController.text);
},
icon: Icon(
Icons.send,
color: Theme.of(context).colorScheme.primary,
),
)
else
const CircularProgressIndicator(),
],
),
),
],
),
);
}
Future<void> _sendChatMessage(String message) async {
setState(() {
_loading = true;
});
try {
final response = await _chat.sendMessage(
Content.text(message),
);
final text = response.text;
if (text == null) {
_showError('Empty response.');
return;
} else {
setState(() {
_loading = false;
_scrollDown();
});
}
} catch (e) {
_showError(e.toString());
setState(() {
_loading = false;
});
} finally {
_textController.clear();
setState(() {
_loading = false;
});
_textFieldFocus.requestFocus();
}
}
void _showError(String message) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Something went wrong'),
content: SingleChildScrollView(
child: Text(message),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
)
],
);
},
);
}
}
class MessageWidget extends StatelessWidget {
const MessageWidget({
super.key,
required this.text,
required this.isFromUser,
});
final String text;
final bool isFromUser;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment:
isFromUser ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 480),
decoration: BoxDecoration(
color: isFromUser
? Theme.of(context).colorScheme.primaryContainer
: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(18),
),
padding: const EdgeInsets.symmetric(
vertical: 15,
horizontal: 20,
),
margin: const EdgeInsets.only(bottom: 8),
child: MarkdownBody(data: text),
),
),
],
);
}
}
InputDecoration textFieldDecoration(BuildContext context, String hintText) =>
InputDecoration(
contentPadding: const EdgeInsets.all(15),
hintText: hintText,
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(
Radius.circular(14),
),
borderSide: BorderSide(
color: Theme.of(context).colorScheme.secondary,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: const BorderRadius.all(
Radius.circular(14),
),
borderSide: BorderSide(
color: Theme.of(context).colorScheme.secondary,
),
),
);