
LangServe[1] 帮助开发者将 LangChain 的 runnables 和 chains[2] 部署为 REST API。该库与 FastAPI[3] 集成,并使用 pydantic[4] 进行数据验证。
此外,它还提供了一个客户端,可用于调用部署在服务器上的 runnables。LangChain.js[5] 中提供了 JavaScript 客户端。
/invoke、/batch 和 /stream 端点,支持单台服务器上的大量并发请求/playground/ 的 Playground 页面,支持流式输出和中间步骤显示/stream_log 端点用于流式传输来自您的链/代理的所有(或部分)中间步骤/stream_events,使得流式传输更便捷,无需解析 /stream_log 的输出总结就是 langserve 将大模型应用部署到 FastAPI,自动暴露成流式对话接口,开箱即用,类似 express + openapi + zod(当然目前 Node.js 是没有对标产品的)。
这就是本文的罪恶起点 🧗♂️:langserve 的官方文档 https://github.com/langchain-ai/langserve#installation 本文将经历九九八十一难 🤣。
langchain app new my-app这个命令等价于
❯ uvx langchain-cli app new my-app
# 类似 npm create vite输出
What package would you like to add? (leave blank to skip):
Success! Created a new LangChain app under "./my-app"!
Next, enter your new app directory by running:
cd ./my-app
Then add templates with commands like:
langchain app add extraction-openai-functions
langchain app add git+ssh://git@github.com/efriis/simple-pirate.git
uv sync 安装依赖,报错“error: No project table found in: pyproject.toml”,原因:cli 默认输出 pyproject.toml 为 poetry 需要转成 uv 支持的格式:
pyproject.toml:
[project]
name = "my-app"
version = "0.1.0"
description = ""
authors = [{name = "Your Name", email = "you@example.com"}]
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"uvicorn>=0.23.2",
"langserve[server]>=0.0.30",
"pydantic<2",
]
[project.optional-dependencies]
dev = [
"langchain-cli>=0.0.15",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
如果再次执行报错:
❯ uv sync
Resolved 52 packages in 1ms
× Failed to download `tenacity==8.5.0`
├─▶ Failed to fetch:
│ `https://pypi.tuna.tsinghua.edu.cn/packages/d2/3f/8ba87d9e287b9d385a02a7114ddcef61b26f86411e121c9003eb509a1773/tenacity-8.5.0-py3-none-any.whl`
╰─▶ HTTP status client error (403 Forbidden) for url
(https://pypi.tuna.tsinghua.edu.cn/packages/d2/3f/8ba87d9e287b9d385a02a7114ddcef61b26f86411e121c9003eb509a1773/tenacity-8.5.0-py3-none-any.whl)换有这个版本的镜像源 ❯ code ~/.config/uv/uv.toml
[[index]]
+ name = "tencent"
+ url = "https://mirrors.cloud.tencent.com/pypi/simple/"
- url = "https://pypi.tuna.tsinghua.edu.cn/simple"
default = truehttps://uv.oaix.tech/blog/2025/06/17/quickly-set-uv-package-index-is-china-mirror/#1-pyprojecttoml
uv sync 继续报错
ValueError: Unable to determine which files to ship inside the wheel using the following heuristics:
https://hatch.pypa.io/latest/plugins/builder/wheel/#default-file-selection
The most likely cause of this is that there is no directory that matches the name of your project (my_app).
At least one file selection option must be defined in the `tool.hatch.build.targets.wheel` table, see:
https://hatch.pypa.io/latest/config/build/
As an example, if you intend to ship a directory named `foo` that resides within a `src` directory located at the root of
your project, you can define the following:
[tool.hatch.build.targets.wheel]
packages = ["src/foo"]解决:pyproject.toml
[tool.hatch.build.targets.wheel]
packages = ["my-app"] 这回成功了
❯ uv sync
Resolved 52 packages in 1ms
Audited 37 packages in 0.27msREAMDE 说
langchain serve但我们需要通过 uvx 运行,因为 langchain 不是全局命令。
方式 1:uvx langchain-cli serve
但是每次运行 ❯ uvx langchain-cli serve 都会重新安装 langchain-cli 且命令长,如何避免?
解法:
uvx就是“每次临时安装、跑完即丢”,所以必然会重新拉包。
想要“装一次、以后秒启”,改用uv tool install把它装进隔离的 全局工具环境即可:
1. 一次性安装 uv tool install langchain-cli
2. 以后随便用 langchain-cli serve # 直接当普通命令用,无需再前置 uvx
uv会在$HOME/.local/bin(Linux/macOS)或%APPDATA%\uv\bin(Windows)里放一个可执行文件,并自动帮你把该目录加进 PATH。
以后无论在哪,直接langchain-cli serve都是秒启动,不会再下载。
我们试试 ❯ langchain --version 输出
langchain-cli 0.0.37说明被全局安装了,这非我所愿!我们需要一个类似 npm 安装在项目内然后 npx foo-cli。除了『全局污染』后面还有讲到全局安装会踩其他坑,具体解决方案随后也会讲到。
因为 uv 安装之初就自动写了 $HOME/.local/bin 需要当做全局命令使用。
# add uv to path using export is more fast than `source`
export PATH=$HOME/.local/bin:$PATHlangchain serve 或 uv run langchain serve
❯ langchain serve
INFO: Will watch for changes in these directories: ['F:\\workspace\\github\\my-app']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [23700] using StatReload
TypeError: Expected a Runnable, got <class 'NotImplementedType'>. The second argument to add_routes should be a Runnable instance.add_route(app, runnable, ...) is the correct usage.Please make sure that you are using a runnable which is an instance of langchain_core.runnables.Runnable.原因在 app/server.py line 14
add_routes(app, NotImplemented)好的现在我们改成自己的模型
# Edit this to add the chain you want to add
add_routes(
app,
chatModel,
path="/openai",
)❯ uv run langchain serve 报错 ModuleNotFoundError: No module named 'dotenv' 或 ModuleNotFoundError: No module named 'langchain_openai' 但是明明项目里已安装这两模块。
uv run langchain serve
INFO: Will watch for changes in these directories: ['F:\\workspace\\github\\my-app']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [22924] using StatReload
File "F:\workspace\github\my-app\app\server.py", line 5, in <module>
from .lib.models import chatModel
File "F:\workspace\github\my-app\app\lib\models.py", line 4, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
INFO: Stopping reloader process [22924]app/lib/models.py 如下:
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from pydantic import SecretStr这是因为我们的 langchain-cli 是全局安装的!❯ uv tool install langchain-cli,核心原因是 python-dotenv 包没有安装在 langchain-cli 命令所使用的那个 Python 环境中。全局当然无 dotenv 和 langchain_openai!
❯ uv tool uninstall langchain-cli
Uninstalled 2 executables: langchain-cli.exe, langchain.exe❯ langchain --version
zsh: command not found: langchain说明卸载成功。
如果 pyproject.toml 已经有了,直接 uv sync 即可,否则 uv add langchain-cli --dev,前端同学是不是特别熟悉,等价于 npm i -D foo 或 pnpm add -D foo。
[project.optional-dependencies]
dev = [
"langchain-cli>=0.0.15",
]❯ uv run langchain --version
langchain-cli 0.0.37说明当前项目安装成功!
❯ uv run langchain serve 报错:
ImportError: cannot import name 'VerifyTypes' from 'httpx._types' (F:\workspace\github\my-app\.venv\Lib\site-packages\httpx\_types.py)ImportError: cannot import name 'VerifyTypes' from 'httpx._types' #796[9] 说 uv install httpx==0.27.2。
即定死版本号,但是这样肯定对于一个新项目是的维护性是大打折扣的。我们最好还是通过升级 langchain-cli 或 langserve 来解决。
langchain-cli 已是最新,langserve 升级就没那么简单了,我在这里查询了大量文档做了多次尝试。
首先我们回到 uvx langchain-cli app new my-app 生成的 pyproject.toml
requires-python = ">=3.11"
dependencies = [
"uvicorn>=0.23.2",
"langserve[server]>=0.0.30",
"pydantic<2",
]尝试 1
❯ uv add -U 'langserve[server]',但 langserve 安装 0.2.3 而非我们预期的最新 0.3.3(2025-12-23)。
怎么看最新版本:https://pypi.org/project/langserve/
pypi.org 类似 npmjs.com
-U类似npm i foo@latest
尝试 2
uv add 'langserve[server]==0.3.3' 类似 npm 写死版本号。
❯ uv add 'langserve[server]==0.3.3'
× No solution found when resolving dependencies for split (python_full_version >= '3.12.4'):
╰─▶ Because langserve==0.3.3 depends on pydantic>=2.7,<3.0 and your project depends on langserve[server]==0.3.3, we can conclude
that your project depends on pydantic>=2.7,<3.0.
And because your project depends on pydantic<2 and your project requires my-app[dev], we can conclude that your project's
requirements are unsatisfiable.
help: If you want to add the package regardless of the failed resolution, provide the `--frozen` flag to skip locking and syncing.终于有点眉目了。
说明我们需要先升级 pydantic。
uv remove pydantic && uv add -U pydanticuv remove 'langserve[server]' && uv add -U 'langserve[server]'终于运行成功了 🎉,太不容易了尤其是从前端转来的 Python 新手!
❯ uv run langchain serve
INFO: Will watch for changes in these directories: ['F:\\workspace\\github\\my-app']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [1860] using StatReload
SecretStr(api_key)=SecretStr('**********')
base_url='https://ark.cn-beijing.volces.com/api/v3'
API Key 已成功加载
INFO: Started server process [20556]
INFO: Waiting for application startup.
__ ___ .__ __. _______ _______. _______ .______ ____ ____ _______
| | / \ | \ | | / _____| / || ____|| _ \ \ \ / / | ____|
| | / ^ \ | \| | | | __ | (----`| |__ | |_) | \ \/ / | |__
| | / /_\ \ | . ` | | | |_ | \ \ | __| | / \ / | __|
| `----./ _____ \ | |\ | | |__| | .----) | | |____ | |\ \----. \ / | |____
|_______/__/ \__\ |__| \__| \______| |_______/ |_______|| _| `._____| \__/ |_______|
LANGSERVE: Playground for chain "/openai/" is live at:
LANGSERVE: │
LANGSERVE: └──> /openai/playground/
LANGSERVE:
LANGSERVE: See all available routes at /docs/
INFO: Application startup complete.完整代码见 github[10]。
最后再来解决一个编辑器类型问题,当我们将代码从 VSCode 打开换成 Trae,却发现:
翻阅资料发现是 Trae 没有 pylance 插件导致的,社区也有历史反馈 Pylance not available #38[11],说使用 BasePyright 或 Pyright,但是都不好使。死马当活马医,试试 uv 公司新出的 ty,trae 内搜索居然有,而且安装后一切正常了!我也在 GitHub issue 留言了『自己淋过雨希望给他人撑把伞[12]』。
[1] LangServe: https://github.com/langchain-ai/langserve[2] runnables 和 chains: https://python.langchain.com/docs/expression_language/[3] FastAPI: https://fastapi.tiangolo.com/[4] pydantic: https://docs.pydantic.dev/latest/[5] LangChain.js: https://js.langchain.com/docs/ecosystem/langserve[6] 功能特性: https://github.com/langchain-ai/langserve#features[7] LangSmith: https://www.langchain.com/langsmith[8] 使用说明: https://docs.smith.langchain.com/[9] ImportError: cannot import name 'VerifyTypes' from 'httpx._types' #796: https://github.com/langchain-ai/langserve/issues/796[10] github: https://github.com/legend80s/youtube-video-article-generator-python[11] 历史反馈 Pylance not available #38: https://github.com/Trae-AI/Trae/issues/38[12] 自己淋过雨希望给他人撑把伞: https://bgithub.xyz/Trae-AI/Trae/issues/38#issuecomment-3688761693