Gemini Flutter

Introduction

Gemini Flutter is a Dart package that simplifies the integration of Gemini APIs into your Flutter applications. It provides convenient methods for making requests to Gemini models and handling responses.

Features

1. Gemini-Vision

Gemini is a family of three AI models: Gemini Ultra, Gemini Pro, and Gemini Nano. Each model caters to different needs, offering varying levels of sophistication and performance.

  • Gemini Ultra: This model boasts the most advanced capabilities and is designed to tackle complex tasks such as scientific research, code generation, and creative writing.
  • Gemini Pro: This mid-range model provides a balance between performance and accessibility, making it ideal for developers and businesses who need a powerful AI tool without the hefty price tag of Ultra.
  • Gemini Nano: This lightweight model is designed for everyday use and can be easily integrated into existing applications.

2. Gemini-Pro-Vision API Method Added

Introducing the gemini-pro-vision API method to enhance the capabilities of the system. This new method allows users to leverage the advanced features provided by Gemini Pro Vision, opening up opportunities for improved vision-related functionalities.
Effortlessly manage your image uploads with our system. You can provide the image path, submit the image as a File object, or even directly use base64 encoding – we take care of the rest for you!

3. Token Count Functionality

A new functionality has been added to count tokens for all methods. Users can enable token counting by setting the countToken parameter in the respective methods.

Getting Started

To use this package, follow the steps below:

1. Add the gemini_flutter dependency to your pubspec.yaml file:

 

dependencies:
 
gemini_flutter: ^0.0.1+1

 

Then, run flutter pub get to fetch the dependency.

2. In your Dart code, import the package:

 

import 'package:gemini_flutter/gemini_flutter.dart';

 

3. Initialize the GeminiHandler in your main function:

 

void main() {
      
GeminiHandler().initialize(
             
apiKey: "YOUR_API_KEY",
             
temperature: 0.7,
             
topK: 50,
             
topP: 0.8,
             
outputLength: 100,
             );

             
runApp(MyApp());
         }

 

Make sure to replace “YOUR_API_KEY” with your actual Gemini API key. You can also customize other parameters as needed.

Parameters

  • temperature: This parameter controls the randomness of the generated text. A higher temperature (e.g., 0.9) produces more diverse and creative output, while a lower value (e.g., 0.1) tends to make the output more focused and deterministic.
  • topP: This parameter is used in nucleus sampling to control the diversity of the generated text. It represents the cumulative probability of the top-k candidates to sample from. In your example, it is set to 0.95.
  • topK: This parameter is the number of top candidates from which to sample during nucleus sampling. In your example, it is set to 40.

outputLength: This parameter specifies the desired length of the generated text. In your example, it is set to 1024 characters.

Usage

Text Generation

 

void generateText() async {
  
final response = await GeminiHandler().geminiPro(
     text:
"Write a long story about a magic backpack.",
     temprature:
0.9,
     topP:
0.95,
     topK:
40,
     outputLength:
1024,
   );

  
if (response != null) {
     print(
"Generated Text: ${response.generatedText}");
   }
 }

 

Inside the function, the geminiPro method of the GeminiHandler class is called. This method appears to generate text using the Gemini API. It takes various parameters:

 

text: The prompt for text generation (“Write a long story about a magic backpack.”).

temperature: A parameter controlling the randomness of the generated text (0.9 in this case).

topP: A parameter for nucleus sampling, controlling diversity (0.95 in this case).

topK: Number of top candidates to sample from during nucleus sampling (40 in this case).

outputLength: The desired length of the generated text (1024 characters).

countTokens: Logs the number of tokens that will be consumed by this prompt.

Gemini-pro-vision

Generate text from an image or let gemini pro tell you whats in your image using the geminiProVision method:

 

 void generateTextFromImage() async {
   
final response = await GeminiHandler().geminiProVision(
      text:
"Write a long story about the image.",
      path:
"path/to/your/image.jpg",
      temprature:
0.9,
      topP:
0.95,
      topK:
40,
      outputLength:
1024,
    );
 
   
if (response != null) {
      print(
"Generated Text: ${response.generatedText}");
    }
  }

 

The above code snippet GeminiHandler class to perform text generation with the geminiProVision method. Here’s an explanation of the parameters:

text: This parameter expects a string representing the input text or prompt for generating the output. In your example, it is set to “Write a long story about the image.”

path: This parameter specifies the path to the image file. In your example, it is set to “path/to/your/image.jpg.” It seems to indicate that the text generation is somehow related to the content or context of the image. pack.”).

imageBase64: This prameter takes the image as base64 format which is the form that Gemini APIs accept the image in.

file: This prameter takes image as File object, all the other conversions are handle in the package

temperature: A parameter controlling the randomness of the generated text (0.9 in this case).

topP: A parameter for nucleus sampling, controlling diversity (0.95 in this case).

topK: Number of top candidates to sample from during nucleus sampling (40 in this case).

outputLength: The desired length of the generated text (1024 characters).

countTokens: Logs the number of tokens that will be consumed by this prompt.

Example:

 

import 'package:flutter/material.dart';
import 'package:gemini_flutter/gemini_flutter.dart';

import 'image.dart';

void main() {
  GeminiHandler().initialize(apiKey:
"API_KEY");
  runApp(
const MyApp());
}

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

 
// This widget is the root of your application.
 
@override
  Widget build(BuildContext context) {
   
return MaterialApp(
      title:
'Gemini Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3:
true,
      ),
      home:
const MyHomePage(),
    );
  }
}

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

 
@override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String textData =
"";
 
@override
  Widget build(BuildContext context) {
   
return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title:
const Text("Gemini Demo"),
      ),
      body: Center(
        child: ListView(
          padding:
const EdgeInsets.symmetric(horizontal: 10),
          children: <Widget>[
           
const SizedBox(
              height:
20,
            ),
            Column(
              children: [
                ElevatedButton(
                    onPressed: ()
async {
                     
final response = await GeminiHandler()
                          .geminiPro(text:
"Write a story about  mustafa");
                      textData = response
                              ?.candidates?.first.content?.parts?.first.text ??
                         
"Failed to fetch data";
                      setState(() {});
                    },
                    child:
const Text("Gemini Pro")),
                ElevatedButton(
                    onPressed: ()
async {
                     
final response = await GeminiHandler().geminiProVision(
                          countTokens:
true,
                          base64Format: imageBase64,
                          text:
"I am blind can you describe me the image");
                      textData = response
                              ?.candidates?.first.content?.parts?.first.text ??
                         
"Failed to fetch data";
                      setState(() {});
                    },
                    child:
const Text("Gemini Pro Vision")),
              ],
            ),
           
const SizedBox(
              height:
20,
            ),
           
const Text(
             
'Press the button to get the response from Gemini',
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize:
16,
                  fontWeight: FontWeight.bold,
                  color: Colors.blueAccent),
            ),
           
const Text(
             
'Tokens Used: ',
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize:
16,
                  fontWeight: FontWeight.bold,
                  color: Colors.blueAccent),
            ),
           
const SizedBox(
              height:
20,
            ),
            Text(
              textData,
            ),
          ],
        ),
      ),
     
// This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

 

Reference

Gemini_flutter

Gemini


You can access the Gemini Postman collection using this link

326, Naroda business point, Haridarshan Cross Roads, Shri Balaji Rd, Nava Naroda, Ahmedabad, Gujarat 382330

C-1204, Ganesh Glory 11, Jagatpur Road, Gota, Ahmedabad, Gujarat, India.

Quick Links

Contact

Connect with us to go live 🚀

© 2022 Created with Techy Panther