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

调用GPT-3.5/GPT-4 API繁译时出现Unicode乱码问题求助

排查OpenAI API调用GPT-3.5/GPT-4返回繁体中文Unicode乱码问题

1. 修复代码变量引用错误

你的代码中定义了title变量,但用户提示词里误用了未定义的{n},这会导致模型接收到无效内容,可能引发异常输出。
修正后的代码片段:

title = "U.S. Treasury Says DeFi Threatens National Security; MacOS Mystery Over Hidden Bitcoin White Paper"

completion = openai.ChatCompletion.create(
model="gpt-4",
messages=[
    {"role": "system", "content": "you are a blockchain expert and financial trader"},
    {"role": "user", "content": f"translate this content {title} to Traditional Chinese"},
]
)
result = completion.choices[0].message
print(result['content'])  # 直接提取content字段而非打印整个message对象

2. 检查Python环境输出编码

终端或输出环境的编码未设置为UTF-8时,Unicode繁体中文字符会被渲染为乱码:

  • 执行以下代码检查当前输出编码:
import sys
print(sys.stdout.encoding)

如果输出不是UTF-8,需调整终端编码:Windows CMD执行chcp 65001,Linux/macOS确保终端编码设置为UTF-8。

  • 强制以UTF-8格式输出:
import json
print(json.dumps(result['content'], ensure_ascii=False))

3. 对齐API请求参数与Playground配置

Playground默认会处理部分隐含参数,API调用时可显式指定参数避免差异:

  • 显式设置响应格式为文本:
completion = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "you are a blockchain expert and financial trader"},
        {"role": "user", "content": f"translate this content {title} to Traditional Chinese"},
    ],
    response_format={"type": "text"}
)
  • 更新openai库到最新版本,修复潜在兼容性问题:
pip install --upgrade openai

4. 优化提示词明确输出要求

模糊的提示词可能导致模型输出格式异常,可明确要求仅输出翻译后的繁体中文:

{"role": "user", "content": f"Translate the following content into Traditional Chinese, output only the translated text:\n{title}"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:52:38