0
1

Flutter(Dart)からGeminiを簡単に呼べるようになったので試してみる

Last updated at Posted at 2024-02-23

動機

Dart3.3のアップデート記事をどこかで見たから。

本題

Googleの発表したAI Bard改めGemini を利用するためのパッケージgoogle_generative_ai を触ってみる。

サンプルを動かしてみる

GeminiでAPIキー取得する

  1. Google AI Studioを有効にする

    法人アカウントの場合、早期アクセスアプリの有効化が必要。

    Core Data Access Permissionsの許可が必要。

  2. 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キー]

質問をしてみる

Simulator Screenshot - iPhone 15 - 2024-02-18 at 02.45.12.png

日本語も通じる。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)]);

画像を送ることもできそう。

参考

What’s new in Flutter 3.19. Revolutionizing App Development with… | by Kevin Chisholm | Flutter | Feb, 2024 | Medium

New in Dart 3.3: Extension Types, JavaScript Interop, and More | by Kevin Moore | Dart | Feb, 2024 | Medium

クイックスタート: Dart アプリまたは Flutter アプリで Gemini API を使ってみる  |  Google AI for Developers

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1