github / github/platform-samples

Google chatbot AI

Abierto
#810 0 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
Shell
Estrellas
2.2k
Forks
1.9k
Merge medio
7 d 19 h
PR fusionados (30 d)
1

Descripción

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







Hello! I'm your AI assistant powered by Flask and Gemini. How can I help you today?







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)

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

El issue proporciona una aplicación Flask independiente con HTML y JavaScript integrados, pero no indica ningún archivo del repositorio, prueba ni cambio específico más allá de “Google chatbot AI”. Primero aclara si esto pretende ser un nuevo ejemplo de plataforma y define los criterios necesarios de integración, configuración y aceptación antes de localizar un punto de entrada o decidir qué significa que esté terminado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
flask, javascript, python, tailwindcss
Área
ai, api, backend, web-dev
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
15/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.