# Lets talk to Gemini Ai

We need an Api Key , you can generate one from

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.

[Get an API key](https://makersuite.google.com/app/apikey)

**Secure your API key**

Keep your API key secure. We strongly recommend that you do *not* include the API key directly in your code, or check files that contain the key into version control systems. Instead, you should use a secrets store for your API key.

All the snippets in this quickstart assume that you're accessing your API key as a process environment variable. If you're developing a Flutter app, you can use `String.fromEnvironment` and pass `--dart-define=API_KEY=$API_KEY` to `flutter build` or `flutter run` to compile with the API key since the process environment will be different when running the app.

{% embed url="<https://aistudio.google.com/app/>" %}

Create a new file consts.dart to store api key , we can also use environments.

```dart
const apiKey = "";
```

Chat logic is in char\_widget.dart

we will be using Gemini model : gemini-1.0-pro

in the initState let's initialise the model, for this, we will need to import  in pubspec.yaml

```
flutter pub add google_generative_ai
```

```dart
google_generative_ai
```

create variable for model and  chat session

```dart
late final GenerativeModel _model;
late final ChatSession _chat;

```

```dart
void initState() {
    super.initState();
    _model = GenerativeModel(
      model: 'gemini-1.0-pro',
      apiKey: apiKey,
    );
     
    _chat = _model.startChat(history: [
      Content.text(
          "Let's play a two-player game where I have to guess the names of movies from the emojis and then I will ask the same."),
      Content.model(
          [TextPart("Here's the first one: 🍫🏭👦🏻. What movie is this?")])
    ]);
  }
```

&#x20;We have created a chat session with some context and a prompt

The chat conversation can be displayed in the list, modify listviewbuilder to show the chat messages between AI and user

```dart
ListView.builder(
            shrinkWrap: true,
            controller: _scrollController,
            itemBuilder: (context, idx) {
              var content = _chat.history.toList()[idx];
              var text = content.parts
                  .whereType<TextPart>()
                  .map<String>((e) => e.text)
                  .join('');
              return MessageWidget(
                text: text,
                isFromUser: content.role == 'user',
              );
            },
            itemCount: _chat.history.length,
          ),
```

When the user types a message \_sendChatMessage is called

```dart
Future<void> _sendChatMessage(String message) async {
    setState(() {
      _loading = true;
    });

    try {
      var response = await _chat.sendMessage(
        Content.text(message),
      );
      var 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();
    }
  }
```

<figure><img src="/files/zvWrzPImRbyyZEcvXY62" alt=""><figcaption></figcaption></figure>

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sumiths-organization.gitbook.io/workshop/lets-talk-to-gemini-ai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
