当前位置:首页>python>langserve ——从前端视角学 Python langchain 系列

langserve ——从前端视角学 Python langchain 系列

  • 2026-10-26 09:56:37
langserve ——从前端视角学 Python langchain 系列

什么是 langserve

LangServe[1] 帮助开发者将 LangChain 的 runnables 和 chains[2] 部署为 REST API。该库与 FastAPI[3] 集成,并使用 pydantic[4] 进行数据验证。

此外,它还提供了一个客户端,可用于调用部署在服务器上的 runnables。LangChain.js[5] 中提供了 JavaScript 客户端。

功能特性[6]

  • • 全部采用经过实战检验的开源 Python 库构建,如 FastAPI、Pydantic、uvloop 和 asyncio
  • • 自动生成高效的 /invoke、/batch 和 /stream 端点,支持单台服务器上的大量并发请求
  • • 位于 /playground/ 的 Playground 页面,支持流式输出和中间步骤显示
  • • /stream_log 端点用于流式传输来自您的链/代理的所有(或部分)中间步骤
  • • 自 0.0.40 版本起 新增 支持 /stream_events,使得流式传输更便捷,无需解析 /stream_log 的输出
  • • 使用客户端 SDK 调用 LangServe 服务器,就如同调用本地运行的 Runnable 一样(或直接调用 HTTP API)
  • • 输入和输出 schema 自动从 LangChain 对象推断,并在每次 API 调用时强制执行,提供丰富的错误信息
  • • API 文档页面包含 JSONSchema 和 Swagger(可插入示例链接)
  • • 内置 trace LangSmith[7],只需添加您的 API 密钥(参见 使用说明[8])

总结就是 langserve 将大模型应用部署到 FastAPI,自动暴露成流式对话接口,开箱即用,类似 express + openapi + zod(当然目前 Node.js 是没有对标产品的)。

创建 langserve 应用

这就是本文的罪恶起点 🧗‍♂️: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 = true

https://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.27ms

运行项目

REAMDE 说

langchain serve

但我们需要通过 uvx 运行,因为 langchain 不是全局命令。

方式 1:uvx langchain-cli serve

但是每次运行 ❯ uvx langchain-cli serve 都会重新安装 langchain-cli 且命令长,如何避免?

解法:

uvx 就是“每次临时安装、跑完即丢”,所以必然会重新拉包。
想要“装一次、以后秒启”,改用 uv tool install 把它装进隔离的 全局工具环境即可:

  1. 1. 一次性安装
uv tool install langchain-cli
  1. 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:$PATH

langchain server 运行报错

langchain 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!

解法
  1. 1. 卸载全局包
❯ uv tool uninstall langchain-cli
Uninstalled
 2 executables: langchain-cli.exe, langchain.exe
❯ langchain --version
zsh: command not found: langchain

说明卸载成功。

  1. 2. 将 langchain cli 安装到当前项目

如果 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

说明当前项目安装成功!

ImportError: cannot import name 'VerifyTypes' from 'httpx._types'

❯ 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。

  1. 1. uv remove pydantic && uv add -U pydantic
  2. 2. uv 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 导入三方包类型全部是 Any

翻阅资料发现是 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

最新文章

随机文章