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

Python调用ChatGPT API遇超长内容:突破gpt-3.5-turbo令牌限制求助

针对长文章ChatGPT API请求问题的解决方案

1. 文本分片处理

当文章内容超过模型令牌限制时,将文本拆分为多个小分片逐个处理,最后整合结果:

  • 用tiktoken库计算令牌数,按合理大小拆分文本(比如单分片不超过3000令牌,预留足够空间给提示词)
  • 每个分片单独请求改写,保持风格一致
  • 拼接所有改写后的内容,再统一生成标题、分类和标签

示例代码:

import tiktoken
import openai

def split_text_by_tokens(text, model="gpt-3.5-turbo", max_tokens=3000):
    encoding = tiktoken.encoding_for_model(model)
    tokens = encoding.encode(text)
    chunks = []
    for i in range(0, len(tokens), max_tokens):
        chunk_tokens = tokens[i:i+max_tokens]
        chunks.append(encoding.decode(chunk_tokens))
    return chunks

# 拆分长内容
content_chunks = split_text_by_tokens(content)
rewritten_chunks = []

# 逐个处理分片
for chunk in content_chunks:
    resp = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        temperature=0.6,
        messages=[
            {
                "role": "system",
                "content": "你是一名记者,正在改写长文章的部分内容,需保持整体风格连贯,仅返回该部分的改写内容,无额外文本。"
            },
            {
                "role": "user",
                "content": f"改写文章的这一部分:{chunk}"
            }
        ]
    )
    rewritten_chunks.append(resp.choices[0].message.content.strip())

# 拼接后生成最终结果
full_rewritten = "\n".join(rewritten_chunks)
final_resp = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    temperature=0.6,
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": """
                你是一名记者,根据提供的内容生成标题、改写全文、从World/Technology/Health中选择分类,并生成3个文章标签。
                必须返回格式合法的JSON,结构如下:
                {
                    "title": "生成的标题",
                    "category": "分类",
                    "content": "改写后的全文",
                    "tags": ["标签1", "标签2", "标签3"]
                }
            """
        },
        {
            "role": "user",
            "content": f"标题和待完善的文章内容:\ntitle: {title}\ncontent: {full_rewritten}"
        }
    ]
)

2. 强制JSON格式与优化提示词

  • 使用支持强制JSON输出的模型版本(如gpt-3.5-turbo-1106),通过response_format={"type": "json_object"}参数确保API返回合法JSON
  • 修正原提示词中的JSON格式错误(补充缺失的逗号),明确要求即使内容过长也要保证结构完整,可先用占位符标记未完成部分

示例代码:

import openai

resp = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-1106",
    temperature=0.6,
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": """
                你是一名记者,根据提供的内容生成标题、改写全文、从World/Technology/Health中选择分类,并生成3个文章标签。
                必须返回格式合法的完整JSON,结构如下:
                {
                    "title": "字符串",
                    "category": "World/Technology/Health其中之一",
                    "content": "字符串",
                    "tags": ["字符串", "字符串", "字符串"]
                }
                若输入内容过长无法完全处理,用[INCOMPLETE]标记未完成部分,确保JSON结构始终有效。
            """
        },
        {
            "role": "user",
            "content": f"待改写的标题和文章内容:\ntitle: {title}\ncontent: {content}"
        }
    ]
)

3. 升级到大上下文窗口模型

直接使用支持更大令牌数的模型,避免分片处理的麻烦:

  • gpt-3.5-turbo-16k支持16k令牌上下文,是基础版的4倍
  • gpt-4或gpt-4-32k支持更高的令牌限制,适合超长篇文章

只需修改model参数即可:

openai.ChatCompletion.create(
    model="gpt-3.5-turbo-16k",
    temperature=0.6,
    response_format={"type": "json_object"},
    messages=[
        # 原提示词内容
    ]
)

4. 不完整JSON的补救处理

若仍遇到损坏的JSON,可通过以下方式修复:

  • 使用jsonrepair库自动补全缺失的语法元素:
import json
from jsonrepair import repair_json

try:
    result = json.loads(resp_content)
except json.JSONDecodeError:
    repaired_json = repair_json(resp_content)
    result = json.loads(repaired_json)
  • 若修复失败,将不完整JSON和剩余原文一起传入下一次请求,要求补全:
next_resp = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    temperature=0.6,
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": "你需要补全一篇不完整的文章JSON,使用提供的剩余原文完成内容,确保最终JSON格式合法完整,仅返回完整JSON。"
        },
        {
            "role": "user",
            "content": f"不完整的JSON:{incomplete_json}\n剩余待处理的文章内容:{remaining_content}"
        }
    ]
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:53:07