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:
python3 -m venv env
Once the environment has been created it can be activated via the following command:
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:
google-generativeai
Flask
flask_cors
The packages can then be installed via the following command:
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:
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:
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:
export GOOGLE_GENAI_API_KEY="YOUR_KEY"
Next we will create the function to handle the request, which is as follows:
@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:
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:
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:
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:
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:
<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:
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:
python main.py
Next to start the front end just use the following command:
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:
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.
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
Top comments (2)
Nice content!
Thanks :)