動機
Dart3.3のアップデート記事をどこかで見たから。
本題
Googleの発表したAI Bard改めGemini を利用するためのパッケージgoogle_generative_ai を触ってみる。
サンプルを動かしてみる
GeminiでAPIキー取得する
-
Google AI Studioを有効にする
法人アカウントの場合、早期アクセスアプリの有効化が必要。
Core Data Access Permissionsの許可が必要。
-
APIキーをCreateする
余談だが、Gemini(本家)に聞いても教えてくれる。
Flutterでアプリを起動する
% git clone git@github.com:google/generative-ai-dart.git
% cd samples/flutter_app
% fvm flutter run -d 1625B704-06DE-46E3-B905-2294D4E16509 --dart-define=API_KEY=[Google AI Studioで取得したAPIキー]
質問をしてみる
日本語も通じる。AIらしい回答が返ってくる。
コードをみる
samples/flutter_app/lib/main.dart
class _ChatWidgetState extends State<ChatWidget> {
late final GenerativeModel _model;
...
@override
void initState() {
super.initState();
_model = GenerativeModel(
model: 'gemini-pro',
apiKey: _apiKey,
);
_chat = _model.startChat();
}
_modelインスタンス生成のところ。_models.startChat()
で会話をスタートしている。
Future<void> _sendChatMessage(String message) async {
setState(() {
_loading = true;
});
try {
var response = await _chat.sendMessage(
Content.text(message),
);
var text = response.text;
チャット送信するメソッド。_chat.sendMessage
の中で会話履歴_chat.history
に追加されることでListViewが再描画される。
Content.text(message)
はユーザー入力のメッセージということ。
sendMessageStream
もあるので用途によってはこちら。
画像を送る
サンプルにそのような機能はない。自分で書く。
画像を送れそうなコードがある
static Content data(String mimeType, Uint8List bytes) =>
Content('user', [DataPart(mimeType, bytes)]);
画像を送ることもできそう。
参考
クイックスタート: Dart アプリまたは Flutter アプリで Gemini API を使ってみる | Google AI for Developers