您可以通过 LM Studio 的 REST API(或通过任何 OpenAI 客户端)向 /v1/chat/completions
终端节点提供 JSON 模式,从而强制 LLM 返回特定的响应格式。
将 LM Studio 启动为服务器
要从您自己的代码中以编程方式使用 LM Studio,请将 LM Studio 作为本地服务器运行。
您可以从 LM Studio 的“开发者”选项卡或通过 lms
CLI 启动服务器
通过运行 npx lmstudio install-cli
安装 lms
这将允许您通过类似 OpenAI 的 REST API 与 LM Studio 交互。 有关 LM Studio 类似 OpenAI 的 API 的介绍,请参阅将 LM Studio 作为服务器运行。
结构化输出
当给定 JSON 模式时,API 通过 /v1/chat/completions
终端节点支持结构化 JSON 输出。 这样做将导致 LLM 以符合所提供模式的有效 JSON 格式响应。
它遵循与 OpenAI 最近宣布的 结构化输出 API 相同的格式,并且预计可通过 OpenAI 客户端 SDK 工作。
使用 curl
的示例
此示例演示了使用 curl
实用程序的结构化输出请求。
要在 Mac 或 Linux 上运行此示例,请使用任何终端。 在 Windows 上,使用 Git Bash。
curl http://{{hostname}}:{{port}}/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "{{model}}",
"messages": [
{
"role": "system",
"content": "You are a helpful jokester."
},
{
"role": "user",
"content": "Tell me a joke."
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "joke_response",
"strict": "true",
"schema": {
"type": "object",
"properties": {
"joke": {
"type": "string"
}
},
"required": ["joke"]
}
}
},
"temperature": 0.7,
"max_tokens": 50,
"stream": false
}'
/v1/chat/completions
识别的所有参数都将被接受,JSON 模式应在 response_format
的 json_schema
字段中提供。
JSON 对象将以 string
形式在典型的响应字段 choices[0].message.content
中提供,并且需要解析为 JSON 对象。
使用 python
的示例
from openai import OpenAI
import json
client = OpenAI(
base_url="https://127.0.0.1:1234/v1",
api_key="lm-studio"
)
messages = [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Create 1-3 fictional characters"}
]
character_schema = {
"type": "json_schema",
"json_schema": {
"name": "characters",
"schema": {
"type": "object",
"properties": {
"characters": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"occupation": {"type": "string"},
"personality": {"type": "string"},
"background": {"type": "string"}
},
"required": ["name", "occupation", "personality", "background"]
},
"minItems": 1,
}
},
"required": ["characters"]
},
}
}
response = client.chat.completions.create(
model="your-model",
messages=messages,
response_format=character_schema,
)
results = json.loads(response.choices[0].message.content)
print(json.dumps(results, indent=2))
重要提示:并非所有模型都能够进行结构化输出,特别是参数低于 7B 的 LLM。
如果您不确定模型是否支持结构化输出,请查看模型卡 README。
结构化输出引擎
- 对于
GGUF
模型:利用 llama.cpp
的基于语法的采样 API。
- 对于
MLX
模型:使用 Outlines。
MLX 实现可在 Github 上找到:lmstudio-ai/mlx-engine。
在 LM Studio Discord 服务器上与其他 LM Studio 用户聊天,讨论 LLM、硬件等。