Google AI Chatbot:使用 Flask 和 Python 建立聊天機械人
Google AI Chatbot
這篇教學示範如何使用 Python、Flask 和 Google AI Studio API 建立聊天機械人,並以 VS Code 設定環境及執行程式。文中使用的模型名稱為 gemini-3.5-flash-lite,並提到可使用 300$ 免費額度。
1/ Install Visual Studio Code
2/ Install Python and get the path where python is installed
C:\Users\XXXXX\Python\pythoncore-3.15-64\python.exe
python --version
python path
3/ go to aistudio.google.com and use 300$ free credit. Create API Key
4/ Check the doumentation for api-key usage according to the requirement. In my case I am using Python. So, I refer the python code
5/ Create a workspace folder on your desktop and open using VS Code editor. Then open the terminal in the path using view --> Open terminal
6/ Create environment in the path for python using below command
python -m venv myEnv
7/ Activate virtual environment
cd .\myEnv\Scripts
.\Activate.ps1
if security error occur then
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
once activated, it shows (yourenv) in greencolor
8/ From the command prompt go to the directory where Pythoncode is writted, same place install flask
pip install Flask
pip list --> will show if installed or not
pip install google-generativeai
9/ Now in the workspace folder create one more folder called templates
10/ In the templates folder create Welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Venkatesh AI Chatbot</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f4f6f9;
}
.chat-container {
max-width: 900px;
margin: 30px auto;
}
.chat-header {
background: #8e95a0;
color: white;
padding: 15px;
border-radius: 10px 10px 0 0;
font-size: 24px;
font-weight: bold;
text-align: center;
}
.chat-window {
height: 500px;
overflow-y: auto;
background: white;
border: 1px solid #dee2e6;
padding: 15px;
}
.message {
margin-bottom: 12px;
padding: 10px 15px;
border-radius: 10px;
max-width: 80%;
word-wrap: break-word;
clear: both;
}
.user-message {
background-color: #d1e7dd;
float: right;
}
.bot-message {
background-color: #e9ecef;
float: left;
}
.input-section {
border: 1px solid #dee2e6;
border-top: none;
padding: 15px;
background: white;
border-radius: 0 0 10px 10px;
}
textarea {
resize: none;
}
.typing {
font-style: italic;
color: gray;
}
</style>
</head>
<body>
<div class="container chat-container">
<!-- Header -->
<div class="chat-header">
Venkatesh AI Chatbot
</div>
<!-- Chat Window -->
<div id="chatWindow" class="chat-window">
<div class="message bot-message">
Hello! How can I help you today?
</div>
<div style="clear:both;"></div>
</div>
<!-- Input Area -->
<div class="input-section">
<div class="row">
<div class="col-md-10">
<textarea
id="userInput"
class="form-control"
rows="3"
placeholder="Type your message here..."></textarea>
</div>
<div class="col-md-2 d-grid">
<button id="sendBtn" class="btn btn-primary">
Send
</button>
</div>
</div>
</div>
</div>
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
function appendMessage(message, type)
{
let cssClass = (type === "user")
? "user-message"
: "bot-message";
$("#chatWindow").append(`
<div class="message ${cssClass}">
${message}
</div>
<div style="clear:both;"></div>
`);
scrollToBottom();
}
function scrollToBottom()
{
$("#chatWindow").scrollTop(
$("#chatWindow")[0].scrollHeight
);
}
$("#sendBtn").on("click", function ()
{
sendMessage();
});
$("#userInput").on("keypress", function(e)
{
if(e.which === 13 && !e.shiftKey)
{
e.preventDefault();
sendMessage();
}
});
function sendMessage()
{
let userText = $("#userInput").val().trim();
if(userText === "")
return;
// Append User Message
appendMessage(userText, "user");
// Clear input
$("#userInput").val("");
// Show typing indicator
let typingId = "typing_" + Date.now();
$("#chatWindow").append(`
<div id="${typingId}" class="message bot-message typing">
AI is typing...
</div>
<div style="clear:both;"></div>
`);
scrollToBottom();
// AJAX POST Call
$.ajax({
//url: "http://127.0.0.1:5000/chat",
url: "/chat",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
message: userText
}),
success: function(response)
{
$("#" + typingId).remove();
appendMessage(
response.response || "No response received",
"bot"
);
},
error: function(xhr)
{
$("#" + typingId).remove();
console.log(xhr.responseText);
appendMessage(
"Error: " + xhr.responseText,
"bot"
);
}
});
}
</script>
</body>
</html>
11/ In the workspace folder create Welcome.py
from flask import Flask, render_template, request, jsonify
import google.generativeai as genai
import os
# Replace with your actual Gemini API key
GOOGLE_API_KEY = "your_APIKe"
genai.configure(api_key=GOOGLE_API_KEY)
#for m in genai.list_models():
# print(m.name)
#model = genai.GenerativeModel("gemini-1.5-flash")
model = genai.GenerativeModel("gemini-3.5-flash-lite")
chat = model.start_chat(history=[])
app = Flask(__name__)
@app.route('/')
def index():
return render_template('Welcome.html')
@app.route('/chat', methods=['POST'])
def chat_response():
user_input = request.json.get('message')
if not user_input:
return jsonify({"error": "No message provided"}), 400
try:
response_raw = chat.send_message(user_input)
#print(response_raw)
print("RAW:", response_raw)
response = response_raw.text
print("TEXT:", response)
return jsonify({"response": response})
except Exception as e:
print(f"Error: {e}")
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
12/ Dubug the output and open the chatbot in Chrome and test
All the best!!!!!!!!!!!!!!!!!!!!!!!!
來源:DEV Community · dev.to