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

上传文件至Gemini 1.5 Vertex AI时触发400前置检查失败错误排查

Google Cloud Vertex AI调用Gemini 1.5时11MB文件触发400 Precondition check failed错误排查

尝试通过Google Cloud的Vertex AI向Gemini 1.5模型上传文件,尽管文件限制为30MB,但11MB的文件触发错误:400 Precondition check failed,仅返回该错误信息,请求协助排查问题原因。

代码实现

async def async_get_model_output(prompt, filepaths, content_type):
    
    vertexai.init(project=os.getenv("PROJECT_ID"), location="us-central1")
    model = GenerativeModel(model_name="gemini-1.5-flash-001")
    #Figure 
    parts = [Part.from_uri(filepath["gcs_link"], mime_type=filepath["mimetype"]) for filepath in filepaths]
    parts.append(prompt)
    # Create a GenerationConfig object with the specified parameters
    generation_config = GenerationConfig(
        temperature=0.3,
        top_p=0.3,
        max_output_tokens = 5000
        # You can add other parameters here as needed
    )
#BLOCK_ONLY_HIGH
    safety_settings = [
        SafetySetting(
        category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH,
    ),
    SafetySetting(
        category=HarmCategory.HARM_CATEGORY_HARASSMENT,
        threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH,
    ),
    SafetySetting(
        category=HarmCategory.HARM_CATEGORY_HATE_SPEECH,
        threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH,
    ),
    SafetySetting(
        category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
        threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH,
    ),
        # Add other categories as needed
    ]

    for attempt in range(3):
        print(f'Attempt {attempt + 1} to get model output')
        try:
            token_count = model.count_tokens(parts)
            print(f"Token count: {token_count}")
            print(f"##{content_type}## DEBUG: INVOKING VERTEX AI")
            response = await asyncio.to_thread(
                model.generate_content,
                parts,
                generation_config=generation_config,
                safety_settings=safety_settings
            )
            logger.debug(f"Received response: {response}")
            json_match = re.search(r'\{[\s\S]*\}', response.text)

            if json_match:
                json_string = json_match.group(0)
                try:
                    study_guide_data = json.loads(json_string)
                    print(f"##{content_type}## DEBUG CONTENT SUCCESS: Successfully Generated content and parsed JSON")
                    return json_string
                except json.JSONDecodeError as e:
                    print(f"##{content_type}##JSON decode error: {e}")
                    print(f"##{content_type}##Extracted JSON string:", json_string)
                    # Continue to next attempt
            else:
                print(f"##{content_type}## No JSON object found in the response")
        except Exception as e:
            error_message = str(e)
            truncated_message = error_message[:197] + "..." if len(error_message) > 200 else error_message
            print(f"##{content_type}## Unexpected error during attempt {attempt + 1}: {error_message}")
        
        # If we reach here, the current attempt failed. We'll continue to the next one.
        print(f"##{content_type}## Attempt {attempt + 1} failed. Moving to next attempt.")

        
        if attempt < 2:  # Don't sleep after the last attempt
            print(f"##{content_type}## Waiting 1 seconds before next attempt...")
            await asyncio.sleep(1)
    # If we've exhausted all attempts without success
    raise Exception(f"##{content_type}## Failed to get valid JSON after 3 attempts")

可能的排查方向

  • GCS权限验证:确认GCS存储桶已为Vertex AI服务账号(service-[PROJECT_NUMBER]@gcp-sa-vertexai.iam.gserviceaccount.com)分配roles/storage.objectViewer角色,确保模型能读取文件。
  • MIME类型一致性检查:核对filepath["mimetype"]与实际文件类型是否匹配,比如PDF需设为application/pdf,Word文档设为application/vnd.openxmlformats-officedocument.wordprocessingml.document,错误类型会触发预检查失败。
  • 文件完整性验证:重新上传文件到GCS,或尝试用本地文件测试,排除文件损坏导致的预检查失败。
  • 区域匹配检查:确认GCS存储桶区域与Vertex AI初始化的us-central1区域一致,跨区域访问可能存在限制。
  • Token计数超限排查:查看代码中token_count的输出值,Gemini 1.5 Flash输入Token上限为1M,部分文件(如长文本、高分辨率图片)转Token后可能超限。
  • API配额检查:在GCP控制台的配额页面,确认generativeModels.generateContent等相关API的请求次数未超限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 21:22:32