开发ChatGPT克隆应用时GPT-3.5 API返回无关代码的问题求助
问题描述
我正在开发一个基于JavaScript的ChatGPT克隆网站,使用GPT-3.5的text-davinci-003模型提供对话响应,但对话过程中会生成无关的Java Spring代码。尝试过更换API密钥、切换到text-davinci-002模型、修改代码,均无法解决问题。
Server.js代码
import express from "express"; import * as dotenv from "dotenv"; import cors from 'cors'; import { Configuration, OpenAIApi } from "openai"; dotenv.config(); const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); const app = express(); app.use(cors()); app.use(express.json()); app.get("/", (req, res) => { res.status(200).send({ message: "Welcome to OpenAI API", }); }); app.post('/', async (req, res) => { try { const prompt = req.body.prompt; const response = await openai.createCompletion({ model: "text-davinci-003", prompt: `${prompt}`, temperature: 0, max_tokens: 4000, top_p: 1, frequency_penalty: 0.5, presence_penalty: 0, }); res.status(200).send({ bot: response.data.choices[0].text }) } catch (error) { console.log(error); res.status(500).send({ error }) } }) app.listen(5000, () => console.log("Sever is running on port :- http://localhost:5000"))
生成的无关代码
package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.example.demo.model.*; import com.example.demo.*; @RestController // This means that this class is a Controller @RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController { @Autowired // This means to get the bean called userRepository // Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository; @GetMapping(path="/add") // Map ONLY GET Requests public @ResponseBody String addNewUser (@RequestParam String name, @RequestParam String email) { // @ResponseBody means the returned String is the response, not a view name // @RequestParam means it is a parameter from the GET or POST request User n = new User(); // Create a new user object and set its values from the request parameters passed in (name, email) using setters .save() will save it to db . .findAll() will return list of all users in db as an iterable .findById(id) will return user object with given id .deleteById(id) will delete user with given id .deleteAll() will delete all users in db .existsById(id) will check if there is a user with given id in db and return true or false accordingly .count() will return number of users in db .getOne(id) returns proxy instead of data and only fetches data when some method like getName() is called on it .saveAndFlush() saves data and refreshes session immediately */ n.setName(name); // Set its name and email values using setters (setName(), setEmail()) */ n.setEmail(email); // Set its name and email values using setters (setName(), setEmail()) */ userRepository.save(n); // Save it to database using save() method of JpaRepository interface which UserRepository class implements */ return "Saved"; // Return string "Saved" as response */ } /* */ @GetMapping(path="/all") /* Map ONLY GET Requests */ public @ResponseBody Iterable<User> getAllUsers() { /* @ResponseBody means the returned Iterable<User> is the response, not a view name */ /* Return list of all users in database as an iterable using findAll() method of JpaRepository interface which UserRepository class implements */ /* findAll() returns all the entries of table as a list */ return userRepository
解决方案
1. 明确Prompt约束
text-davinci-003是文本补全模型,若Prompt无明确输出限制,模型可能生成无关内容。给Prompt添加严格指令:
const prompt = `仅用自然语言回答用户问题,禁止生成任何代码:${req.body.prompt}`;
2. 切换到Chat Completions接口
gpt-3.5-turbo是专为对话场景设计的模型,比text-davinci-003更适配ChatGPT克隆,且成本更低。修改后端请求逻辑:
// 替换原createCompletion代码块 const response = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: [ { role: "system", content: "你是一个友好的对话助手,仅用自然语言回答问题,不生成任何代码" }, { role: "user", content: req.body.prompt } ], temperature: 0, max_tokens: 4000, }); res.status(200).send({ bot: response.data.choices[0].message.content })
3. 调整模型参数(若坚持用text-davinci-003)
- 提高
frequency_penalty至1.0,增强对重复/无关内容的抑制 - 优化Prompt前缀,例如:
"请以日常对话形式回答以下问题,绝对不要生成代码:\n${req.body.prompt}"
4. 检查前端输入
确认前端传递的prompt未混入代码片段或异常关键词,避免模型误判上下文。
内容的提问来源于stack exchange,提问作者Angel Malewar
相关产品推荐
相关产品推荐

