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

使用API Key调用ChatGPT上传PDF评分时请求报错问题

问题:ChatGPT API评分请求传入PDF提取文本时报错
  • 纯文本请求可正常执行,传入PDF解析后的文本后触发错误:Invalid argument (string): Contains invalid characters.
  • 报错对应的请求体包含PDF提取的考试文本内容
解决方案

1. 清洗PDF提取的文本

PDF解析出的文本常带有冗余空格、换行或不可见控制字符,会破坏API请求参数格式:

  • 去除连续多余的空格、换行,统一文本格式
  • 过滤非打印ASCII控制字符,Python示例:
    import re
    cleaned_text = re.sub(r'[\x00-\x1F\x7F]', '', raw_pdf_text)
    cleaned_text = re.sub(r'\s+', ' ', cleaned_text).strip()
    

2. 禁止手动拼接JSON请求体

手动拼接JSON时,文本中的特殊字符(如引号、换行)会导致JSON格式失效,必须使用语言自带的JSON序列化工具:

  • Python示例:
    import json
    
    # 清洗后的文本
    cleaned_text = "Name: Sara Question 1: calculate: 1+1 Q1 Answer: 3 Question 2: What is the capital of Saudi? Q2 Answer: Riyadh"
    
    messages = [
        {"role": "system", "content": f"You are a grading assistant. Grade the following answers based on the model answer. 📄 exam.pdf:\n{cleaned_text}"},
        {"role": "user", "content": f"Course: Math\nSection: Section A\nExam Type: Midterm\n\nPlease grade the following student submissions.\n\n📄 exam.pdf:\n{cleaned_text}"}
    ]
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": messages,
        "temperature": 0.7
    }
    
    # 自动处理转义,生成合法JSON
    request_body = json.dumps(payload)
    

3. 验证请求格式

将序列化后的JSON内容放入在线JSON校验工具,确认无格式错误后再发送请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:52:44