github / github/platform-samples
Google chatbot AI
- Dominant language
- Shell
- Stars
- 2.2k
- Forks
- 1.9k
- Avg merge
- 7d 19h
- Merged PRs (30d)
- 1
Description
import os
from flask import Flask, render_template_string, request, jsonify
import requests
import time
app = Flask(__name__)
# --- Configuration ---
# Note: In this environment, the API key is handled automatically.
# We initialize it as an empty string for the request logic.
API_KEY = ""
MODEL_NAME = "gemini-2.5-flash-preview-09-2025"
API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_NAME}:generateContent?key={API_KEY}"
# --- HTML Template (Embedded for Single-File Portability) ---
HTML_TEMPLATE = """
AI Assistant
.chat-container { height: calc(100vh - 160px); }
.message-bubble { max-width: 80%; word-wrap: break-word; }
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
Gemini Flask AI
Online
Send
const chatWindow = document.getElementById('chat-window');
const chatForm = document.getElementById('chat-form');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
function appendMessage(text, isUser) {
const wrapper = document.createElement('div');
wrapper.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`;
const bubble = document.createElement('div');
bubble.className = `message-bubble p-4 rounded-2xl shadow-sm ${
isUser
? 'bg-indigo-600 text-white rounded-tr-none'
: 'bg-slate-100 text-slate-800 rounded-tl-none'
}`;
bubble.innerText = text;
wrapper.appendChild(bubble);
chatWindow.appendChild(wrapper);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
chatForm.onsubmit = async (e) => {
e.preventDefault();
const message = userInput.value.trim();
if (!message) return;
// Update UI
appendMessage(message, true);
userInput.value = '';
userInput.disabled = true;
sendBtn.disabled = true;
// Fetch AI Response
try {
const response = await fetch('/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
const data = await response.json();
if (data.error) {
appendMessage("Error: " + data.error, false);
} else {
appendMessage(data.response, false);
}
} catch (err) {
appendMessage("Failed to connect to server.", false);
} finally {
userInput.disabled = false;
sendBtn.disabled = false;
userInput.focus();
}
};
"""
# --- Helper Function: Call Gemini API ---
def call_gemini_api(prompt):
payload = {
"contents": [{
"parts": [{"text": prompt}]
}],
"systemInstruction": {
"parts": [{"text": "You are a helpful, concise AI assistant integrated into a Flask web application."}]
}
}
# Implement exponential backoff for reliability
retries = 5
for i in range(retries):
try:
response = requests.post(API_URL, json=payload)
response.raise_for_status()
data = response.json()
return data.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', "No response.")
except Exception:
if i == retries - 1:
return "I'm having trouble connecting to my brain right now. Please try again later."
time.sleep(2 ** i)
return "Something went wrong."
# --- Routes ---
@app.route('/')
def home():
return render_template_string(HTML_TEMPLATE)
@app.route('/ask', methods=['POST'])
def ask():
user_data = request.json
user_message = user_data.get('message', '')
if not user_message:
return jsonify({"error": "Empty message"}), 400
ai_response = call_gemini_api(user_message)
return jsonify({"response": ai_response})
if __name__ == '__main__':
# Setting host to 0.0.0.0 makes it accessible on the local network
app.run(debug=True, port=5000)
Contributor guide
Research direction
The issue supplies a standalone Flask application with embedded HTML and JavaScript, but names no repository file, test, or specific change beyond “Google chatbot AI.” First clarify whether this is intended as a new platform sample and define its required integration, configuration, and acceptance criteria before locating an entry point or deciding what done means.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- flask, javascript, python, tailwindcss
- Domain
- ai, api, backend, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 15/100