所以我有一个名为 algo.py 的文件,它接受用户输入,通过 OpenAI 对其进行处理,然后将 GPT 的响应输出回用户。在 HTML 文件中,我有一个允许用户输入问题的表单和一个将输出显示给用户的部分 (div)。我尝试使用 Node JS 捕获用户数据,然后将其转发到 algo.py 但无济于事。下面是我的 HTML 和 python 代码的代码片段。我愿意接受建议,并且希望对我当前的代码进行任何修改和注释,以便我能够理解您的推理。
HTML 表单:
<!-- SEARCH FORM -->
<form id="searchform" onsubmit="submitForm(event)">
<div class="search">
<span class="search-icon material-symbols-outlined">search</span>
<input id="searchinput" class="search-input" type="search" placeholder="What did you want to build? ">
<button type="submit">Generate</button>
</div>
</form>
同一 HTML 文件中的脚本:
<script>
function submitForm(event) {
// prevent default form submission
event.preventDefault();
// Capture user input
var userInput = document.getElementById("searchinput").value;
// Send user input over to execute python script locally
fetch('/execute_script', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: userInput }),
})
.then(response => {
if (!response.ok) {
throw new Error('Server response was not OK')
}
return response.json();
})
.then(data => {
// Display response from the Python script
var responseContainer = document.getElementById("responseContainer");
responseContainer.innerHTML = "<p>" + data.response + "</p>";
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
Python脚本:
import subprocess
import sys
import json
import cgi
def install(library):
subprocess.check_call([sys.executable, "-m", "pip", "install", library])
install('openai')
import openai
from openai import OpenAI
# Set up OpenAI API key
openai.api_key = '...'
client = OpenAI(
# This is the default and can be omitted
api_key='...',
)
def AI_PC_Buddy(prompt):
messages = [{'role': 'user', 'content': prompt}]
response = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=messages
)
return response.choices[0].message.content.strip()
# Process CGI input and output
form = cgi.FieldStorage()
prompt = form.getValue('prompt', '')
response = AI_PC_Buddy(prompt)
print("Content-type: application/json\n")
print(json.dumps({'response': response}))
节点服务器.js:
const express = require('express');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
const app = express();
const port = 8005;
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// Define the route for handling POST requests to /execute_script
app.post('/execute_script', (req, res) => {
const userInput = req.body.prompt;
// Execute the Python script with the user input as a command-line argument
exec(`python3 algo.py "${userInput}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing Python script: ${error.message}`);
return;
}
if (stderr) {
console.error(`Python script encountered an error: ${stderr}`);
return;
}
// Send the output of the Python script back to the client
res.send(stdout);
});
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
您正在侦听端口 8005,但获取了端口 5500...