在本文中,将学习如何利用LangChain的强大功能来创建一个从英文翻译到其他语言的基本应用程序。尽管这是一个简单的示例,但它为提供了对LangChain中一些关键概念和工作流程的基础理解。将使用LCEL(LangChain表达式语言)来构建这个LLM应用程序。
通过本文的学习,将更好地理解以下要点:
- 使用语言模型:应用程序的核心是调用一个大型语言模型(LLM)来处理翻译,通过发送提示并接收响应。
- 提示模板和输出解析器:提示模板为动态输入创建灵活的提示,而输出解析器确保LLM的响应格式正确。
- LangChain表达式语言(LCEL):LCEL将创建提示、发送LLM和处理输出等步骤串联起来,实现更复杂的工作流程。
- 使用LangSmith进行调试:LangSmith帮助监控性能,追踪数据流,并在应用程序扩展时调试组件。
- 使用LangServe部署:LangServe允许将应用程序部署到云端,使其对其他用户可用。
以下是构建LCEL的LLM应用程序的步骤:
安装所需库
!pip install langchain!pip install -qU langchain-openai!pip install fastapi!pip install uvicorn!pip install langserve[all]设置OpenAI GPT-4模型进行翻译
import getpassimport osos.environ["OPENAI_API_KEY"] = getpass.getpass('Enter your OpenAI API Key:')from langchain_openai import ChatOpenAImodel = ChatOpenAI(model="gpt-4")使用模型进行英文到日文翻译
from langchain_core.messages import HumanMessage, SystemMessagemessages = [SystemMessage(content="Translate the following from English into Japanese"),HumanMessage(content="I love programming in Python!"),]response = model.invoke(messages)response.content使用输出解析器
from langchain_core.output_parsers import StrOutputParserparser = StrOutputParser()parsed_result = parser.invoke(response)parsed_result将组件串联在一起
chain = model | parsertranslated_text = chain.invoke(messages)translated_text使用提示模板进行翻译
from langchain_core.prompts import ChatPromptTemplatesystem_template = "Translate the following text into Japanese:"prompt_template = ChatPromptTemplate.from_messages([('system', system_template),('user', '{text}')])result = prompt_template.invoke({"text": "I love programming in Python!"})result.to_messages()使用LCEL(LangChain表达式语言)进行串联
chain = prompt_template | model | parserfinal_translation = chain.invoke({"text": "I love programming in Python!"})final_translation使用LangSmith进行调试
os.environ["LANGCHAIN_TRACING_V2"] = "true"os.environ["LANGCHAIN_API_KEY"] = getpass.getpass('Enter your LangSmith API Key:')-
from fastapi import FastAPIfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_openai import ChatOpenAIfrom langserve import add_routesimport osos.environ["OPENAI_API_KEY"] = "Put your api here"model = ChatOpenAI()prompt_template = ChatPromptTemplate.from_messages([('system', system_template),('user', '{text}')])parser = StrOutputParser()chain = prompt_template | model | parserapp = FastAPI(title="LangChain English to Japanese Translation API", version="1.0")add_routes(app, chain, path="/chain") -
if __name__ == "__main__":import uvicornuvicorn.run(app, host="localhost", port=8000) -
from langserve import RemoteRunnableremote_chain = RemoteRunnable("http://localhost:8000/chain/")translated_text = remote_chain.invoke({"text": "I love programming in Python!"})print(translated_text)