6. LangServe 与 LangChain.js
# 6.1 LangServe
LangServe 用于将 Chain 或者 Runnable 部署成一个 REST API 服务。
# 安装
pip install --upgrade "langserve[all]"
# 也可以只安装一端
# pip install "langserve[client]"
# pip install "langserve[server]"
1
2
3
4
5
2
3
4
5
# 服务端示例
server.py:
from fastapi import FastAPI
from langchain.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langserve import add_routes
import uvicorn
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple api server using Langchain's Runnable interfaces",
)
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("讲一个关于{topic}的笑话")
add_routes(
app,
prompt | model,
path="/joke",
)
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=9999)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 客户端示例
client.py:
import requests
response = requests.post(
"http://localhost:9999/joke/invoke",
json={'input': {'topic': '小明'}}
)
print(response.json())
1
2
3
4
5
6
7
2
3
4
5
6
7
输出示例:
{
'output': {
'content': '小明去看电影,结果一路上碰到了三个警察,第一个警察对他说:"小朋友,你怎么不去上学?" \n小明回答说:"我今天放学了。" \n第二个警察问:"你家长知道你去看电影吗?" \n小明想了一下说:"他们也在看电影。" \n第三个警察开玩笑地说:"你要注意安全,不然吃不到晚饭!" \n小明笑着说:"没关系,我早餐吃了两碗!"',
'additional_kwargs': {'refusal': None},
'response_metadata': {
'token_usage': {
'completion_tokens': 161,
'prompt_tokens': 17,
'total_tokens': 178,
...
},
'model_name': 'gpt-3.5-turbo-0125',
'finish_reason': 'stop',
...
},
'type': 'ai',
'id': 'run-bbf58653-832d-4eef-a3d7-2d48e5e666af-0',
...
},
'metadata': {
'run_id': '4e2c6608-e4cc-4137-8dd9-c40a65a229c8',
'feedback_tokens': []
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 6.2 LangChain.js
LangChain.js 是 Python 版 LangChain 的姊妹项目,都是由 Harrison Chase 主理。
- 项目地址:https://github.com/langchain-ai/langchainjs (opens new window)
- 文档地址:https://js.langchain.com/docs/ (opens new window)
# 特色
- 可以和 Python 版 LangChain 无缝对接
- 抽象设计完全相同,概念一一对应
- 所有对象序列化后都能跨语言使用,但 API 差别挺大,不过在努力对齐
# 支持环境
- Node.js (ESM and CommonJS) - 18.x, 19.x, 20.x
- Cloudflare Workers
- Vercel / Next.js (Browser, Serverless and Edge functions)
- Supabase Edge Functions
- Browser
- Deno
# 安装
npm install langchain
1
# 当前重点
- 追上 Python 版的能力(甚至为此做了一个基于 gpt-3.5-turbo 的代码翻译器)
- 保持兼容尽可能多的环境
- 对质量关注不多,随时间自然能解决
编辑 (opens new window)
上次更新: 2025/12/19, 15:17:48