llama serve 在 http://localhost:9931 上以多种格式暴露 REST API:

  • OpenAI 兼容端点位于 /v1/...,可与现有的 OpenAI SDK 和应用程序配合使用
  • Anthropic 兼容的 /v1/messages 端点
  • 具有额外功能(更底层选项)的 llama.cpp 端点

如果服务器启动时使用了 --api-key,请将其作为 Bearer token 传递:Authorization: Bearer YOUR_KEY。

Chat completions

POST /v1/chat/completions 是你最常使用的端点。它接受标准的 OpenAI chat 格式,并通过 "stream": true 支持流式传输:

curl http://localhost:9931/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Write a limerick about python exceptions"}
        ]
    }'

或者使用 OpenAI Python SDK —— 只需更改 base URL:

import openai

client = openai.OpenAI(base_url="http://localhost:9931/v1", api_key="no-key-required")

completion = client.chat.completions.create(
    model="local-model",
    messages=[{"role": "user", "content": "Write a limerick about python exceptions"}],
)
print(completion.choices[0].message.content)

除了 OpenAI 参数外,同一请求体中还接受 llama.cpp 特有的生成参数。

结构化输出

将响应约束为有效的 JSON,或特定的 schema:

{
	"messages": [{ "role": "user", "content": "Extract the name and date: ..." }],
	"response_format": {
		"type": "json_schema",
		"schema": {
			"type": "object",
			"properties": {
				"name": { "type": "string" },
				"date": { "type": "string" }
			},
			"required": ["name", "date"]
		}
	}
}

对于自由格式的 JSON,请使用 {"type": "json_object"}。

工具调用

OpenAI 风格的 function calling 适用于任何模型;针对经过工具使用训练的模型使用其原生格式,其他模型则使用通用回退机制。照常传递 tools 和 tool_choice。有关支持的模型系列,请参阅 function calling 文档。

多模态输入

视觉和音频模型接受消息中的带类型内容部分:

{
	"messages": [
		{
			"role": "user",
			"content": [
				{ "type": "text", "text": "What is in this image?" },
				{ "type": "image_url", "image_url": { "url": "https://example.com/photo.jpg" } }
			]
		}
	]
}

image_url.url 可以是远程 URL 或 base64 data URI;input_audio 对音频文件的工作方式相同。

推理模型

对于 thinking models,解析后的 reasoning 返回在 message.reasoning_content 中,与 message.content 中的最终答案分开(可通过 --reasoning-format 配置)。

计时和使用情况

响应包含标准的 OpenAI usage 对象,以及一个 llama.cpp timings 对象,其中包含 tokens-per-second 统计信息和从缓存中复用的 prompt tokens 数量(cache_n)——有助于跟踪性能和上下文使用情况。

其他 OpenAI 兼容端点

端点用途
POST /v1/completions基于原始 prompt 的文本补全
POST /v1/responsesOpenAI Responses API(内部转换为 chat completions)
POST /v1/embeddingsEmbeddings — 需要启用 pooling 的模型(参见 serving)
POST /v1/rerank根据查询对文档进行排序 — 需要 reranker 模型
GET /v1/models模型元数据(id、context size、parameters)

/v1/models 报告的模型 id 默认为模型文件路径;使用 --alias 设置友好的名称。

Anthropic 兼容端点

POST /v1/messages 接受 Anthropic Messages API 格式,包括 system、stop_sequences、流式传输和工具使用 —— 因此 Anthropic SDK 和应用程序也可以指向 llama serve:

curl http://localhost:9931/v1/messages \
    -H "Content-Type: application/json" \
    -H "x-api-key: your-api-key" \
    -d '{
        "model": "local-model",
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": "Hello!"}]
        }'

POST /v1/messages/count_tokens 在不生成的情况下计算输入 tokens。

原生端点

这些端点暴露了 OpenAI 接口范围之外的 llama.cpp 原生功能:

端点用途
GET /health存活检测:就绪时返回 200,加载中返回 503
POST /completion原生补全,支持 llama.cpp 全套参数(token 数组、n_probs 对数概率、id_slot 槽位固定、单请求 LoRA 缩放等)
POST /tokenize / POST /detokenize文本与 token 之间相互转换
POST /apply-template仅应用模型的对话模板,不执行推理
POST /infill基于 input_prefix 和 input_suffix 实现中间填充式代码补全
GET /props服务器与模型属性(上下文长度、对话模板、支持的模态)
GET /slots查看每个处理槽位的当前状态
GET /metricsPrometheus 指标(需启用 --metrics 参数)
GET /lora-adapters / POST /lora-adapters运行时列出并设置 LoRA 适配器缩放系数

一个最简原生补全请求示例:

curl http://localhost:9931/completion \
-H "Content-Type: application/json" \
-d '{"prompt": "Building a website can be done in 10 simple steps:", "n_predict": 128}'

路由模式

当同时部署多个模型时,同一套 API 会按模型名路由请求:POST 请求体里的 "model" 字段,或 GET 端点上的 ?model= 查询参数。GET /models 列出所有可用模型及其加载状态与支持模态;POST /models/load / POST /models/unload 用于显式加载/卸载模型。

错误格式

错误响应采用 OpenAI 格式:

{
"error": {
"code": 401,
"message": "Invalid API Key",
"type": "authentication_error"
}
}

完整的请求/响应结构与全部端点参数,请参阅服务器 README。