github / github/platform-samples

Google chatbot AI

Đang mở
#810 0 bình luận 0 reaction 0 người được giao Xem trên GitHub
Ngôn ngữ chính
Shell
Star
2.2k
Fork
1.9k
Merge trung bình
7 ngày 19 giờ
Pull request đã merge (30 ngày)
1

Mô tả

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)

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
flask, javascript, python, tailwindcss
Lĩnh vực
ai, api, backend, web-dev
Loại issue
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Cần làm rõ
Mức phù hợp với người mới
15/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.