Hello! Welcome back.
In the last lesson, you enhanced your application by adding a readability score to your text analysis endpoint. This was a great exercise in using external Python libraries to add valuable features.
Today, we're taking a big step forward by integrating the power of a large language model directly into your application. Our goal is to create a Flask endpoint that uses the Gemini API for grammar and spelling correction. You've used Gemini through its web interface before, but now you'll learn to command it programmatically to act as an expert editor for your users.
This will involve three main steps:
- Setting up the official Google AI Python library in your project.
- Crafting a specific instruction, or "prompt," to tell the Gemini model exactly what to do.
- Building a new Flask endpoint that takes user text, sends it to Gemini for correction, and returns the result.
By the end of this lesson, you'll have a working AI-powered grammar checker API endpoint, like the one demonstrated in the image below.

1. Setting Up the Gemini Python Library
To communicate with the Gemini API from our Python code, we need to install Google's official library. Just like you did with textstat in the last lesson, we'll use pip. We also need to make sure our secret API key is handled securely.
This short video will walk you through the essential setup steps.
Gemini API with Python - Getting Started Tutorial
This video from Patrick Loeber's 'Gemini API with Python' tutorial clearly demonstrates how to install the necessary library and configure your API key.
Please watch the segment from 01:57 to 03:43. Pay close attention to the two key commands: pip install google-genai for installation and export GEMINI_API_KEY=... for setting up your API key as an environment variable.
As the video showed, there are two main tasks:
A. Install the Library
Open your terminal (with your virtual environment activated) and run:
pip install google-generativeai
B. Secure Your API Key
Hardcoding your API key directly in your script is a major security risk. The video shows using export to set it as an environment variable for a single terminal session. A more permanent and project-friendly method is to use a .env file. This approach is demonstrated in the following article.
Google AI Gemini API: A Complete Example of a Python Flask ...
The article 'Google AI Gemini API: A Complete Example of a Python Flask...' shows a common best practice for handling API keys in a project.
Read the section 'Example Code' (part â“¶) which starts after the list of package installation commands. Focus on how it recommends creating a .env file to store your GEMINI_API_KEY. You will also need to install one more package to read this file: pip install python-dotenv.
To follow this best practice:
- Install the
python-dotenvpackage:pip install python-dotenv - In the main folder of your project (the same level as
app.py), create a new file named.env. - Inside the
.envfile, add this line, replacing<YOUR_API_KEY>with the key you got from Google AI Studio:GEMINI_API_KEY=<YOUR_API_KEY>
This .env file will be loaded by our application to securely access the key.
2. The Art of the Prompt: Instructing the AI
The key to making a large language model perform a specific task is giving it clear, precise instructions. This is often called "prompt engineering." We don't want a long conversation or a creative story; we want a simple grammar and spelling correction.
To do this, we'll provide a system_instruction that tells the model its role before it even sees the user's text.
How to Use Gemini API in Python
The article 'How to Use Gemini API in Python' by Listendata provides a perfect example of how to create a system instruction for grammar checking.
Please read the section titled 'How to Set Instructions'. Focus on the Python code block that defines an instruction variable and uses it in the system_instruction argument. This is exactly the technique we will use.
As the article shows, a good instruction for our task would be:"You are an expert editor specializing in English. Correct the grammar and spelling of the text I provide. Only return the corrected text, without any additional comments or explanations."
This prompt is effective because it:
- Defines a role: "You are an expert editor..."
- Specifies the task: "Correct the grammar and spelling..."
- Constrains the output: "Only return the corrected text..."
3. Creating the Grammar Correction Endpoint
Now, let's put it all together in a new Flask endpoint. We will add a route, /api/correct-grammar, to your app.py file. This endpoint will receive text, use the Gemini API with our special instruction, and return the corrected version.
Here is the code to add to your app.py. Read through it carefully, paying attention to the comments that explain each new part.
# In app.py
# 1. Add these new imports at the top of your file
import os
import google.generativeai as genai
from dotenv import load_dotenv
# 2. Load the environment variables from the .env file
load_dotenv()
# 3. Configure the Gemini API with your key
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
# Initialize the Gemini model
model = genai.GenerativeModel('gemini-1.5-flash')
# ... your existing Flask app and other endpoints ...
# 4. Define the new endpoint for grammar correction
@app.route('/api/correct-grammar', methods=['POST'])
def correct_grammar_endpoint():
# Get the text from the request
user_text = request.json.get('text')
if not user_text:
return jsonify({'error': 'No text provided'}), 400
# The specific instruction for the AI
prompt = (
"You are an expert editor specializing in English. "
"Correct the grammar and spelling of the following text. "
"Only return the corrected text, without any additional comments or explanations.\n\n"
"Text: " + user_text
)
try:
# 5. Call the Gemini API
response = model.generate_content(prompt)
# 6. Create the JSON response with the corrected text
corrected_text = response.text
return jsonify({'corrected_text': corrected_text.strip()})
except Exception as e:
# Handle potential API errors
print(f"An error occurred: {e}")
return jsonify({'error': 'Failed to communicate with the AI model.'}), 500
Code Breakdown:
- We import the necessary libraries:
osto interact with the operating system,genaifor the Gemini API, andload_dotenvto read our.envfile. load_dotenv()reads theGEMINI_API_KEYfrom your.envfile and makes it available to the application.genai.configure()sets up the library with your key.- We define a new route
/api/correct-grammarthat acceptsPOSTrequests. - Inside the function, we construct our detailed prompt and call
model.generate_content(). We also wrap this in atry...exceptblock, which is good practice for handling potential network or API errors. - We extract the text from the response and send it back to the client in a JSON object.
Test your understanding!
In the code above, why is it better to combine the instruction and the user_text into a single prompt string, rather than just sending the user_text to the Gemini model by itself?
Show answer
If we only sent the user_text, the Gemini model wouldn't know what to do with it. It might try to continue the sentence, translate it, or answer a question it thinks is hidden in the text. By providing the detailed instruction ("You are an expert editor..."), we guide the model to perform the specific task of grammar and spelling correction.
4. Testing Your New AI Endpoint
It's time to see your AI corrector in action!
- Save your updated
app.pyfile. - Run your Flask application from the terminal:
python app.py. - Open a tool like Postman or Insomnia.
- Create a new
POSTrequest tohttp://127.0.0.1:5000/api/correct-grammar. - In the
Bodytab, selectJSONand enter the following:{ "text": "i is a programer and i luv to code." } - Send the request.
If everything is set up correctly, you should receive a JSON response from your server like this:
{
"corrected_text": "I am a programmer and I love to code."
}
Congratulations! You have successfully integrated a powerful AI feature into your web application's backend.
Conclusion
In this lesson, you moved beyond simple statistics and connected your application to a state-of-the-art AI model. This is a huge milestone in building your writing assistant.
Key Takeaways:
- You learned how to install the
google-generativeailibrary and securely configure it using a.envfile and environment variables. - You saw the power of prompt engineering—crafting specific instructions to guide an AI model's behavior.
- You built a new Flask endpoint that takes user input, communicates with an external API (Gemini), and returns the processed result.
- You implemented a
try...exceptblock to make your API call more robust.
The structure you built today—an endpoint that takes text and a prompt—is incredibly versatile. In the next lesson, we will leverage this exact same pattern to create another endpoint for text summarization, showing just how quickly you can add new AI features once the foundation is in place.