实战: LangChain 版 OpenAI-Translator v2.0
深入理解 Chat Model 和 Chat Prompt Template
深入理解 LangChain 的聊天模型。简而言之:
-
Chat Model
不止是一个用于聊天对话的模型抽象,更重要的是提供了多角色
提示能力(System,AI,Human,Function)。 -
Chat Prompt Template
则为开发者提供了便捷维护不同角色
的提示模板
与消息记录
的接口。
温故:LangChain Chat Model 使用方法和流程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from langchain.chat_models import ChatOpenAI chat_model = ChatOpenAI(model_name = "gpt-3.5-turbo" ) from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) messages = [SystemMessage(content = "You are a helpful assistant." ), HumanMessage(content = "Who won the world series in 2020?" ), AIMessage(content = "The Los Angeles Dodgers won the World Series in 2020." ), HumanMessage(content = "Where was it played?" )] print (messages) chat_model(messages) |
使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate
使用 ChatPromptTemplate.from_messages
方法,类似使用和维护messages
的方式,构造 chat_prompt_template
创建系统模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from langchain.schema import AIMessage, HumanMessage, SystemMessage # 导入 Chat Model 即将使用的 Prompt Templates from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate, ) # 翻译任务指令始终由 System 角色承担 template = ( """You are a translation expert, proficient in various languages. \n Translates English to Chinese.""" ) system_message_prompt = SystemMessagePromptTemplate.from_template(template) |
Human 角色输入
1 2 3 | # 待翻译文本由 Human 角色输入 human_template = "{text}" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) |
使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate
1 2 3 | chat_prompt_template = ChatPromptTemplate.from_messages( [system_message_prompt, human_message_prompt] ) |
生成用于翻译的 Chat Prompt
1 | chat_prompt = chat_prompt_template.format_prompt(text = "I love programming." ).to_messages() |
使用 Chat Model(GPT-3.5-turbo)实际执行翻译任务
1 2 3 4 5 | from langchain.chat_models import ChatOpenAI # 为了翻译结果的稳定性,将 temperature 设置为 0 translation_model = ChatOpenAI(model_name = "gpt-3.5-turbo" , temperature = 0 ) translation_model(chat_prompt) |
使用 LLMChain 简化重复构造 ChatPrompt
1 2 3 4 5 6 | from langchain.chains import LLMChain # 无需再每次都使用 to_messages 方法构造 Chat Prompt translation_chain = LLMChain(llm = translation_model, prompt = chat_prompt_template) # 等价于 translation_result.content (字符串类型) translation_chain.run({ 'text' : "I love programming." }) |
扩展:支持多语言对翻译
System 增加 source_language 和 target_language
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # System 增加 source_language 和 target_language template = ( """You are a translation expert, proficient in various languages. \n Translates {source_language} to {target_language}.""" ) system_message_prompt = SystemMessagePromptTemplate.from_template(template) # 待翻译文本由 Human 角色输入 human_template = "{text}" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) # 使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate m_chat_prompt_template = ChatPromptTemplate.from_messages( [system_message_prompt, human_message_prompt] ) m_translation_chain = LLMChain(llm = translation_model, prompt = m_chat_prompt_template) |
基于 LangChain 优化 OpenAI-Translator 架构设 计
v2.0 设计:回应 Model 模块挑战
定义 trnslation chain
Gradio GUI
图形化界面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | import sys import os import gradio as gr sys.path.append(os.path.dirname(os.path.abspath(__file__))) from utils import ArgumentParser, LOG from translator import PDFTranslator, TranslationConfig def translation(input_file, source_language, target_language): LOG.debug(f "[翻译任务]\n源文件: {input_file.name}\n源语言: {source_language}\n目标语言: {target_language}" ) output_file_path = Translator.translate_pdf( input_file.name, source_language = source_language, target_language = target_language) return output_file_path def launch_gradio(): iface = gr.Interface( fn = translation, title = "OpenAI-Translator v2.0(PDF 电子书翻译工具)" , inputs = [ gr. File (label = "上传PDF文件" ), gr.Textbox(label = "源语言(默认:英文)" , placeholder = "English" , value = "English" ), gr.Textbox(label = "目标语言(默认:中文)" , placeholder = "Chinese" , value = "Chinese" ) ], outputs = [ gr. File (label = "下载翻译文件" ) ], allow_flagging = "never" ) iface.launch(share = True , server_name = "0.0.0.0" ) def initialize_translator(): # 解析命令行 argument_parser = ArgumentParser() args = argument_parser.parse_arguments() # 初始化配置单例 config = TranslationConfig() config.initialize(args) # 实例化 PDFTranslator 类,并调用 translate_pdf() 方法 global Translator Translator = PDFTranslator(config.model_name) if __name__ = = "__main__" : # 初始化 translator initialize_translator() # 启动 Gradio 服务 launch_gradio() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了