You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在前后端请求中传递额外文本及解决返回乱文本问题

问题排查与解决方案

一、前后端数据传递逻辑确认

前端传递逻辑

前端通过fetch发送POST请求时,将additionaltext与userInput以JSON格式封装进请求体的逻辑是正确的:

const response = await fetch('http://localhost:5000/api/generate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ additionaltext, userInput }),
});

需注意:要确保后端接口已配置JSON解析中间件(比如Express的express.json()),否则无法正确读取请求体参数。

后端接收逻辑

后端generateProductDescription函数拼接prompt的逻辑本身无语法问题,但需确认后端接口是否正确提取前端参数:

// 示例Express路由实现
const { generateProductDescription } = require('./your-module-path');
app.post('/api/generate', async (req, res) => {
  // 必须从req.body中正确提取参数
  const { additionaltext, userInput } = req.body;
  try {
    const result = await generateProductDescription(additionaltext, userInput);
    res.json({ generatedText: result });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

若未正确提取参数,会导致prompt拼接异常,直接引发AI返回随机内容。

二、返回随机文本的核心原因及修复

1. 模型参数设置不合理

  • temperature值过高:当前设置为0.8(范围0-1),值越高AI生成内容的随机性越强,建议调整为0.3-0.5,降低输出的不确定性。
  • 模型版本老旧:text-davinci-001是OpenAI的旧版模型,推荐替换为gpt-3.5-turbo-instruct,该模型在文本生成任务上的稳定性和准确性更优。
  • stop词设置无效:当前stop: ['"""']的停止条件几乎不会触发,模型会一直生成到max_tokens上限,导致内容冗余偏离。可移除该配置,或设置stop: ['\n']以控制生成长度。

2. Prompt格式优化

当前prompt仅简单拼接文本,缺乏明确约束,可通过补充指令引导AI生成符合需求的内容:

prompt: `${additionaltext}: ${userInput}. Focus on key features, target audience, and unique selling points, keep it concise and suitable for product listings.`

3. 参数校验缺失

  • 前端添加输入校验,避免空输入触发请求:
const handleButtonClick = async () => {
  if (!userInput.trim()) {
    alert('Please enter a product name or details');
    return;
  }
  // 原有请求逻辑
};
  • 后端打印拼接后的prompt,确认格式正确:
async function generateProductDescription(additionaltext, userInput) {
  const prompt = `${additionaltext}: ${userInput}`;
  console.log('Final Prompt:', prompt); // 验证prompt是否符合预期
  // 后续API调用逻辑
}

三、优化后的后端代码示例

const axios = require('axios');
async function generateProductDescription(additionaltext, userInput) {
  try {
    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'gpt-3.5-turbo-instruct',
        prompt: `${additionaltext}: ${userInput}. Generate a concise, engaging product description highlighting core benefits.`,
        max_tokens: 150,
        temperature: 0.4,
        top_p: 1,
        frequency_penalty: 0.1,
        presence_penalty: 0,
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer YOUR_OPENAI_API_KEY',
        },
      }
    );

    const generatedText = response.data.choices[0].text.trim();
    return generatedText;
  } catch (error) {
    console.error('API Error:', error.response?.data || error.message);
    throw new Error('Failed to generate product description');
  }
}

module.exports = { generateProductDescription };

内容的提问来源于stack exchange,提问作者Soumaya Guenaguen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:05:09