Flutter AI功能集成插件google_gemini_ai的使用

Flutter AI功能集成插件google_gemini_ai的使用

Google DeepMind Gemini

Google Gemini 是一组尖端的大规模语言模型(LLM),旨在成为谷歌未来AI计划的核心驱动力。

Gemini

此包为您的Flutter应用程序与谷歌革命性的Gemini AI之间提供了一个强大的桥梁。它使您能够无缝地将Gemini的功能集成到您的应用中,解锁构建创新、智能且吸引人的体验的世界,重新定义用户交互。

示例

特性

获取开始

要获得API密钥,您需要在ai.google.dev上创建一个Gemini帐户。一旦您有了Gemini API密钥,您就可以开始构建了。

创建Gemini实例

final gemini = GoogleGemini(
  apiKey: "--- Your Gemini Api Key ---",
);

生成内容

使用Gemini,您可以根据所使用的模型变体使用文本和图像数据进行提示。

例如,您可以使用仅文本提示与gemini-pro模型生成文本,并使用文本和图像数据提示gemini-pro-vision模型。

仅文本输入

此功能允许您执行自然语言处理(NLP)任务,如文本补全和摘要。

gemini.generateFromText("Tell me a story")
.then((value) => print(value.text))
.catchError((e) => print(e));
文本和图像输入

您可以向gemini-pro-vision模型发送带有图像的文本提示以执行与视觉相关的任务。例如,给图像加标题或识别图像中的内容。

File image = File("assets/images.png");

gemini.generateFromTextAndImages(
  query: "What is this picture?",
  image: image
)
.then((value) => print(value.text))
.catchError((e) => print(e));

配置

您发送给模型的每个提示都包含控制模型如何生成响应的参数值。不同的参数值可以生成不同的结果。

模型参数

最常用的模型参数包括:

  1. 最大输出令牌数:指定响应中可以生成的最大令牌数量。一个令牌大约相当于四个字符。100个令牌大致相当于60-80个单词。
  2. 温度:温度控制令牌选择的随机程度。较低的温度适用于需要更确定或不那么开放的回答,而较高的温度可以导致更多样化或创造性的结果。
  3. topK:topK参数改变模型选择输出令牌的方式。
  4. topP:topP参数改变模型选择输出令牌的方式。
  5. 停止序列:设置停止序列以告诉模型停止生成内容。停止序列可以是任何字符序列。尽量避免使用可能出现在生成内容中的字符序列。
// 生成配置
final config = GenerationConfig(
    temperature: 0.5,
    maxOutputTokens: 100,
    topP: 1.0,
    topK: 40,
    stopSequences: []
);

// Gemini 实例
final gemini = GoogleGemini(
    apiKey: "--- Your Gemini Api Key ---",
    config: config // 传递配置
);
安全设置

安全设置是您发送给文本服务请求的一部分。它可以针对每次API请求进行调整。

类别

这些类别涵盖了开发人员可能希望调整的各种类型的伤害。

HARM_CATEGORY_UNSPECIFIED
HARM_CATEGORY_DEROGATORY
HARM_CATEGORY_TOXICITY
HARM_CATEGORY_VIOLENCE
HARM_CATEGORY_SEXUAL
HARM_CATEGORY_MEDICAL
HARM_CATEGORY_DANGEROUS
HARM_CATEGORY_HARASSMENT
HARM_CATEGORY_HATE_SPEECH
HARM_CATEGORY_SEXUALLY_EXPLICIT
HARM_CATEGORY_DANGEROUS_CONTENT
门槛

在指定的危害概率及以上阻止。

HARM_BLOCK_THRESHOLD_UNSPECIFIED
BLOCK_LOW_AND_ABOVE
BLOCK_MEDIUM_AND_ABOVE
BLOCK_ONLY_HIGH
BLOCK_NONE
// 安全设置
final safety1 = SafetySettings(
  category: SafetyCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
  threshold: SafetyThreshold.BLOCK_ONLY_HIGH
);

//  Gemini 实例
final gemini = GoogleGemini(
  apiKey:"--- Your Gemini Api Key ---",
  safetySettings: [
    safety1,
    // safety2
  ]
);

构建多轮对话

// 进行中

使用流式处理以加快交互速度

// 进行中

Gemini响应

// 进行中

Gemini方法

// 进行中

完整示例代码

import 'package:flutter/material.dart';
import 'package:google_gemini_ai/google_gemini_ai.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

const apiKey = "--- Your Gemini Api Key ---";

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
  });

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return DefaultTabController(
        initialIndex: 0,
        length: 2,
        child: Scaffold(
            appBar: AppBar(
              title: const Text("Google Gemini"),
              centerTitle: true,
              bottom: const TabBar(
                tabs: [
                  Tab(text: "Text Only"),
                  Tab(text: "Text with Image"),
                ],
              ),
            ),
            body: const TabBarView(
              children: [TextOnly(), TextWithImage()],
            )));
  }
}

// ------------------------------ Text Only ------------------------------

class TextOnly extends StatefulWidget {
  const TextOnly({
    super.key,
  });

  [@override](/user/override)
  State<TextOnly> createState() => _TextOnlyState();
}

class _TextOnlyState extends State<TextOnly> {
  bool loading = false;
  List textChat = [];
  List textWithImageChat = [];

  final TextEditingController _textController = TextEditingController();
  final ScrollController _controller = ScrollController();

  // 创建Gemini实例
  final gemini = GoogleGemini(
    apiKey: apiKey,
  );

  // 仅文本输入
  void fromText({required String query}) {
    setState(() {
      loading = true;
      textChat.add({
        "role": "User",
        "text": query,
      });
      _textController.clear();
    });
    scrollToTheEnd();

    gemini.generateFromText(query).then((value) {
      setState(() {
        loading = false;
        textChat.add({
          "role": "Gemini",
          "text": value.text,
        });
      });
      scrollToTheEnd();
    }).onError((error, stackTrace) {
      setState(() {
        loading = false;
        textChat.add({
          "role": "Gemini",
          "text": error.toString(),
        });
      });
      scrollToTheEnd();
    });
  }

  void scrollToTheEnd() {
    _controller.jumpTo(_controller.position.maxScrollExtent);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Expanded(
          child: ListView.builder(
            controller: _controller,
            itemCount: textChat.length,
            padding: const EdgeInsets.only(bottom: 20),
            itemBuilder: (context, index) {
              return ListTile(
                isThreeLine: true,
                leading: CircleAvatar(
                  child: Text(textChat[index]["role"].substring(0, 1)),
                ),
                title: Text(textChat[index]["role"]),
                subtitle: Text(textChat[index]["text"]),
              );
            },
          ),
        ),
        Container(
          alignment: Alignment.bottomRight,
          margin: const EdgeInsets.all(20),
          padding: const EdgeInsets.symmetric(horizontal: 15.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            border: Border.all(color: Colors.grey),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _textController,
                  decoration: InputDecoration(
                    hintText: "Type a message",
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                        borderSide: BorderSide.none),
                    fillColor: Colors.transparent,
                  ),
                  maxLines: null,
                  keyboardType: TextInputType.multiline,
                ),
              ),
              IconButton(
                icon: loading
                    ? const CircularProgressIndicator()
                    : const Icon(Icons.send),
                onPressed: () {
                  fromText(query: _textController.text);
                },
              ),
            ],
          ),
        )
      ],
    ));
  }
}

// ------------------------------ Text with Image ------------------------------

class TextWithImage extends StatefulWidget {
  const TextWithImage({
    super.key,
  });

  [@override](/user/override)
  State<TextWithImage> createState() => _TextWithImageState();
}

class _TextWithImageState extends State<TextWithImage> {
  bool loading = false;
  List textAndImageChat = [];
  List textWithImageChat = [];
  File? imageFile;

  final ImagePicker picker = ImagePicker();

  final TextEditingController _textController = TextEditingController();
  final ScrollController _controller = ScrollController();

  // 创建Gemini实例
  final gemini = GoogleGemini(
    apiKey: apiKey,
  );

  // 仅文本输入
  void fromTextAndImage({required String query, required File image}) {
    setState(() {
      loading = true;
      textAndImageChat.add({
        "role": "User",
        "text": query,
        "image": image,
      });
      _textController.clear();
      imageFile = null;
    });
    scrollToTheEnd();

    gemini.generateFromTextAndImages(query: query, image: image).then((value) {
      setState(() {
        loading = false;
        textAndImageChat
            .add({"role": "Gemini", "text": value.text, "image": ""});
      });
      scrollToTheEnd();
    }).onError((error, stackTrace) {
      setState(() {
        loading = false;
        textAndImageChat
            .add({"role": "Gemini", "text": error.toString(), "image": ""});
      });
      scrollToTheEnd();
    });
  }

  void scrollToTheEnd() {
    _controller.jumpTo(_controller.position.maxScrollExtent);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              controller: _controller,
              itemCount: textAndImageChat.length,
              padding: const EdgeInsets.only(bottom: 20),
              itemBuilder: (context, index) {
                return ListTile(
                  isThreeLine: true,
                  leading: CircleAvatar(
                    child:
                        Text(textAndImageChat[index]["role"].substring(0, 1)),
                  ),
                  title: Text(textAndImageChat[index]["role"]),
                  subtitle: Text(textAndImageChat[index]["text"]),
                  trailing: textAndImageChat[index]["image"] == ""
                      ? null
                      : Image.file(
                          textAndImageChat[index]["image"],
                          width: 90,
                        ),
                );
              },
            ),
          ),
          Container(
            alignment: Alignment.bottomRight,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
              border: Border.all(color: Colors.grey),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textController,
                    decoration: InputDecoration(
                      hintText: "Write a message",
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                          borderSide: BorderSide.none),
                      fillColor: Colors.transparent,
                    ),
                    maxLines: null,
                    keyboardType: TextInputType.multiline,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.add_a_photo),
                  onPressed: () async {
                    final XFile? image =
                        await picker.pickImage(source: ImageSource.gallery);
                    setState(() {
                      imageFile = image != null ? File(image.path) : null;
                    });
                  },
                ),
                IconButton(
                  icon: loading
                      ? const CircularProgressIndicator()
                      : const Icon(Icons.send),
                  onPressed: () {
                    if (imageFile == null) {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text("Please select an image")));
                      return;
                    }
                    fromTextAndImage(
                        query: _textController.text, image: imageFile!);
                  },
                ),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: imageFile != null
          ? Container(
              margin: const EdgeInsets.only(bottom: 80),
              height: 150,
              child: Image.file(imageFile ?? File("")),
            )
          : null,
    );
  }
}

更多关于Flutter AI功能集成插件google_gemini_ai的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter AI功能集成插件google_gemini_ai的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中集成Google Gemini AI功能,可以通过使用google_gemini_ai插件来实现。不过,需要注意的是,Google Gemini AI并不是Flutter官方或广泛认知的插件,这可能是一个假设的或者非官方的插件名称。在实际应用中,Google提供的AI功能通常通过其官方的ML Kit或其他服务来实现。

然而,为了回答你的问题,我将假设存在一个名为google_gemini_ai的Flutter插件,并给出一个基本的集成和使用代码案例。请注意,这个案例是基于假设的,并且在实际项目中,你需要根据真实的插件文档进行调整。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加google_gemini_ai依赖:

dependencies:
  flutter:
    sdk: flutter
  google_gemini_ai: ^x.y.z  # 替换为实际的版本号

然后运行flutter pub get来安装依赖。

步骤 2: 导入插件

在你的Dart文件中导入插件:

import 'package:google_gemini_ai/google_gemini_ai.dart';

步骤 3: 初始化并使用插件

假设google_gemini_ai插件提供了一个用于文本分析的方法,你可以按照以下方式使用它:

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String result = '';

  @override
  void initState() {
    super.initState();
    _analyzeText();
  }

  Future<void> _analyzeText() async {
    try {
      // 假设这是插件提供的方法
      final analysis = await GoogleGeminiAi.analyzeText(
        text: '这是一个需要分析的文本。',
        options: AnalysisOptions(
          // 根据插件文档设置必要的选项
          language: 'zh-CN',
          // 其他选项...
        ),
      );

      // 更新UI
      setState(() {
        result = analysis.result; // 假设result是分析后的输出
      });
    } catch (e) {
      // 处理错误
      print('Error analyzing text: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Google Gemini AI Demo'),
        ),
        body: Center(
          child: Text(
            result.isEmpty ? 'Analyzing...' : result,
            style: TextStyle(fontSize: 24),
          ),
        ),
      ),
    );
  }
}

注意事项

  1. 插件文档:务必参考google_gemini_ai插件的官方文档,因为上面的代码是基于假设的API。真实的插件可能有不同的方法名和参数。
  2. 错误处理:在实际应用中,添加更全面的错误处理逻辑,以确保应用的稳定性。
  3. 权限:如果插件需要访问网络或设备的其他功能,确保在AndroidManifest.xmlInfo.plist中添加了必要的权限。
  4. 依赖版本:确保使用与Flutter SDK兼容的插件版本。

由于google_gemini_ai并非一个真实存在的广泛认知的插件,上述代码仅为示例。在实际项目中,请查阅官方文档或相关资源以获取准确的集成和使用方法。

回到顶部