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

使用Apps Script调用OpenAI API返回无关乱码内容的问题求助

问题解决:Apps Script调用OpenAI接口生成视频标题返回杂乱内容

问题现象

使用Apps Script基于输入文本生成视频标题时,调用Davinci Codex接口返回混杂代码、符号的无关文本,但ChatGPT网页版可得到正常结果。

输入示例:

income threshold for social media must be increased
government need to do more

异常输出示例:

to provide universal access to the internet access for all people in the developing countries

Use a for loop on the words to make similar sentences
s = ["", government need to do more to provide universal access to the internet access for all people in the developing countries"",
""income threshold for social media must be increased, "",]

for l in range(10):
for k in range(3):
new_s

问题原因

  1. 模型选型错误:Davinci Codex是专为代码生成训练的模型,天生倾向输出代码相关内容,不适合通用文本类的标题生成需求。
  2. Prompt设计不足:原prompt缺少明确的格式约束和示例引导,模型无法精准理解任务要求。
  3. 参数设置不合理:max_tokens设为100过大,导致模型生成大量超出需求的冗余内容。

解决方案

1. 更换适配的模型

改用通用文本生成模型,比如gpt-3.5-turbo(性价比更高,推荐)或text-davinci-003。

2. 优化Prompt

明确任务要求,添加分隔符区分指令和输入内容,强化模型认知:

生成不超过6个词的视频标题,总结以下内容:
---
{输入文本}
---

3. 调整参数

将max_tokens设为15左右(足够容纳6词标题),同时设置temperature为0.3控制生成随机性,保证结果精准。

修改后的完整代码

var apiUrl = "https://api.openai.com/v1/chat/completions"; // gpt-3.5-turbo接口地址
var apiKey = "*****************";

function generateContentForMultipleRows(myRange) {
  var bulletPoints = myRange.getValues();

  bulletPoints.forEach(function (row, i) {
    // 优化后的prompt
    var prompt = `生成不超过6个词的视频标题,总结以下内容:
---
${row[0]}
---`;

    var options = {
      "method": "POST",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + apiKey
      },
      "payload": JSON.stringify({
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 15,
        "temperature": 0.3
      })
    };

    try {
      var response = UrlFetchApp.fetch(apiUrl, options);
      var json = JSON.parse(response.getContentText());
      var generatedTitle = json.choices[0].message.content.trim(); // 去除多余空格和换行

      SpreadsheetApp.getActiveSheet().getRange(2 + i, 4).setValue(generatedTitle);
    } catch (e) {
      SpreadsheetApp.getActiveSheet().getRange(2 + i, 4).setValue("生成失败:" + e.message);
    }
  });
}

补充说明

若坚持使用Davinci类模型,可改用text-davinci-003,接口地址改为https://api.openai.com/v1/completions,payload结构调整为:

{
  "model": "text-davinci-003",
  "prompt": prompt,
  "max_tokens": 15,
  "temperature": 0.3,
  "stop": ["\n"] // 遇到换行停止生成,避免冗余内容
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:46:01