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

使用GPT-3.5-Turbo的Python翻译函数返回冗余结果的解决方法

解决GPT-3.5-Turbo翻译返回多选项问题

问题场景

使用Python调用GPT-3.5-Turbo实现文本翻译时,函数返回结果包含多个翻译选项,仅需保留首个结果。当前输出示例:

A. Thugs of Bharat <-- Translation --> ['Thugs de Bharat', 'Pirates de l'Inde', 'Thugs de Hindostan', 'Combattants de la mer']

期望输出:

A. Thugs of Bharat <-- Translation --> Thugs de Bharat

用户实现代码如下:

翻译函数

def translate_text(text, source_language, target_language):
    prompt = f"Translate the following '{source_language}' text to '{target_language}': {text}"

    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant that translates text."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=150,
        n=1,
        stop=None,
        temperature=0.5,
    )

    translation = response.choices[0].message.content.strip()
    return translation

函数调用代码

slide = presentation.slides.add_slide(slide_layout)
shapes = slide.shapes

answers = [row[3], row[4], row[5], row[6]]

body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
t0 = translate_text(answers, 'auto', 'fr').translate(answers[0])
tf.text = "A. " + answers[0] + " <-- Translation --> " + ''.join([str(t0)])
slide_count += 1
print(t0)

问题原因

  1. Prompt未明确约束输出:原prompt仅要求翻译,未指定返回单个结果,GPT默认生成多个候选翻译。
  2. 调用参数错误:传入translate_text的是整个answers列表而非单个待翻译文本;后续错误使用字符串translate方法,导致逻辑混乱。

解决方案

方案1:优化Prompt并修正调用逻辑

通过明确Prompt要求仅返回单个翻译结果,同时修正调用参数:

修正后的翻译函数

def translate_text(text, source_language, target_language):
    # 明确要求仅返回单个翻译结果,无额外内容
    prompt = f"Translate the following '{source_language}' text to '{target_language}'. Return ONLY the translated text, no extra options, explanations or lists: {text}"

    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a professional translator that provides only accurate, single translations."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=150,
        n=1,
        stop=None,
        temperature=0.3,  # 降低随机性,减少多结果输出
    )

    translation = response.choices[0].message.content.strip()
    return translation

修正后的调用代码

slide = presentation.slides.add_slide(slide_layout)
shapes = slide.shapes

answers = [row[3], row[4], row[5], row[6]]

body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
# 仅传入单个待翻译文本,移除错误的translate方法调用
t0 = translate_text(answers[0], 'auto', 'fr')
tf.text = f"A. {answers[0]} <-- Translation --> {t0}"
slide_count += 1
print(t0)

方案2:处理返回结果(兼容偶尔多选项情况)

若优化Prompt后仍出现多选项,可解析返回字符串提取首个结果:

import ast

def translate_text(text, source_language, target_language):
    prompt = f"Translate the following '{source_language}' text to '{target_language}': {text}"

    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant that translates text."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=150,
        n=1,
        stop=None,
        temperature=0.5,
    )

    translation = response.choices[0].message.content.strip()
    
    # 检测并解析列表格式的返回结果,提取首个元素
    if translation.startswith('[') and translation.endswith(']'):
        try:
            translation_list = ast.literal_eval(translation)
            if isinstance(translation_list, list) and len(translation_list) > 0:
                translation = translation_list[0]
        except (ValueError, SyntaxError):
            # 解析失败则保留原结果
            pass
    
    return translation

调用代码同方案1修正后的版本即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:42:35