🚀 作者 :“大數據小禪”
🚀 文章簡介 :本專欄后續將持續更新大模型相關文章,從開發到微調到應用,需要下載好的模型包可私。
🚀 歡迎小伙伴們 點贊👍、收藏?、留言💬
目錄導航
- Langchain中的chain模塊
- 常見的Chain類
- Chain模塊完成英文翻譯
Langchain中的chain模塊
- LangChain的chain模塊用于將多個模型、工具或步驟鏈接在一起,以實現復雜的任務自動化。
- 該模塊提供了各種鏈式操作的功能,可以方便地將不同類型的處理步驟組合起來
常見的Chain類
- LLMChain:將語言模型(如GPT-3)與提示模板結合,用于生成和處理自然語言。
- SimpleSequentialChain:按順序執行一系列步驟,每一步的輸出作為下一步的輸入。
- SequentialChain:支持更復雜的鏈式結構,包括條件邏輯和多輸入/輸出處理
Chain模塊完成英文翻譯
from langchain.prompts.chat import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
import os
from langchain.chains.llm import LLMChain# 設置OpenAI API密鑰
os.environ['OPENAI_API_KEY'] = 'YOUR_API_KEY'# 初始化ChatOpenAI模型,指定使用的模型名稱
openai_model = ChatOpenAI(model_name="gpt-3.5-turbo")# 定義系統消息的模板
system_template = """
you are a translation expert, please translate English to Chinese
"""
system_message = SystemMessagePromptTemplate.from_template(system_template)# 定義用戶消息的模板
human_template = "{english_text}"
human_message = HumanMessagePromptTemplate.from_template(human_template)# 創建聊天模板,包括系統消息和用戶消息
chat_template = ChatPromptTemplate(messages=[system_message, human_message])
print(chat_template) # 打印聊天模板# 格式化消息,將用戶輸入格式化為聊天模板所需的格式
chat_message = chat_template.format_prompt(english_text="please give me a pleasure work")# 生成聊天模型可用的消息記錄 Messages
chat_prompt = chat_template.format_prompt(english_text="please give me a pleasure work").to_messages()
print(chat_prompt) # 打印格式化后的聊天消息# 使用OpenAI模型生成翻譯結果
translation_res = openai_model(chat_prompt)
print(translation_res.content) # 打印翻譯結果# 創建LLMChain對象,用于鏈式調用
translation_chain = LLMChain(llm=openai_model, prompt=chat_template)
print(translation_chain) # 打印LLMChain對象信息# 運行LLMChain,傳入一個字典,包含需要翻譯的文本
res = translation_chain.run({'english_text': 'You can use LLMs to do question answering over tabular data.'})
print(res) # 打印翻譯結果
- 輸出結果