Using Google Gemini With Flask, Vue and Vite
Tags: vue, javascript, beginners, python
Published: 2024-02-19 04:11:18

# Introduction

Hello! 😎
In this tutorial I'll show you how to implement Google's Gemini AI using Python Flask, Vuejs and Vite.

Flask is a micro web framework for Python, know for its simplicity and ease of use. It lets you create web applications quickly with minimal code.

Google's Generative AI is accessed via the package "google.generativeai", is a tool for generating content based on prompts. 😃

---

## Requirements

* Basic Python knowledge
* Google Generative AI API Key (Can be obtained via: https://aistudio.google.com/app/apikey)

---

## Creating The Service Application

First we will create the Flask server to handle requests, in this case a prompt and returning a response from Google Gemini.

For best practices we will be creating and running the server in a virtual environment, this can be set up with the following command:

```bash
python3 -m venv env
```

Once the environment has been created it can be activated via the following command:

```bash
source env/bin/activate
```

Next we will create the requirements.txt file with the packages needed for the server side, create a file called "requirements.txt" and populate it with the following:

```txt
google-generativeai
Flask
flask_cors
```

The packages can then be installed via the following command:

```bash
pip install -r requirements.txt
```

Now that the packages have been installed we can now write the code for the server side, create a new file called "main.py" and import the packages like so:

```python
import google.generativeai as genai
from flask import Flask, request, jsonify
from flask_cors import CORS
import os
```

* google.generativeai: imports the Google Generative AI library
* Flask: imports the Flask server
* request: allows us to access incoming requests
* jsonify: a helper function that turns responses into JSON format
* CORS: used to enable CORS which allows the API to be accessed from the front end

Next we will set up the server and Google Generative AI:

```python
app = Flask(__name__)
CORS(app)
api_key = os.getenv('GOOGLE_GENAI_API_KEY')
genai.configure(api_key=api_key)
```

The above creates a Flask application instance, CORS applies CORS settings to your flask app, making it accessible from any domain.
The Google Generative API key is also obtained from a variable called "GOOGLE_GENAI_API_KEY" and initialized.

The environment variable can be set via the following command:

```bash
export GOOGLE_GENAI_API_KEY="YOUR_KEY"
```

Next we will create the function to handle the request, which is as follows:

```python
@app.route("/prompt", methods=["POST"])
def prompt():
    data = request.json
    prompt = data.get("prompt", "")

    if not prompt:
        return jsonify({"error": "Prompt is required"}), 400

    try:
        model = genai.GenerativeModel("gemini-pro")

        response = model.generate_content(prompt)

        return jsonify({"response": response.text})
    except Exception as e:
        return jsonify({"error": "Request failed"}), 500
```

The above handles a POST request to the "prompt" route, it takes the response prompt data and passes it to Google Generative AI, as you can see we are using the "gemini-pro" model which only handles text. The response from the AI is then passed back to the front end in a JSON format.

Finally we will create the main function for the application:

```python
if __name__ == "__main__":
    app.run(debug=True)
```

Done! Thats the server side sorted, next we will create the front end with Vue and Vite. 😆

---

## Creating The Front End

Now that the server has been created, we can now create the front end for the application, in this example I have chosen Vue.

The project can be initialized via:

```bash
yarn create vite app --template vue
```

The above creates a new Vuejs application via Vite.

Next we will need to add a couple of packages to handle the request and the response.

Install the following packages via the yarn command:

```bash
yarn add bootstrap axios marked
```

Bootstrap handles the CSS, axios handles the request and marked will allow us to handle basic markdown which is returned quite a lot from Google Gemini.

To enable bootstrap in the project add the following import to "src/main.js" file:

```javascript
import 'bootstrap/dist/css/bootstrap.min.css';
```

Next we will create a custom component to handle the prompt request and response. Create a new file called "src/components/PromptForm.vue" and populate it with the following code:

```javascript
<template>
    <div class="container mt-5">
        <form @submit.prevent="submitPrompt">
            <div class="mb-3">
                <label for="promptText" class="form-label">Enter your prompt:</label>
                <input type="text" class="form-control prompt" id="promptText" v-model="prompt" :disabled="loading"/>
            </div>
            <button type="submit" class="btn btn-primary" :disabled="loading">Submit</button>
        </form>
        <br />
        <div v-if="response" v-html="formattedResponse"></div>

        <div v-if="loading" class="spinner-border" role="status">
            <span class="visually-hidden">Loading Response...</span>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';

export default {
    data() {
        return {
            prompt: '',
            response: undefined,
            loading: false
        };
    },
    computed: {
        formattedResponse() {
            return this.response ? marked(this.response) : '';
        }
    },
    methods: {
        async submitPrompt() {
            try {
                this.loading = true;
                const res = await axios.post('http://localhost:5000/prompt', {
                    prompt: this.prompt
                });

                this.response = res.data.response;
            } catch (error) {
                console.error(error);
            } finally {
                this.prompt = '';
                this.loading = false;
            }
        }
    }
}
</script>

<style scoped>
.spinner-border {
    display: inline-block;
    width: 2rem;
    height: 2rem;
    vertical-align: text-bottom;
    border: 0.25em solid currentColor;
    border-right-color: transparent;
    border-radius: 50%;
    animation: spinner-border .75s linear infinite;
}

@keyframes spinner-border {
    to { transform: rotate(360deg); }
}

.visually-hidden {
    position: absolute;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0;
}

.form-control {
    width: 100%;
    display: inline;
}
</style>
```

The above component displays a simple bootstrap form with one input element for the prompt, a submit button and the response. Once the user has entered a prompt and hit the submit button a request with the prompt will be sent to the server displaying a loading spinner, once the response has been obtained from the server the loading spinner disappears and the response is displayed to the user.

Thats it, now all we need to do is add the custom component to the main "App.vue" file, open "src/App.vue" and replace the contents with the following:

```javascript
import PromptForm from './components/PromptForm.vue'
</script>

<template>
    <PromptForm />
</template>
```

Done! Now the only thing left to do is to try the application out! 😊

---

## Starting The Application

To start the server side of the application simply run the following command:

```bash
python main.py
```

Next to start the front end just use the following command:

```bash
yarn dev
```

You should now be able to access and try out the application via: http://localhost:5173/

Simply enter a prompt hit submit and the response should be displayed once it has been processed like so:

![Meow Promt](https://i.ibb.co/VH135qC/meowing.png)

So thats why my cat is meowing. 😺

---

## Conclusion

Here I have shown how you can easily implement Google Generative AI into your projects. I have only touched on a simple prompt/response generator but you can use Google Generative AI to build chatbots, process images and various other things I have yet to try out. 👀

If you've built any cool things with Google Generative AI please show me.

I hope you learned something new from this tutorial and as always, happy coding! 😎

The code can also be found on my Github via:
https://github.com/ethand91/gemini-example

---

Like my work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee. 

[![“Buy Me A Coffee”](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/ethand9999)

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the [following course](https://algolab.so/p/algorithms-and-data-structure-video-course?affcode=1413380_bzrepgch