github / github/platform-samples

Google chatbot AI

未關閉
#810 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
主要語言
Shell
星號
2.2k
分支
1.9k
平均合併
7 天 19 小時
30 天內合併 PR
1

描述

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)

貢獻指南

開啟貢獻指南

研究方向

該 issue 提供了一個嵌入 HTML 和 JavaScript 的獨立 Flask 應用程式,但除了「Google chatbot AI」之外,沒有指出任何 repository 檔案、測試或具體變更。首先釐清這是否旨在作為新的平台範例,並在尋找進入點或決定完成標準之前,定義其所需的整合、設定與驗收標準。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
flask, javascript, python, tailwindcss
領域
ai, api, backend, web-dev
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
需要釐清
新手友好度
15/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。