Lesson 3 of 6
Create Your First Gemini-Powered Assistant
On this page
This is where the course becomes code. You will install Google's official Python SDK, send one request to Gemini and print the reply. Then you will wrap that in a loop so you can hold a short conversation in your terminal. It is a small program, but it contains every ingredient the later lessons build on.
One decision first. Google's documentation now recommends a newer interface, the Interactions API, for new projects, and describes the older generateContent method as legacy. This course teaches the Interactions API because it is the one Google currently recommends and it supports both system instructions and manual function calling in Python. Interfaces change, so if the code here stops working, compare it with the official quickstart (opens in a new tab) first.
What you will learn
- Install the official Google Gen AI SDK for Python in a virtual environment.
- Load the API key from .env without writing it in code.
- Send a first request and print the response text.
- Explain each part of the program, including the model constant and the previous interaction ID.
Before you start
- Lesson 2 finished: the gemini-order-helper folder, an active virtual environment and a .env file with GEMINI_API_KEY.
- Python 3.10 or newer.
- Ability to run a Python file from a terminal.
What a first request really is
Your program will create a client, which is an object that knows how to talk to the Gemini API with your key. It will then call one method on that client and give it two things: the name of a model and the text of your question. The service returns an object describing what the model produced. You read the text from it.
In the Interactions API, one request and its response together are called an interaction. Every interaction has an id. Later, you can hand an earlier interaction's ID to a new request to continue the same conversation, so your program does not need to resend the whole history itself. That makes multi-turn chat code short.
Install the SDK and python-dotenv
Step 1: Check that the virtual environment is active
Your prompt should start with (.venv). If it does not, activate it as in lesson 2. Installing into the wrong place is a common cause of ModuleNotFoundError later.
What you should see: (.venv) appears in the prompt.
Step 2: Install both packages
The Google Gen AI SDK is published as google-genai. python-dotenv reads your .env file. Google's quickstart gives the current install command, so compare it with this if yours differs.
Bashterminal python -m pip install -U google-genai python-dotenvWhat you should see: pip reports Successfully installed, listing google-genai and python-dotenv among others.
Step 3: Confirm the import works
A one-line check saves confusion later. Note that the package is google-genai but you import it from google, as genai.
Bashterminal python -c "from google import genai; print('SDK import OK')"What you should see: SDK import OK is printed.
Send your first request
Create agent.py in your project folder and paste the program below. Read the comments; they explain intent. The model name sits in a single constant at the top so that you change it in one place.
import sys
from dotenv import load_dotenv
from google import genai
# Read GEMINI_API_KEY from the .env file into this process's environment.
# This must happen before the client is created.
load_dotenv()
# The model to use. Model names change and older ones are retired, so check
# Google's models page for a current one before you run this:
# https://aistudio.google.com/docs/models
MODEL = "gemini-3.8-flash"
def main() -> None:
# The client reads GEMINI_API_KEY from the environment by itself.
# We never write the key in this file.
client = genai.Client()
# One request and its response together make an interaction.
interaction = client.interactions.create(
model=MODEL,
input="In two sentences, explain what a bookshop loyalty card is.",
)
# output_text is the model's reply joined into a plain string.
print(interaction.output_text)
if __name__ == "__main__":
try:
main()
except Exception as error:
# Keep the message short and avoid printing anything that could
# contain secrets. Lesson 6 improves this error handling.
print("The request failed:", type(error).__name__, error)
sys.exit(1)Version 1: one question, one answer.
Step 1: Check the model name
Open the models page and confirm that the name in MODEL is currently listed for your account. Pick a different listed name if it is not. The model list, and which models you can use, vary by account, region and over time.
What you should see: You are confident the name exists on the models page.
Step 2: Run the program
Run it from inside gemini-order-helper with the virtual environment active.
Bashterminal python agent.pyWhat you should see: A short explanation of a loyalty card is printed. The wording will differ on every run.
A loyalty card is a small card, physical or digital, that records a customer's purchases at a shop. After a set amount of spending or visits, the shop gives a reward such as a discount.Reading the code in short pieces
| Piece | What it does | Why it is needed |
|---|---|---|
| load_dotenv() | Copies the lines in .env into the environment. | The SDK looks for GEMINI_API_KEY there. Without this call, your key is invisible to Python. |
| MODEL = "..." | Holds the model name in one place. | Model names change. One constant means one edit. |
| genai.Client() | Creates the object that sends requests. | It carries your key and settings for every call. |
| client.interactions.create(...) | Sends the request. | This is the Interactions API call. It needs a model and an input. |
| interaction.output_text | The reply as a string. | The full response has more structure, which you will use for functions in lesson 5. |
| try / except | Catches failures and prints a short message. | Keys, networks and limits can all fail. A friendly message beats a long traceback. |
Notice what is not here: no key, no HTTP code and no JSON handling. The SDK takes care of those. That is the benefit of the official SDK compared with writing raw web requests.
Turn it into a small conversation
A single question is not an assistant. Replace main() with the version below. It keeps asking you for input, sends each question and chains the turns using previous_interaction_id, so Gemini remembers what was said earlier.
def main() -> None:
client = genai.Client()
# None means "no earlier turn yet". After each reply we store its id.
previous_id = None
print("Lantern Lane Books helper. Type 'quit' to leave.")
while True:
question = input("You: ").strip()
if question.lower() in {"quit", "exit"}:
break
if not question:
continue # ignore empty lines instead of paying for a request
# Only send previous_interaction_id once we actually have one.
options = {}
if previous_id is not None:
options["previous_interaction_id"] = previous_id
interaction = client.interactions.create(
model=MODEL,
input=question,
**options,
)
previous_id = interaction.id
print("Gemini:", interaction.output_text)Replace main() with this loop. The imports and MODEL stay as they were.
Lantern Lane Books helper. Type 'quit' to leave.
You: My name is Sam.
Gemini: Nice to meet you, Sam. How can I help?
You: What is my name?
Gemini: You told me your name is Sam.
You: quitReusable prompt
Code explainer
Ask an assistant to explain your program line by line so you can check your own understanding.
Explain this Python program to a beginner, in order, one short paragraph per block. Point out where the API key is read, where the network request happens and what could fail. Do not rewrite the code.
[paste agent.py here]Show the reusable template
Replace each {{placeholder}} with your own details.
Explain this {{language}} program to a beginner, in order, one short paragraph per block. Point out where the API key is read, where the network request happens and what could fail. Do not rewrite the code.
{{code}}Common errors and how to fix them
ModuleNotFoundError: No module named 'google' or 'dotenv'.
Why it happens: The packages were installed outside the virtual environment, or the environment is not active.
Fix: Activate .venv, then run python -m pip install -U google-genai python-dotenv again so pip and python match.
An error about a missing API key or default credentials.
Why it happens: GEMINI_API_KEY is not in the environment. load_dotenv() may be missing, .env may be in another folder, or the line has quotes or spaces.
Fix: Run from the folder that holds .env, check the line is exactly GEMINI_API_KEY=your-key, and make sure load_dotenv() runs before genai.Client().
A 404 or "model not found" style error.
Why it happens: The name in MODEL is not available to your account or has been retired.
Fix: Open the models page, choose a currently listed model and change only the MODEL constant.
A permission or quota error such as 403 or 429.
Why it happens: The key is invalid, restricted, or you have reached a limit that depends on your account, region and model.
Fix: Check the key page and the troubleshooting guide, wait before retrying, and read the site's guide on API errors.
AttributeError: 'Client' object has no attribute 'interactions'.
Why it happens: An old SDK version is installed.
Fix: Upgrade with python -m pip install -U google-genai and check the quickstart for current usage.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Make the first request your own
Change the program so that it asks a different bookshop question of your choice, then add a second constant, MAX_QUESTION_CHARS, and refuse any question longer than that before calling the API.
You will need
- Your working agent.py.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Use len(question) and compare it to the constant.
- Put the check before the interaction call, next to the empty-line check.
Show a model answer
Add MAX_QUESTION_CHARS at the top, and after stripping the input write: if len(question) > MAX_QUESTION_CHARS: print a short message; continue. Checking on your side saves requests and starts a habit of validating input before using it, which lesson 6 extends to function arguments.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. It only loads values from the file into the environment, locally. The first option is tempting because the key does get used for requests, but that is the client's job after the key has been found.
Show the answer and explanation
Answer: B. Models are listed and retired over time and availability differs by account. A constant makes the update a one-line change. The SDK has no such rule.
Show the answer and explanation
Answer: B. The id links the new request to the stored earlier one. The loop alone does not help because each API request is separate, and creating a new client has no effect on memory.
- Written by
- PromptFable Editorial
- Last updated 13 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Gemini API quickstart(opens in a new tab)
Google · Official documentation
- Interactions API overview(opens in a new tab)
Google · Official documentation
- Gemini models(opens in a new tab)
Google · Official documentation · Check here for current model names and retirements.
- Using Gemini API keys(opens in a new tab)
Google · Official documentation
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.