如何实现JavaScript与Python互传变量/函数?AI聊天Bot实操需求
实现JavaScript与Python聊天机器人逻辑的交互
核心思路
JavaScript运行在浏览器前端,Python代码运行在服务器端,两者无法直接调用函数,需通过HTTP接口实现通信:用Python搭建简单Web服务,暴露接口接收前端发送的用户消息,调用response()函数处理后返回结果,前端通过fetch请求该接口获取响应。
具体实现步骤
1. 用Flask搭建Python后端服务
首先安装Flask依赖:
pip install flask flask-cors nltk scikit-learn
修改并完善你的Python代码,添加Flask接口包装,同时修正原代码的语法错误:
from flask import Flask, request, jsonify from flask_cors import CORS import random import nltk from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity # 下载NLTK所需资源 nltk.download('punkt') nltk.download('wordnet') # 初始化Flask应用并解决跨域问题 app = Flask(__name__) CORS(app) # 替换为你的实际训练语料句子列表 sent_tokens = ["你的训练语料句子1", "你的训练语料句子2", "这里填充真实的语料内容"] lemmatizer = WordNetLemmatizer() def LemNormalize(text): return [lemmatizer.lemmatize(token) for token in nltk.word_tokenize(text.lower())] def response(user_response): robo_response = '' sent_tokens.append(user_response) TfIdVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfIdVec.fit_transform(sent_tokens) vals = cosine_similarity(tfidf[-1], tfidf) idx = vals.argsort()[0][-2] flat = vals.flatten() flat.sort() req_tfidf = flat[-2] # 问候语匹配逻辑 GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up", "hey") GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I'm glad you're talking to me"] for word in user_response.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSES) # 无匹配内容的回复 if req_tfidf == 0: robo_response_options = [ "Sorry, I have not been trained to answer that yet!", "Sorry, I cannot answer to that!" ] return random.choice(robo_response_options) # 返回匹配到的语料内容 robo_response = sent_tokens[idx] return robo_response # 定义接收前端请求的接口 @app.route('/get_bot_response', methods=['POST']) def get_bot_response(): data = request.get_json() user_msg = data.get('user_message', '') bot_reply = response(user_msg) return jsonify({'reply': bot_reply}) if __name__ == '__main__': app.run(debug=True)
2. 修改JavaScript代码,发送请求并渲染响应
更新你的JS函数,实现消息发送、请求后端接口、接收并显示机器人回复的逻辑:
async function sendMessage() { const inputElement = document.getElementById('input-chat'); const userResponse = inputElement.value.trim(); if (!userResponse) return; // 显示用户消息到聊天界面 const chatBox = document.getElementById('chat-box'); const userMsgElement = document.createElement('div'); userMsgElement.className = 'user-message'; userMsgElement.textContent = userResponse; chatBox.appendChild(userMsgElement); inputElement.value = ''; try { // 发送请求到后端接口 const response = await fetch('http://localhost:5000/get_bot_response', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ user_message: userResponse }), }); const result = await response.json(); // 显示机器人回复到聊天界面 const botMsgElement = document.createElement('div'); botMsgElement.className = 'bot-message'; botMsgElement.textContent = result.reply; chatBox.appendChild(botMsgElement); // 滚动到聊天框底部 chatBox.scrollTop = chatBox.scrollHeight; } catch (error) { console.error('请求失败:', error); } } // 绑定发送按钮点击事件 document.getElementById('send-btn')?.addEventListener('click', sendMessage); // 绑定回车键发送事件 document.getElementById('input-chat')?.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); });
3. 关键注意事项
- 语料库配置:
sent_tokens必须替换为你的实际训练语料句子,否则机器人无法生成有效回复 - 依赖检查:确保所有Python依赖库已正确安装
- 服务启动:运行Python文件后,后端服务默认在
http://localhost:5000启动
内容的提问来源于stack exchange,提问作者Harshil Patel
相关产品推荐
相关产品推荐

