LMDeploy Anthropic 兼容端点(/v1/messages)接入指南:从启动 API Server 到工具调用与 SSE 流式响应
LMDeploy Anthropic 兼容端点(/v1/messages)接入指南:从启动 API Server 到工具调用与 SSE 流式响应
LMDeploy 在标准 OpenAI 兼容接口之外,额外提供了一套轻量的 Anthropic 兼容服务面(Anthropic-compatible surface),让 Anthropic 风格的客户端、网关(如 Claude Code 等工具生态)可以直接复用 POST /v1/messages、POST /v1/messages/count_tokens 与 GET /anthropic/v1/models 三个端点完成对话、工具调用与 token 估算。本文以 docs/en/llm/api_server_anthropic.md 为主体,结合 lmdeploy/serve/anthropic 目录下的路由、协议、适配与流式实现源码,完整讲解端点清单、请求头约束、请求/响应协议、工具调用与 reasoning 输出、SSE 流式事件序列、token 计数原理,以及服务端参数校验与错误语义,帮助你直接在 LMDeploy 上对接 Anthropic 协议客户端。
一、端点总览与接入位置
Anthropic 兼容层共暴露三个端点,均挂在同一个 FastAPI 路由上:
| 端点 | 方法 | 用途 |
|---|---|---|
/v1/messages |
POST | 对话补全,支持文本、thinking(reasoning)与 tool_use 三种输出块 |
/v1/messages/count_tokens |
POST | 估算输入 token 数,返回 { "input_tokens": N } |
/anthropic/v1/models |
GET | 列出服务当前可用的模型名 |
路由的组装逻辑集中在 router.py 的 create_anthropic_router:它会先探测当前 chat template 是否支持内联 system 消息(detect_inline_system_support),再把三个端点依次注册到 APIRouter 上。该 router 在 api_server.py 中与 OpenAI router、Responses router 一同挂载到应用上:
router = create_openai_router(server_context)
app.include_router(router)
app.include_router(create_anthropic_router(server_context))
app.include_router(create_responses_router(server_context))
因此不需要任何额外开关,只要按标准方式启动 API Server,Anthropic 端点就自动生效。启动方式与通用接口完全一致,例如(详见 api_server.md):
lmdeploy serve api_server internlm/internlm2_5-7b-chat --server-port 23333
其他常用参数(--tp 张量并行、--session-len 上下文长度、--cache-max-entry-count KV cache 显存占比等)均可通过 lmdeploy serve api_server -h 查看,具体参数解析入口在 serve.py 的 SubCliServe.api_server。
二、必需请求头
对 Anthropic 的两个 POST 端点,请求必须携带以下头:
content-type: application/jsonanthropic-version: 2023-06-01(或其他被接受的版本字符串)
anthropic-version 是硬校验项:在 validation.py 与 messages_count_tokens.py 中,若请求缺少该头,服务会直接返回 400:
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "Missing required header: anthropic-version"
}
}
三、请求协议:MessagesRequest 字段详解
POST /v1/messages 的请求体由 protocol.py 中的 MessagesRequest 定义,它完整覆盖了 Anthropic Messages API 的常用字段,并扩展了若干 LMDeploy 特有字段:
| 字段 | 类型 | 说明 |
|---|---|---|
model |
str | 必填,模型名,须在服务端模型列表中 |
messages |
list | 消息历史,role 支持 user/assistant/system,content 可为字符串或内容块列表 |
max_tokens |
int | 必填,须 > 0(Pydantic gt=0 约束) |
system |
str / list | 系统提示词,可为字符串或内容块列表 |
stop_sequences |
list[str] | 停止序列,会被映射为 OpenAI 协议的 stop |
stream |
bool | 是否流式返回(默认 false) |
temperature / top_p / top_k |
float/int | 采样参数,取值在 [0, 1](top_k 须非负) |
metadata |
dict | 透传元数据 |
tools |
list[ToolParam] | 工具定义,name、description、input_schema |
tool_choice |
对象/字符串 | 支持 {"type":"auto"}、{"type":"any"}、{"type":"tool","name":...} 或字符串 "auto"/"any" |
service_tier |
str | auto 或 standard_only |
扩展字段(来自 /generate 端点的能力透传):
input_ids:token ID 列表。仅当messages为空时生效,用于绕过消息渲染直接送入 token 序列;image_data:多模态图片输入(URL/base64 字符串、dict 或它们的列表),同样仅与input_ids配合使用;return_routed_experts:是否返回 MoE 路由专家索引;return_token_ids:是否在响应中附带输出 token ID;return_logprob:是否返回输出 token 的对数概率;include_stop_str_in_output:是否把命中的停止序列包含在输出文本中。
messages 中的 content 支持多块结构(ContentBlockParam,见 protocol.py):text、thinking、redacted_thinking、image、tool_use、tool_result 等类型都会被适配器逐块转换(详见下文“协议适配”)。
四、最简调用示例:/v1/messages
文档给出的基础示例(原样可运行,只需替换 server_ip、server_port 与 model):
curl http://{server_ip}:{server_port}/v1/messages \
-H "content-type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "intern-s2-preview",
"max_tokens": 128,
"messages": [{"role": "user", "content": "Hello from Anthropic client"}]
}'
非流式响应结构由 protocol.py 的 MessagesResponse 定义,包含 id(形如 msg_<uuid>)、type: "message"、role: "assistant"、content 块列表、model、stop_reason、stop_sequence、usage(input_tokens / output_tokens),以及可选的 output_ids、output_token_logprobs、routed_experts。stop_reason 取值共五种:end_turn、max_tokens、stop_sequence、tool_use、parse_error。
内容块共三类:
MessageTextBlock:{"type": "text", "text": "..."}MessageThinkingBlock:{"type": "thinking", "thinking": "...", "signature": "lmdeploy-local"}(signature 常量LOCAL_THINKING_SIGNATURE,见 protocol.py)MessageToolUseBlock:{"type": "tool_use", "id": "...", "name": "...", "input": {...}}
若没有产生任何内容块,服务会回退为单个空文本块 <a href="https://link.gitcode.com/i/cb733d358152f5420abaf7cff7faf148" target="_blank">MessageTextBlock(text='')](见 [messages.py)。
五、协议适配:Anthropic 请求如何进入 LMDeploy 推理栈
Anthropic 端点并非独立实现推理,而是把请求“翻译”成 OpenAI 兼容协议再走统一的 ChatRunner。核心适配逻辑位于 adapter.py:
- 消息转换(
to_openai_messages,adapter.py):把system与每条消息的内容块逐块映射——text→ OpenAI 的文本内容;image→ OpenAI 的image_url内容(source.type为url或base64时分别构造 URL 或data:{media_type};base64,{data},见_convert_image_source_to_url);tool_use→ OpenAI 的tool_calls(arguments为input的 JSON 序列化);tool_result→ 对应role: "tool"消息(含tool_call_id),图片结果会追加一条image_url的 user 消息(_convert_user_tool_result);thinking→ 汇总到reasoning_content字段;redacted_thinking直接跳过;- 系统提示会合并为一条
role: "system"消息,且x-anthropic-billing-header开头的计费头文本会被过滤(_convert_system_message)。 - 若 chat template 不支持内联 system 消息,
merge_inline_system=True会把所有 system 内容前移合并(_merge_system_messages),该能力由detect_inline_system_support在 router.py 启动时探测得出。
- 工具转换(
to_openai_tools):Anthropic 的{name, description, input_schema}映射为 OpenAI 的type: "function"工具定义。 - tool_choice 归一化(
normalize_tool_choice):{"type":"any"}→"required";{"type":"tool","name":X}→ 指定函数名;其余(含auto与缺省)→"auto"。 - stop_reason 映射(
map_finish_reason):stop→end_turn、length→max_tokens、tool_calls→tool_use、parse_error→parse_error、abort/error→stop_sequence。
转换完成后,messages.py 构造一个 ChatCompletionRequest,通过 ChatRunner.prepare 提交给统一引擎;非流式模式下用 chat_runner.collect 收集结果,再经 build_message_content_blocks(adapter.py)把 reasoning_content、正文文本与 tool_calls 还原为 thinking/text/tool_use 内容块。
六、工具调用(Tool Use)实战
工具调用不仅需要请求体携带 tools,服务端还必须预先配置工具解析器。文档明确指出:Tool use requires launching API server with a configured tool parser(--tool-call-parser ...)。
启动示例(解析器名可用 lmdeploy serve api_server -h 查看,--tool-call-parser 参数定义在 cli/utils.py):
lmdeploy serve api_server intern-s2-preview \
--server-port 23333 \
--tool-call-parser <注册的工具解析器名称>
带工具调用的请求示例(来自文档,完整保留):
curl http://{server_ip}:{server_port}/v1/messages \
-H "content-type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "intern-s2-preview",
"max_tokens": 128,
"messages": [{"role": "user", "content": "Find lmdeploy docs"}],
"tools": [{
"name": "search",
"description": "Search docs",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}],
"tool_choice": {"type": "auto"}
}'
服务端的工具相关校验集中在 validation.py:
tool_choice={"type":"any"}必须在tools中至少提供一个工具,否则 400;tool_choice={"type":"tool","name":X}要求tools非空且X必须在tools列表中,否则 400;- 只要请求携带
tools,而服务端未配置--tool-call-parser,一律返回 400:Please launch the api_server with --tool-call-parser if you want to use tool calling.
模型决定调用工具后,响应会包含 {"type": "tool_use", ...} 内容块,stop_reason 为 tool_use;后续轮次中客户端应把工具结果以 tool_result 块回传,适配器会将其转换为 role: "tool" 消息并正确关联 tool_call_id。
七、Reasoning / thinking 输出
文档指出:reasoning 块(thinking)的提取依赖解析器配置,与 OpenAI 兼容 chat 端点共用同一套 parser 栈。即服务端需通过 --reasoning-parser 指定 reasoning 解析器(参数定义见 cli/utils.py):
lmdeploy serve api_server intern-s2-preview \
--server-port 23333 \
--reasoning-parser <注册的 reasoning 解析器名称>
开启后,模型的思考内容会被解析并输出为 MessageThinkingBlock(非流式)或 thinking_delta(流式),并携带固定的本地签名 signature: "lmdeploy-local";请求历史中的 thinking/redacted_thinking 块也会被适配器正确解析(thinking 汇入 reasoning_content,redacted_thinking 跳过),保证多轮对话上下文一致。
八、流式响应(SSE Events)
当请求设置 stream=true 时,端点返回 text/event-stream(ManagedStreamingResponse,media type 见 messages.py),事件序列与 Anthropic 官方协议一致,文档列出的事件类型为:
message_startcontent_block_startcontent_block_delta(text_delta、thinking_delta、input_json_delta)content_block_stopmessage_deltamessage_stop
从源码看,实际事件集合还包括 ping 与 error(协议定义见 protocol.py),SSE 帧格式为 event: <type>\ndata: <json>\n\n(见 streaming.py)。
流式转换器 stream_messages_response(streaming.py)的实现要点:
- 先缓存第一个解析 chunk 用于填充
message_start事件中的usage(Anthropic 要求message_start携带 usage 且 content 为空),随后该 chunk 仍走正常的内容块路径; - 用块状态机(
_StreamBlockState)维护 text / thinking / tool_use 三种块的索引与切换:同一块内的增量发text_delta或thinking_delta,工具参数增量发input_json_delta(partial_json); - thinking 块结束时补发
signature_delta(签名为lmdeploy-local); - 生成结束(或解析流中抛出
RequestError)时,先关闭当前块,再发message_delta(携带最终stop_reason与累计output_tokens)与message_stop; - 若启用了
return_token_ids/return_logprob,对应元数据会附在最后一个相关 delta 事件上;routed_experts附带在message_delta中。
九、Token 计数端点:/v1/messages/count_tokens
count_tokens 用于在真正生成前估算输入 token 数,文档特别说明:它是基于 tokenizer/chat template 的近似估算(practical estimation),并非模型精确计数的复刻。
curl http://{server_ip}:{server_port}/v1/messages/count_tokens \
-H "content-type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "intern-s2-preview",
"system": "You are a helpful assistant.",
"messages": [{"role": "user", "content": "Count these tokens"}]
}'
响应体为 CountTokensResponse,仅含 input_tokens 一个字段(protocol.py)。
实现细节(messages_count_tokens.py + adapter.py):
- 校验
anthropic-version头(缺失返回 400); - 校验
model在服务端模型列表中(否则返回not_found_error); CountTokensRequest要求messages非空(Pydantic validator 强制至少一条,见 protocol.py);- 通过
to_lmdeploy_messages把请求转换为纯文本聊天消息,然后调用async_engine.chat_template.messages2prompt渲染提示词,再用tokenizer.encode(prompt, add_bos=True)编码并返回 token 数。
十、模型列表端点:GET /anthropic/v1/models
该端点返回 Anthropic 风格的模型列表,供 Anthropic 客户端发现可用模型:
curl http://{server_ip}:{server_port}/anthropic/v1/models
响应结构为 AnthropicModelList(protocol.py):data 为 <a href="https://link.gitcode.com/i/cb525ce77dacb790e5949cdd4d2141a9" target="_blank">{id, type: "model", display_name, created_at}] 列表,另有 has_more: false、first_id、last_id 分页占位字段。模型名来源是 get_model_list([adapter.py):引擎主模型名 + 配置中的 adapters 列表。
十一、扩展输入路径:input_ids 与 image_data
MessagesRequest 支持绕过消息渲染的原始输入路径:当 messages 为空时,可用 input_ids(必要时配合 image_data)直接输入 token 序列,适用于已编码输入或与 /generate 对齐的场景。相关约束(validation.py):
messages非空时禁止同时携带input_ids/image_data;messages为空时必须提供非空input_ids,否则 400;image_data必须配合input_ids使用;- 使用
input_ids时禁止携带system、tools及非auto的tool_choice(原始 token 绕过消息渲染,无法做工具解析)。
image_data 会被组装为 image_url 内容块(URL 或 base64 data URI),与文本输入合并为一条 user 消息后进入推理(messages.py)。
十二、错误语义
所有 POST 端点的错误都采用 Anthropic 风格包装:{"type": "error", "error": {"type": ..., "message": ...}}(errors.py)。错误类型映射规则:
| 场景 | HTTP 状态码 | error.type |
|---|---|---|
| 参数/校验类错误(缺头、模型不存在、采样参数越界、工具配置缺失等) | 400 / 404 | invalid_request_error / not_found_error |
引擎内部错误(INTERNAL_ERROR) |
500 | api_error |
| 引擎不可用 | 503 | overloaded_error |
| 鉴权失败 | 401 | authentication_error |
流式场景下的错误会以 error SSE 事件发出(ErrorEvent),且错误发生前已打开的块会被先关闭,保证事件序列合法(streaming.py)。
十三、测试与验证
仓库在 tests/test_lmdeploy/serve/anthropic/ 下提供了两组针对性测试,可作为理解行为边界的参考:
- test_endpoints.py:用
create_anthropic_router构造路由并直接调用端点,覆盖POST /v1/messages、POST /v1/messages/count_tokens的请求头校验、模型校验、工具调用、流式事件序列与错误响应; - test_adapter_conversion.py:验证
to_openai_messages/to_lmdeploy_messages对text、tool_use、tool_result、thinking、image、系统计费头等各类内容块的转换结果。
十四、当前限制小结
/v1/messages仅支持文本、reasoning(thinking)与工具(tool_use)三类输出块,不包含多模态输出块;- 工具调用必须在启动时配置
--tool-call-parser,reasoning 提取必须配置--reasoning-parser; count_tokens为 tokenizer/chat-template 层面的近似估算,适合预算预估而非精确计费;- 扩展字段(
return_logprob需引擎开启logprobs_mode,return_routed_experts需启动时带--enable-return-routed-experts)在未开启对应引擎配置时会被服务端拒绝(validation.py)。
掌握了以上端点、请求协议、适配链路与校验规则后,你可以直接用 Anthropic SDK 或任意 Anthropic 协议客户端对接 LMDeploy 服务,在统一的推理引擎上获得文本、思考与工具调用的完整能力。