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

Google Sheets自定义GPT函数批量使用时出现TypeError报错求助

问题:Google Sheets批量调用GPT API时触发TypeError报错

问题详情

自行编写Google Apps Script在Sheets中调用GPT-4 API,单个单元格使用时功能正常,但批量填充多个单元格时出现报错:

TypeError: Cannot read properties of undefined (reading '0')

报错指向代码中访问response.choices[0].message.content的行。原代码如下:

function GPT(Input) {
  const GPT_API = "INSERT API KEY";
  const BASE_URL = "https://api.openai.com/v1/chat/completions";
  const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${GPT_API}`
  };
  const options = {
    headers,
    method: "POST",
    muteHttpExceptions: true,
    payload: JSON.stringify({
      "model": "gpt-4",
      "messages": [
        {
          "role": "system",
          "content": ""
        },
        {
          "role": "user",
          "content": Input
        }
      ],
      "temperature": 0
    })
  }
  const response = JSON.parse(UrlFetchApp.fetch(BASE_URL, options));
  console.log(response.choices[0].message.content);
  return response.choices[0].message.content
}

报错原因

批量调用时,部分请求可能因以下原因返回非预期结构,导致response.choices为undefined:

  • 触发OpenAI API的速率/配额限制
  • 输入为空或格式无效
  • API密钥失效、无GPT-4访问权限
  • 网络请求异常,返回错误JSON

修复后的代码

添加错误处理、输入校验和结构检查,确保批量调用时的稳定性:

function GPT(Input) {
  // 处理空输入
  if (!Input || Input.toString().trim() === "") {
    return "请输入有效内容";
  }

  const GPT_API = "INSERT API KEY";
  const BASE_URL = "https://api.openai.com/v1/chat/completions";
  const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${GPT_API}`
  };
  const options = {
    headers,
    method: "POST",
    muteHttpExceptions: true,
    payload: JSON.stringify({
      "model": "gpt-4",
      "messages": [
        {
          "role": "system",
          "content": ""
        },
        {
          "role": "user",
          "content": Input.toString().trim()
        }
      ],
      "temperature": 0
    })
  };

  try {
    const response = UrlFetchApp.fetch(BASE_URL, options);
    const jsonResponse = JSON.parse(response.getContentText());

    // 检查返回结构有效性
    if (!jsonResponse.choices || jsonResponse.choices.length === 0) {
      const errorMsg = jsonResponse.error ? jsonResponse.error.message : "请求未返回有效结果";
      console.error("API错误:", errorMsg);
      return `错误: ${errorMsg}`;
    }

    const content = jsonResponse.choices[0].message.content;
    console.log(content);
    return content;
  } catch (e) {
    console.error("请求失败:", e.toString());
    return `请求错误: ${e.toString()}`;
  }
}

额外注意事项

  • 替换代码中的INSERT API KEY为你的OpenAI有效API密钥
  • 批量调用时建议添加请求延迟(如Utilities.sleep(1000)),避免触发速率限制
  • 确认OpenAI账户拥有GPT-4访问权限及足够的API额度
  • 空输入会直接返回提示,减少无效API请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:22:39