文档
入门
项目设置
设置您的 lmstudio-python
应用程序或脚本。
lmstudio
是一个在 PyPI 上发布的库,它允许您在自己的项目中使用 lmstudio-python
。它是开源的,并在 GitHub 上开发。您可以在此处找到源代码。
lmstudio-python
由于它已发布到 PyPI,lmstudio-python
可以使用 pip
或您首选的项目依赖管理器(显示了 pdm
和 uv
,但其他 Python 项目管理工具也提供类似的依赖添加命令)进行安装。
pip install lmstudio
文档中的所有示例都假设服务器 API 在本地运行于默认应用程序端口之一(注意:在 Python SDK 1.5.0 版本之前,SDK 还要求启用可选的 HTTP REST 服务器)。
可以通过在创建客户端实例时传递 "host:port"
字符串来覆盖服务器 API 的网络位置。
import lmstudio as lms
SERVER_API_HOST = "localhost:1234"
# This must be the *first* convenience API interaction (otherwise the SDK
# implicitly creates a client that accesses the default server API host)
lms.configure_default_client(SERVER_API_HOST)
# Note: the dedicated configuration API was added in lmstudio-python 1.3.0
# For compatibility with earlier SDK versions, it is still possible to use
# lms.get_default_client(SERVER_API_HOST) to configure the default client
所需 Python SDK 版本:1.5.0
虽然最常见的连接模式是让 SDK 在无法连接到指定 API 服务器主机时引发异常,但 SDK 也支持直接运行 API 检查,而无需先创建 SDK 客户端实例。
import lmstudio as lms
SERVER_API_HOST = "localhost:1234"
if lms.Client.is_valid_api_host(SERVER_API_HOST):
print(f"An LM Studio API server instance is available at {SERVER_API_HOST}")
else:
print("No LM Studio API server instance found at {SERVER_API_HOST}")
所需 Python SDK 版本:1.5.0
当未指定 API 服务器主机时,SDK 会在本地回环接口上查询多个端口以查找正在运行的 API 服务器实例。每次创建新的客户端实例时都会重复此扫描。SDK 也支持显式运行此扫描,并在创建客户端时传入报告的 API 服务器详细信息,而不是让 SDK 隐式执行此扫描。
import lmstudio as lms
api_host = lms.Client.find_default_local_api_host()
if api_host is not None:
print(f"An LM Studio API server instance is available at {api_host}")
else:
print("No LM Studio API server instance found on any of the default local ports")
此页面的源代码可在 GitHub 上获取