Leerpad
Is zelfs een simpele AI-app bouwen niet een warboel van vectorstores, RAG-tools, API’s en debugging? Niet meer. Gemini 2.5 Pro heeft een lang contextvenster van 1 miljoen tokens (met plannen om dit te verdubbelen) en kan bestanden direct laden, zonder RAG- of vectorstore-tools.
Gemini 2.5 Pro is een redeneermodel dat uitblinkt in coderen, en het enorme contextvenster maakt echte businesswaarde mogelijk in codegerichte applicaties. Daarom laat ik je in deze blog zien hoe je een volwaardige webapp bouwt die broncode verwerkt en je in seconden helpt om je projecten te optimaliseren.
Ik duik meteen de code in—zoek je alleen een overzicht van het model, bekijk dan deze introblog over Gemini 2.5 Pro, en het nieuwste model, Gemini 3. Wil je meer weten over de nieuwe Computer Use-functie, bekijk dan onze volledige tutorial over Gemini 2.5 Computer Use.
Verbinden met de API van Gemini 2.5 Pro
Volg deze stappen om via de Google API toegang te krijgen tot het Gemini 2.5 Pro-model:
1. Installeren
Installeer eerst het Python-pakket google-genai. Voer de volgende opdracht uit in je terminal:
pip install google-genai
2. Een API-sleutel genereren
Ga naar Google AI Studio en genereer je API-sleutel. Stel de sleutel vervolgens in als een omgevingsvariabele op je systeem.

3. De GenAI-client maken
Gebruik de API-sleutel om de Google GenAI-client te initialiseren. Met deze client kun je communiceren met het Gemini 2.5 Pro-model.
import os
from google import genai
from google.genai import types
from IPython.display import Markdown, HTML, Image, display
API_KEY = os.environ.get("GEMINI_API_KEY")
client = genai.Client(api_key=API_KEY)
4. Het bestand laden
Laad het Python-bestand waarmee je wilt werken en maak een prompt voor het model.
# Load the Python file as text
file_path = "secure_app.py"
with open(file_path, "r") as file:
doc_data = file.read()
prompt = "Please integrate user management into the FastAPI application."
contents = [
types.Part.from_bytes(
data=doc_data.encode("utf-8"),
mime_type="text/x-python",
),
prompt,
]
5. Een reactie genereren
Maak een chatinstantie met het Gemini 2.5 Pro-model (gemini-2.5-pro-exp-03-25) en geef de inhoud van het bestand en de prompt door. Het model analyseert de code en genereert een reactie.
chat = client.aio.chats.create(
model="gemini-2.5-pro-exp-03-25",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
response = await chat.send_message(contents)
Markdown(response.text)
Binnen enkele seconden werd de contextbewuste reactie gegenereerd.

Let op: Gratis toegang tot het model is mogelijk tijdelijk niet beschikbaar door hoge belasting. Wacht een paar minuten en probeer het opnieuw.
6. Code uitvoeren (experimenteel)
Je kunt het model ook vragen om de code uit te voeren.
response = await chat.send_message('Please run the code to ensure that everything is functioning properly.')
Markdown(response.text)
Houd er rekening mee dat deze functie experimenteel is en beperkingen heeft. Zo kan het model geen webservers draaien, geen toegang krijgen tot het bestandssysteem, en geen netwerkoperaties uitvoeren.

Let op: het Gemini 2.5 Pro-model bevat geavanceerde "denk"-mogelijkheden. Deze zijn zichtbaar in Google AI Studio, maar niet opgenomen in de API-output.
Een code-analyse-app bouwen met Gemini 2.5 Pro
Met deze applicatie kunnen gebruikers bestanden uploaden, inclusief meerdere bestanden of zelfs een ZIP-archief met een volledig project, naar een chatinterface. Gebruikers kunnen vragen stellen over hun project, problemen oplossen of hun codebase verbeteren. In tegenstelling tot traditionele AI-code-editors die moeite hebben met grote contexten door hun beperkingen, kan Gemini 2.5 Pro met zijn lange contextvenster effectief een heel project analyseren en problemen oplossen.
1. Benodigde libraries installeren
Installeer gradio voor de UI en zipfile36 voor het verwerken van ZIP-bestanden.
pip install gradio==5.14.0
pip install zipfile36==0.1.3
2. Client en UI opzetten
Importeer de benodigde Python-packages, definieer globale variabelen, initialiseer de GenAI-client, stel UI-constanten in en maak een lijst met ondersteunde bestandsextensies.
import os
import zipfile
from typing import Dict, List, Optional, Union
import gradio as gr
from google import genai
from google.genai import types
# Retrieve API key for Google GenAI from the environment variables.
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
# Initialize the client so that it can be reused across functions.
CLIENT = genai.Client(api_key=GOOGLE_API_KEY)
# Global variables
EXTRACTED_FILES = {}
# Store chat sessions
CHAT_SESSIONS = {}
TITLE = """<h1 align="center">✨ Gemini Code Analysis</h1>"""
AVATAR_IMAGES = (None, "https://media.roboflow.com/spaces/gemini-icon.png")
# List of supported text extensions (alphabetically sorted)
TEXT_EXTENSIONS = [
".bat",
".c",
".cfg",
".conf",
".cpp",
".cs",
".css",
".go",
".h",
".html",
".ini",
".java",
".js",
".json",
".jsx",
".md",
".php",
".ps1",
".py",
".rb",
".rs",
".sh",
".toml",
".ts",
".tsx",
".txt",
".xml",
".yaml",
".yml",
]
3. Functie: extract_text_from_zip
De functie extract_text_from_zip() haalt tekstinhoud uit bestanden in een ZIP-archief en geeft deze terug als een woordenboek.
def extract_text_from_zip(zip_file_path: str) -> Dict[str, str]:
text_contents = {}
with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
for file_info in zip_ref.infolist():
# Skip directories
if file_info.filename.endswith("/"):
continue
# Skip binary files and focus on text files
file_ext = os.path.splitext(file_info.filename)[1].lower()
if file_ext in TEXT_EXTENSIONS:
try:
with zip_ref.open(file_info) as file:
content = file.read().decode("utf-8", errors="replace")
text_contents[file_info.filename] = content
except Exception as e:
text_contents[file_info.filename] = (
f"Error extracting file: {str(e)}"
)
return text_contents
4. Functie: extract_text_from_single_file
De functie extract_text_from_single_file() haalt tekstinhoud uit één bestand en geeft deze terug als een woordenboek.
def extract_text_from_single_file(file_path: str) -> Dict[str, str]:
text_contents = {}
filename = os.path.basename(file_path)
file_ext = os.path.splitext(filename)[1].lower()
if file_ext in TEXT_EXTENSIONS:
try:
with open(file_path, "r", encoding="utf-8", errors="replace") as file:
content = file.read()
text_contents[filename] = content
except Exception as e:
text_contents[filename] = f"Error reading file: {str(e)}"
return text_contents
5. Functie: upload_zip
De functie upload_zip() verwerkt geüploade bestanden, in ZIP-formaat of tekstbestanden, extraheert de tekstinhoud en voegt een bericht toe aan de chat.
def upload_zip(files: Optional[List[str]], chatbot: List[Union[dict, gr.ChatMessage]]):
global EXTRACTED_FILES
# Handle multiple file uploads
if len(files) > 1:
total_files_processed = 0
total_files_extracted = 0
file_types = set()
# Process each file
for file in files:
filename = os.path.basename(file)
file_ext = os.path.splitext(filename)[1].lower()
# Process based on file type
if file_ext == ".zip":
extracted_files = extract_text_from_zip(file)
file_types.add("zip")
else:
extracted_files = extract_text_from_single_file(file)
file_types.add("text")
if extracted_files:
total_files_extracted += len(extracted_files)
# Store the extracted content in the global variable
EXTRACTED_FILES[filename] = extracted_files
total_files_processed += 1
# Create a summary message for multiple files
file_types_str = (
"files"
if len(file_types) > 1
else ("ZIP files" if "zip" in file_types else "text files")
)
# Create a list of uploaded file names
file_list = "\n".join([f"- {os.path.basename(file)}" for file in files])
chatbot.append(
gr.ChatMessage(
role="user",
content=f"<p>📚 Multiple {file_types_str} uploaded ({total_files_processed} files)</p><p>Extracted {total_files_extracted} text file(s) in total</p><p>Uploaded files:</p><pre>{file_list}</pre>",
)
)
# Handle single file upload (original behavior)
elif len(files) == 1:
file = files[0]
filename = os.path.basename(file)
file_ext = os.path.splitext(filename)[1].lower()
# Process based on file type
if file_ext == ".zip":
extracted_files = extract_text_from_zip(file)
file_type_msg = "📦 ZIP file"
else:
extracted_files = extract_text_from_single_file(file)
file_type_msg = "📄 File"
if not extracted_files:
chatbot.append(
gr.ChatMessage(
role="user",
content=f"<p>{file_type_msg} uploaded: {filename}, but no text content was found or the file format is not supported.</p>",
)
)
else:
file_list = "\n".join([f"- {name}" for name in extracted_files.keys()])
chatbot.append(
gr.ChatMessage(
role="user",
content=f"<p>{file_type_msg} uploaded: {filename}</p><p>Extracted {len(extracted_files)} text file(s):</p><pre>{file_list}</pre>",
)
)
# Store the extracted content in the global variable
EXTRACTED_FILES[filename] = extracted_files
return chatbot
6. Functie: user
De functie user() voegt de tekstinvoer van een gebruiker toe aan de gespreksgeschiedenis van de chatbot.
def user(text_prompt: str, chatbot: List[gr.ChatMessage]):
if text_prompt:
chatbot.append(gr.ChatMessage(role="user", content=text_prompt))
return "", chatbot
7. Functie: get_message_content
De functie get_message_content() haalt de inhoud op van een bericht, dat een woordenboek of een Gradio-chatbericht kan zijn.
def get_message_content(msg):
if isinstance(msg, dict):
return msg.get("content", "")
return msg.content
8. Functie: send_to_gemini
De functie send_to_gemini() stuurt de prompt van de gebruiker naar Gemini AI en streamt de reactie terug naar de chatbot. Als er codebestanden zijn geüpload, worden die aan de context toegevoegd.
def send_to_gemini(chatbot: List[Union[dict, gr.ChatMessage]]):
global EXTRACTED_FILES, CHAT_SESSIONS
if len(chatbot) == 0:
chatbot.append(
gr.ChatMessage(
role="assistant",
content="Please enter a message to start the conversation.",
)
)
return chatbot
# Get the last user message as the prompt
user_messages = [
msg
for msg in chatbot
if (isinstance(msg, dict) and msg.get("role") == "user")
or (hasattr(msg, "role") and msg.role == "user")
]
if not user_messages:
chatbot.append(
gr.ChatMessage(
role="assistant",
content="Please enter a message to start the conversation.",
)
)
return chatbot
last_user_msg = user_messages[-1]
prompt = get_message_content(last_user_msg)
# Skip if the last message was about uploading a file (ZIP, single file, or multiple files)
if (
"📦 ZIP file uploaded:" in prompt
or "📄 File uploaded:" in prompt
or "📚 Multiple files uploaded" in prompt
):
chatbot.append(
gr.ChatMessage(
role="assistant",
content="What would you like to know about the code in this ZIP file?",
)
)
return chatbot
# Generate a unique session ID based on the extracted files or use a default key for no files
if EXTRACTED_FILES:
session_key = ",".join(sorted(EXTRACTED_FILES.keys()))
else:
session_key = "no_files"
# Create a new chat session if one doesn't exist for this set of files
if session_key not in CHAT_SESSIONS:
# Configure Gemini with code execution capability
CHAT_SESSIONS[session_key] = CLIENT.chats.create(
model="gemini-2.5-pro-exp-03-25",
)
# Send all extracted files to the chat session first
initial_contents = []
for zip_name, files in EXTRACTED_FILES.items():
for filename, content in files.items():
file_ext = os.path.splitext(filename)[1].lower()
mime_type = "text/plain"
# Set appropriate mime type based on file extension
if file_ext == ".py":
mime_type = "text/x-python"
elif file_ext in [".js", ".jsx"]:
mime_type = "text/javascript"
elif file_ext in [".ts", ".tsx"]:
mime_type = "text/typescript"
elif file_ext == ".html":
mime_type = "text/html"
elif file_ext == ".css":
mime_type = "text/css"
elif file_ext in [".json", ".jsonl"]:
mime_type = "application/json"
elif file_ext in [".xml", ".svg"]:
mime_type = "application/xml"
# Create a header with the filename to preserve original file identity
file_header = f"File: {filename}\n\n"
file_content = file_header + content
initial_contents.append(
types.Part.from_bytes(
data=file_content.encode("utf-8"),
mime_type=mime_type,
)
)
# Initialize the chat context with files if available
if initial_contents:
initial_contents.append(
"I've uploaded these code files for you to analyze. I'll ask questions about them next."
)
# Use synchronous API instead of async
CHAT_SESSIONS[session_key].send_message(initial_contents)
# For sessions without files, we don't need to send an initial message
# Append a placeholder for the assistant's response
chatbot.append(gr.ChatMessage(role="assistant", content=""))
# Send the user's prompt to the existing chat session using streaming API
response = CHAT_SESSIONS[session_key].send_message_stream(prompt)
# Process the response stream - text only (no images)
output_text = ""
for chunk in response:
if chunk.candidates and chunk.candidates[0].content.parts:
for part in chunk.candidates[0].content.parts:
if part.text is not None:
# Append the new chunk of text
output_text += part.text
# Update the last assistant message with the current accumulated response
if isinstance(chatbot[-1], dict):
chatbot[-1]["content"] = output_text
else:
chatbot[-1].content = output_text
# Yield the updated chatbot to show streaming updates in the UI
yield chatbot
# Return the final chatbot state
return chatbot
9. Functie: reset_app
De functie rest_app() reset de applicatie door de chatgeschiedenis en alle geüploade bestanden te wissen.
def reset_app(chatbot):
global EXTRACTED_FILES, CHAT_SESSIONS
# Clear the global variables
EXTRACTED_FILES = {}
CHAT_SESSIONS = {}
# Reset the chatbot with a welcome message
return [
gr.ChatMessage(
role="assistant",
content="App has been reset. You can start a new conversation or upload new files.",
)
]
10. Gradio UI-componenten
Laten we de Gradio-componenten definiëren: chatbot, tekstinvoer, uploadknop en bedieningsknoppen.
# Define the Gradio UI components
chatbot_component = gr.Chatbot(
label="Gemini 2.5 Pro",
type="messages",
bubble_full_width=False,
avatar_images=AVATAR_IMAGES,
scale=2,
height=350,
)
text_prompt_component = gr.Textbox(
placeholder="Ask a question or upload code files to analyze...",
show_label=False,
autofocus=True,
scale=28,
)
upload_zip_button_component = gr.UploadButton(
label="Upload",
file_count="multiple",
file_types=[".zip"] + TEXT_EXTENSIONS,
scale=1,
min_width=80,
)
send_button_component = gr.Button(
value="Send", variant="primary", scale=1, min_width=80
)
reset_button_component = gr.Button(
value="Reset", variant="stop", scale=1, min_width=80
)
# Define input lists for button chaining
user_inputs = [text_prompt_component, chatbot_component]
11. Gradio-appindeling
Laten we de Gradio-interface structureren met rijen en kolommen voor een overzichtelijke layout.
with gr.Blocks(theme=gr.themes.Ocean()) as demo:
gr.HTML(TITLE)
with gr.Column():
chatbot_component.render()
with gr.Row(equal_height=True):
text_prompt_component.render()
send_button_component.render()
upload_zip_button_component.render()
reset_button_component.render()
# When the Send button is clicked, first process the user text then send to Gemini
send_button_component.click(
fn=user,
inputs=user_inputs,
outputs=[text_prompt_component, chatbot_component],
queue=False,
).then(
fn=send_to_gemini,
inputs=[chatbot_component],
outputs=[chatbot_component],
api_name="send_to_gemini",
)
# Allow submission using the Enter key
text_prompt_component.submit(
fn=user,
inputs=user_inputs,
outputs=[text_prompt_component, chatbot_component],
queue=False,
).then(
fn=send_to_gemini,
inputs=[chatbot_component],
outputs=[chatbot_component],
api_name="send_to_gemini_submit",
)
# Handle ZIP file uploads
upload_zip_button_component.upload(
fn=upload_zip,
inputs=[upload_zip_button_component, chatbot_component],
outputs=[chatbot_component],
queue=False,
)
# Handle Reset button clicks
reset_button_component.click(
fn=reset_app,
inputs=[chatbot_component],
outputs=[chatbot_component],
queue=False,
)
12. De app starten
Laten we de Gradio-app lokaal starten met een wachtrij, zodat meerdere verzoeken verwerkt kunnen worden.
# Launch the demo interface
demo.queue(max_size=99, api_open=False).launch(
debug=False,
show_error=True,
server_port=9595,
server_name="localhost",
)
De Gemini 2.5 Pro Code Analysis-app testen
Om de webapp te starten, combineer je alle bovenstaande codebronnen in het bestand main.py (dat ik naar GitHub heb geüpload, zodat je het makkelijk kunt kopiëren). Voer het uit met de volgende opdracht:
python main.py
De webapp is beschikbaar op de URL: http://localhost:9595/
Je kunt de URL kopiëren en in je webbrowser plakken.
Zoals je ziet heeft de webapp een chatbotinterface. Je kunt hem net als ChatGPT gebruiken.

De knop “Upload” ondersteunt het uploaden van enkele en meerdere bestanden, én zipbestanden voor je project. Maak je dus geen zorgen als je project meer dan 20 bestanden bevat; de code-analyse-app kan het verwerken en naar de Gemini 2.5 Pro API sturen.

Laten we meerdere bestanden uploaden en Gemini 2.5 Pro vragen om ons project te verbeteren.
Zoals je ziet geeft het model correcte suggesties voor verbeteringen.

We kunnen het vragen om alle suggesties te implementeren in het bestand secure_app.py.

Wil je aan een ander project werken, klik dan op de knop “Reset” en begin een gesprek over het nieuwe project.

De broncode en configuraties zijn beschikbaar in de GitHub-repository: kingabzpro/Gemini-2.5-Pro-Coding-App.
Conclusie
Een volwaardige AI-applicatie bouwen is flink eenvoudiger geworden. In plaats van complexe applicaties te maken met tools als LangChain, vectorstores te integreren, prompts te optimaliseren of chains of thought toe te voegen, kunnen we simpelweg de Gemini 2.5 Pro-client via de Google API initialiseren. De Gemini 2.5 Pro Chat API kan verschillende bestandstypen direct verwerken, staat vervolgvragen toe en geeft uiterst nauwkeurige antwoorden.
Als gecertificeerd data scientist haal ik met passie het maximale uit de nieuwste technologie om innovatieve machinelearning-toepassingen te bouwen. Met een sterke achtergrond in spraakherkenning, data-analyse en -rapportage, MLOps, conversationele AI en NLP heb ik mijn vaardigheden aangescherpt in het ontwikkelen van intelligente systemen die echt impact maken. Naast mijn technische expertise ben ik ook een sterke communicator met een talent om complexe concepten terug te brengen tot heldere, beknopte taal. Daardoor ben ik uitgegroeid tot een veelgelezen blogger over data science, waar ik mijn inzichten en ervaringen deel met een groeiende community van data-professionals. Op dit moment richt ik me op contentcreatie en redactie, waarbij ik met large language models werk aan krachtige en aansprekende content die zowel bedrijven als individuen helpt het beste uit hun data te halen.

