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

GoogleGenerativeAI偶发400错误:如何打印GenerateContentRequest排查空parts?

排查GoogleGenerativeAI 400错误:打印GenerateContentRequest

要捕获并打印GenerateContentRequest以定位contents.parts为空的问题,可以通过以下两种方式实现:

方法一:快速打印关键数据(简单直接)

在调用sendMessage前,打印当前聊天历史和待发送的prompt,快速排查是否存在空内容:

const genAI = new GoogleGenerativeAI(apiKey)
const model = genAI.getGenerativeModel({
  model: "gemini-pro",
})

const chat = model.startChat({
      history: [],
      generationConfig: {
        maxOutputTokens: 10000,
      }
    })

// 打印关键数据
console.log('当前聊天历史:', chat.history);
console.log('待发送的prompt:', prompt);

// 提前检查空内容
if (!prompt || (typeof prompt === 'object' && (!prompt.parts || prompt.parts.length === 0))) {
  console.error('检测到空的prompt或parts:', prompt);
}

let result = await chat.sendMessage(prompt)

方法二:完整捕获GenerateContentRequest(全面排查)

如果快速打印无法定位问题,可以包装SDK的generateContent方法,捕获并打印完整的请求参数:

const genAI = new GoogleGenerativeAI(apiKey)
const model = genAI.getGenerativeModel({
  model: "gemini-pro",
})

// 包装原generateContent方法,打印完整请求
const originalGenerateContent = model.generateContent;
model.generateContent = async function(request) {
  // 打印完整的GenerateContentRequest
  console.log('完整请求参数:', JSON.stringify(request, null, 2));
  
  // 针对性检查contents中的parts是否为空
  if (request.contents) {
    request.contents.forEach((content, idx) => {
      if (!content.parts || content.parts.length === 0) {
        console.error(`⚠️ 发现空parts,索引${idx}:`, content);
      }
    });
  }
  
  return originalGenerateContent.call(this, request);
};

const chat = model.startChat({
      history: [],
      generationConfig: {
        maxOutputTokens: 10000,
      }
    })

let result = await chat.sendMessage(prompt)

当错误再次出现时,控制台会输出完整的请求内容,你可以直接查看contents[1]对应的具体数据,定位是prompt本身为空,还是聊天历史被意外修改导致空内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:45:16