专栏名称: Datawhale
一个专注于AI领域的开源组织,汇聚了众多顶尖院校和知名企业的优秀学习者,聚集了一群有开源精神和探索精神的团队成员。愿景-for the learner,和学习者一起成长。
目录
相关文章推荐
嘶吼专业版  ·  Google Play 上的恶意 ... ·  2 天前  
中核集团  ·  核电难题,被这支“特种部队”破解! ·  2 天前  
萧山发布  ·  一键“预约”!萧山再出“新招”! ·  3 天前  
萧山发布  ·  一键“预约”!萧山再出“新招”! ·  3 天前  
51好读  ›  专栏  ›  Datawhale

吴恩达的翻译Agent项目,复现教程来了!

Datawhale  · 公众号  ·  · 2025-03-14 23:13

正文

Datawhale教程

作者:郭才高,Datawhale创作者


1. Translation Agent复现效果展示

#执行任务
# 调用编译后的工作流,传入初始状态字典
result = app.invoke({
    "source_lang""English"# 源语言为英语
    "target_lang""中文",    # 目标语言为中文
    "source_text""""By using an LLM as the heart of the translation engine, this system is highly steerable. For example, by changing the prompts, it is easier using this workflow than a traditional machine translation (MT) system to:

Modify the output's style, such as formal/informal.
Specify how to handle idioms and special terms like names, technical terms, and acronyms. For example, including a glossary in the prompt lets you make sure particular terms (such as open source, H100 or GPU) are translated consistently.
Specify specific regional use of the language, or specific dialects, to serve a target audience. For example, Spanish spoken in Latin America is different from Spanish spoken in Spain; French spoken in Canada is different from how it is spoken in France."""

})

1.1 要翻译的内容:

By using an LLM as the heart of the translation engine, this system is highly steerable. For example, by changing the prompts, it is easier using this workflow than a traditional machine translation (MT) system to:Modify the output's style, such as formal/informal.Specify how to handle idioms and special terms like names, technical terms, and acronyms. For example, including a glossary in the prompt lets you make sure particular terms (such as open source, H100 or GPU) are translated consistently.Specify specific regional use of the language, or specific dialects, to serve a target audience. For example, Spanish spoken in Latin America is different from Spanish spoken in Spain; French spoken in Canada is different from how it is spoken in France.

1.2 模型初翻结果:

通过将LLM作为翻译引擎的核心,该系统具备高度可调控性。例如相较于传统机器翻译(MT)系统,通过修改提示词可以更便捷地实现以下功能:调整输出文本风格(正式/非正式);指定成语和专业术语(如名称、技术术语、缩略语)的处理方式——通过在提示词中添加术语表,可确保特定词汇(如开源、H100或GPU)的翻译一致性;根据目标受众需求指定语言的地域变体或方言,例如拉丁美洲西班牙语与西班牙本土西班牙语存在差异,加拿大法语与法国本土法语亦有不同。

1.3 模型给出的改进建议:

1.




    
 将"可调控性"改为"可操控性"更符合中文技术语境,原词"steerable"在翻译系统中更常对应"可操控"概念。2. "提示词"建议统一译为"提示语",因在大型语言模型领域"prompt"的规范译法为"提示语",且后文重复出现需保持术语一致性。3. "调整输出文本风格(正式/非正式)"中的括号应改为中文全角括号「」更符合中文排版规范,建议修改为「(正式/非正式)」→「(正式/非正式)」并添加顿号。4. "名称"建议改为"专有名词",因原文"names"在翻译语境中特指需要特殊处理的专有名词翻译,原译容易产生歧义。5. "H100或GPU"中的"或"应改为顿号,中文列举多项时应用顿号分隔,建议修改为"如开源、H100、GPU"6. "术语表"建议改为"词汇表",因"glossary"在本地化行业标准译法为"词汇表",且与后文"特定词汇"形成更好的术语呼应。7. "地域变体"调整为"地域性变体"更符合中文表达习惯,原译"地域变体"在语言学领域不够规范。8. "根据目标受众需求"建议补充为"根据目标受众的具体需求",添加"具体"二字更准确对应原文"specific"的双重含义。9. "存在差异""亦有不同"形成重复,建议统一为"有所不同",既保持译文流畅度又符合中文忌重复的表达习惯。10. 最后一句建议增加连接词:"例如,拉丁美洲使用的西班牙语与西班牙本土的西班牙语有所不同,而加拿大法语与法国本土法语也存在差异",通过添加"而"字增强句间逻辑关系。11. "西班牙本土西班牙语"存在语义重复,建议简化为"西班牙的西班牙语",符合中文简洁表达原则。12. 专业术语处理部分建议调整语序:"指定如何处理成语及特殊术语(包括名称、技术术语、缩略语等)",通过添加"包括"使列举关系更清晰。

1.4 模型最终翻译结果:

通过将LLM作为翻译引擎的核心,该系统具备高度可操控性。例如相较于传统机器翻译(MT)系统,通过修改提示语可以更便捷地实现以下功能:调整输出文本风格(正式/非正式);指定如何处理成语及特殊术语(包括专有名词、技术术语、缩略语等)——通过在提示语中添加词汇表,可确保特定词汇(如开源、H100、GPU)的翻译一致性;根据目标受众的具体需求指定语言的地域性变体或方言,例如拉丁美洲使用的西班牙语与西班牙的西班牙语有所不同,而加拿大法语与法国本土法语亦存在差异。

2. LangGraph简介

LangGraph是一个用于构建有状态、多角色应用程序的库,特别适用于与大型语言模型(LLMs)一起使用。它扩展了LangChain表达式语言,允许以循环方式协调多个链或角色,其灵感来源于Pregel和Apache Beam,并借鉴了NetworkX的接口。

2.1 核心功能

  • 支持循环流 :LangGraph允许定义包含循环的流程,这对于大多数代理架构至关重要,而基于DAG的解决方案则不支持循环流。
  • 状态管理 :提供状态管理功能,允许代理在多个步骤之间存储和检索信息,这对于构建需要跟踪对话状态或游戏状态的应用程序至关重要。
  • 多角色支持 :支持多个代理相互交互,以实现更复杂的工作流程,适合构建需要协作或竞争的代理应用程序。
  • 可扩展性 :可以扩展到生产环境,以支持大规模应用程序。
  • 高级接口和低级API :既提供用于创建常见类型代理的高级接口,也提供用于自定义和组合工作流程的低级API。

2.2 主要特点

  • 图结构 :使用图结构来表示应用程序的工作流程,其中节点代表不同的操作或步骤,边定义了这些步骤之间的执行顺序和条件。
  • 细粒度控制 :为用户提供对应用程序的流程和状态的细粒度控制,这对于创建可靠、可预测的代理至关重要。
  • 内置持久性 :包括内置的持久性功能,使代理能够记住过去的交互并使用这些信息来指导未来的决策。

2.3 应用场景

  • 对话代理和聊天机器人 :构建能够与用户进行自然语言对话的代理,例如客户服务代理或虚拟助手。
  • RAG应用 :在语义检索相关文档后,对其质量进行评估,若文档质量差,可重写检索问题并再次交给检索器以获得更精确结果。
  • 多智能体系统 :构建由多个AI智能体构成的系统,通过相互关联与协作共同完成任务。
  • 业务流程自动化 :在企业中自动化复杂的业务流程,如订单处理、库存管理和供应链协调。
  • 个性化推荐系统 :根据用户的兴趣、历史行为和上下文信息提供相关的建议。

3. Translation Agent项目介绍

吴恩达老师的项目地址: https://github.com/andrewyng/translation-agent

Translation Agent 是一个基于大型语言模型(LLM)的翻译工具,它采用反思工作流来提升翻译质量。以下是该项目的简单介绍:

3.1 核心功能

  • 翻译与反思 :先通过LLM将文本从源语言翻译成目标语言,然后让LLM对翻译结果进行反思,提出改进建议,最后根据建议优化翻译。
  • 高度可定制 :通过调整提示词,可轻松修改输出风格,如正式/非正式;还能指定如何处理习语、专有名词等特殊术语;也可针对特定地区的语言变体或方言进行翻译,以满足目标受众需求。

3.2 原理及核心步骤

  1. 1. 构建prompt让LLM将文本从source_language翻译为target_language;
  2. 2. 让LLM对翻译结果进行反思,提出改进建议;
  3. 3. 利用这些建议来进一步改进翻译结果并输出。

3.3 核心代码阅读

https://github.com/andrewyng/translation-agent/blob/main/src/translation_agent/utils.py

one_chunk_initial_translation

该函数是一个简单的翻译工具,它利用大型语言模型(LLM)将一段文本(source_text)从一种语言(source_lang)翻译成另一种语言(target_lang)。函数接收source_lang、 target_lang和source_text作为输入,构造一个system_message 来设定 LLM 的角色,然后创建一个明确的translation_prompt ,要求 LLM 仅提供翻译结果而不添加任何额外内容。最后,函数通过调用 get_completion 函数来获取 LLM 的翻译输出并返回。

defone_chunk_initial_translation(
    source_lang: str, target_lang: str, source_text: str
) -> str:
    """
    Translate the entire text as one chunk using an LLM.

    Args:
        source_lang (str): The source language of the text.
        target_lang (str): The target language for translation.
        source_text (str): The text to be translated.

    Returns:
        str: The translated text.
    """


    system_message = f"You are an expert linguist, specializing in translation from {source_lang} to {target_lang}."

    translation_prompt = f"""This is an {source_lang} to {target_lang} translation, please provide the {target_lang} translation for this text. \
Do not provide any explanations or text apart from the translation.
{source_lang}{source_text}

{target_lang}:"""


    translation = get_completion(translation_prompt, system_message=system_message)

    return translation

one_chunk_reflect_on_translation

该函数利用大型语言模型(LLM)对一段文本的翻译进行反思和评估,以提高翻译质量。函数接收源语言(source_lang)、目标语言(target_lang)、原文本(source_text)、初始翻译(translation_1)以及可选的国家/地区参数(country),构造一个system_message 来设定 LLM 的角色为翻译专家,然后根据是否提供国家/地区信息来生成相应的反思和建议。reflection_prompt 中明确要求 LLM 从准确性、流畅性、风格和术语使用等方面对翻译进行评估,并提出具体的改进建议。最后,函数通过调用 get_completion 函数获取 LLM 的反思结果并返回。该函数适用于需要对翻译结果进行优化的场景,尤其是当需要针对特定地区语言变体进行翻译优化时。

defone_chunk_reflect_on_translation(
    source_lang: str,
    target_lang: str,
    source_text: str,
    translation_1: str,
    country: str = "",
) -> str:
    """
    Use an LLM to reflect on the translation, treating the entire text as one chunk.

    Args:
        source_lang (str): The source language of the text.
        target_lang (str): The target language of the translation.
        source_text (str): The original text in the source language.
        translation_1 (str): The initial translation of the source text.
        country (str): Country specified for the target language.

    Returns:
        str: The LLM's reflection on the translation, providing constructive criticism and suggestions for improvement.
    """


    system_message = f"You are an expert linguist specializing in translation from {source_lang} to {target_lang}. \
You will be provided with a source text and its translation and your goal is to improve the translation."


    if country != "":
        reflection_prompt = f"""Your task is to carefully read a source text and a translation from {source_lang} to {target_lang}, and then give constructive criticism and helpful suggestions to improve the translation. \
The final style and tone of the translation should match the style of {target_lang} colloquially spoken in {country}.

The source text and initial translation, delimited by XML tags and , are as follows:


{source_text}



{translation_1}


When writing suggestions, pay attention to whether there are ways to improve the translation's \n\
(i) accuracy (by correcting errors of addition, mistranslation, omission, or untranslated text),\n\
(ii) fluency (by applying {target_lang} grammar, spelling and punctuation rules, and ensuring there are no unnecessary repetitions),\n\
(iii) style (by ensuring the translations reflect the style of the source text and take into account any cultural context),\n\
(iv) terminology (by ensuring terminology use is consistent and reflects the source text domain; and by only ensuring you use equivalent idioms {target_lang}).\n\

Write a list of specific, helpful and constructive suggestions for improving the translation.
Each suggestion should address one specific part of the translation.
Output only the suggestions and nothing else."""


    else:
        reflection_prompt = f"""Your task is to carefully read a source text and a translation from {source_lang} to {target_lang}, and then give constructive criticisms and helpful suggestions to improve the translation. \

The source text and initial translation, delimited by XML tags and , are as follows:


{source_text}



{translation_1}


When writing suggestions, pay attention to whether there are ways to improve the translation's \n\
(i) accuracy (by correcting errors of addition, mistranslation, omission, or untranslated text),\n\
(ii) fluency (by applying {target_lang} grammar, spelling and punctuation rules, and ensuring there are no unnecessary repetitions),\n\
(iii) style (by ensuring the translations reflect the style of the source text and take into account any cultural context),\n\
(iv) terminology (by ensuring terminology use is consistent and reflects the source text domain; and by only ensuring you use equivalent idioms {target_lang}).\n\

Write a list of specific, helpful and constructive suggestions for improving the translation.
Each suggestion should address one specific part of the translation.
Output only the suggestions and nothing else."""


    reflection = get_completion(reflection_prompt, system_message=system_message)
    return reflection

one_chunk_improve_translation

该函数利用大型语言模型(LLM)根据reflection种给出的建议对source_text文本的翻译(translation_1)进行改进。函数接收source_lang、target_lang、source_text、translation_1、reflection作为输入,构造一个system_message 来设定 LLM 的角色为翻译专家,然后创建一个详细的prompt ,要求 LLM 根据专家建议对翻译进行编辑,确保翻译的准确性、流畅性、风格和术语使用等方面得到优化。最后,函数通过调用 get_completion 函数获取改进后的翻译结果并返回。该函数适用于需要对翻译结果进行精细化调整的场景,尤其是当有具体的改进建议时,能够有效提升翻译质量。

defone_chunk_improve_translation(
    source_lang: str,
    target_lang: str,
    source_text: str,
    translation_1: str,
    reflection: str,
) -> str:
    """
    Use the reflection to improve the translation, treating the entire text as one chunk.

    Args:
        source_lang (str): The source language of the text.
        target_lang (str): The target language for the translation.
        source_text (str): The original text in the source language.
        translation_1 (str): The initial translation of the source text.
        reflection (str): Expert suggestions and constructive criticism for improving the translation.

    Returns:
        str: The improved translation based on the expert suggestions.
    """


    system_message = f"You are an expert linguist, specializing in translation editing from {source_lang} to {target_lang}."

    prompt = f"""Your task is to carefully read, then edit, a translation from {source_lang} to {target_lang}, taking into
account a list of expert suggestions and constructive criticisms.

The source text, the initial translation, and the expert linguist suggestions are delimited by XML tags , and \
as follows:


{source_text}



{translation_1}



{reflection}


Please take into account the expert suggestions when editing the translation. Edit the translation by ensuring:

(i) accuracy (by correcting errors of addition, mistranslation, omission, or untranslated text),
(ii) fluency (by applying {target_lang} grammar, spelling and punctuation rules and ensuring there are no unnecessary repetitions), \
(iii) style (by ensuring the translations reflect the style of the source text)
(iv) terminology (inappropriate for context, inconsistent use), or
(v) other errors.

Output only the new translation and nothing else."""


    translation_2 = get_completion(prompt, system_message)

    return translation_2

4. 利用LangGraph复现Translation Agent

4.1 配置和使用 DeepSeek API

这段 Python 代码的主要功能是配置和使用 DeepSeek API 来获取模型的完成结果。它首先导入了必要的库,包括 json openai langgraph.graph 中的 StateGraph START END ,以及 os 模块。然后,它设置了 DeepSeek API 的相关参数,如 API 密钥、基地址和默认模型名称。

代码的核心部分是一个名为 get_completion 的函数,它接受提示文本、系统消息、模型名称、温度参数和 JSON 模式标志作为输入参数。这个函数使用 OpenAI 的 Python 客户端库创建了一个客户端实例,并通过该实例向 DeepSeek API 发送请求。

这段代码为开发者提供了一个方便的接口,可以快速地向 DeepSeek API 发送请求并获取模型的完成结果,适用于需要与 DeepSeek API 集成的自然语言处理应用。

import json
import openai
from langgraph.graph import StateGraph, START, END
import os

# 设置 DeepSeek API 的相关参数
deep_seek_api_key = 'sk-21070************494b7e5db'# API 密钥
deep_seek_url = 'https://api.deepseek.com/v1'# API 请求的基地址
deep_seek_default_model = 'deepseek-reasoner'# 默认使用的模型名称

# 使用 OpenAI 的 Python 客户端库创建一个客户端实例,用于与 DeepSeek API 进行交互
client = openai.OpenAI(
    api_key=deep_seek_api_key,  # 设置 API 密钥
    base_url=deep_seek_url  # 设置 API 请求的基地址
)
default_model = deep_seek_default_model  # 设置默认模型

defget_completion(
    prompt: str,  # 提示文本
    system_message: str = "You are a helpful assistant.",  # 系统消息,默认值为 "You are a helpful assistant."
    model: str = default_model,  # 使用的模型,默认为 deep_seek_default_model
    temperature: float = 0.3,  # 生成文本的随机程度,值越低越确定
    json_mode: bool = False,  # 是否以 JSON 模式返回结果,默认为 False
):
    """
    向 DeepSeek API 发送请求并获取完成结果。

    参数:
        prompt (str): 提示文本,用于引导模型生成回答。
        system_message (str): 系统消息,用于设定模型的行为。
        model (str): 使用的模型名称。
        temperature (float): 控制生成文本的随机程度。
        json_mode (bool): 是否以 JSON 格式返回结果。

    返回:
        str: 模型生成的回答内容。
    """

    # 调用 OpenAI 客户端的 chat.completions.create 方法,发送请求
    response = client.chat.completions.create(
        model=model,  # 指定使用的模型






请到「今天看啥」查看全文