错误:模型 gemini-3.1-pro-preview: invalid character '<' looking for beginning of val...

2026年03月09日 13:58 processing

错误信息

错误:模型 gemini-3.1-pro-preview: invalid character '<' looking for beginning of value

AI 解决方案

报错分析报告

1.错误翻译


原文:invalid character '<' looking for beginning of value
译文:寻找值的起始位置时遇到无效字符‘<’

2. 原因分析


  • 根本原因:API响应返回了非JSON内容(如HTML错误页面),代码尝试将其解析为JSON时失败('<'是HTML的起始字符,而非JSON的{/[)。

  • 发生位置:解析gemini-3.1-pro-preview模型API响应的JSON阶段,因响应以<开头触发解析错误。
  • 3. 解决方案


    import requests
    import json
    
    # 配置API请求
    url = "YOUR_DMXAPI_ENDPOINT"  # 替换为实际端点
    payload = {
        "model": "gemini-3.1-pro-preview",
        "messages": [{"role": "user", "content": "Hello"}]  # 替换为实际参数
    }
    
    try:
        # 发送请求并检查状态码
        response = requests.post(url, json=payload, timeout=10)
        response.raise_for_status()  # 非200状态码直接抛异常
        
        # 安全解析JSON
        try:
            result = response.json()
            print("解析成功:", result)
        except json.JSONDecodeError:
            print(f"JSON解析失败!响应内容(前200字): {response.text[:200]}")
            raise  # 或自定义错误处理
    
    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
    

    4. 预防措施


  • 最佳实践1:调用API时必须检查HTTP状态码(非200时先处理错误,不直接解析);用try-except捕获JSONDecodeError并打印原始响应。

  • 最佳实践2:用Postmancurl先测试API端点,确认返回application/json类型的合法JSON。

  • 推荐工具:Python的requests库(自带raise_for_status())、JSON校验工具(如[JSONLint](https://jsonlint.com/))。