文档

快速开始

代理流程

文本嵌入

分词

管理模型

模型信息

聊天补全

使用 llm.respond(...) 为聊天对话生成补全内容。

快速示例:生成聊天响应

以下代码片段展示了如何获取 AI 对快速聊天提示的响应。

import lmstudio as lms
model = lms.llm()
print(model.respond("What is the meaning of life?"))

流式传输聊天响应

以下代码片段展示了如何将 AI 对聊天提示的响应进行流式传输,在接收到文本片段时即时显示(而不是等待生成完整响应后才显示)。

import lmstudio as lms
model = lms.llm()

for fragment in model.respond_stream("What is the meaning of life?"):
    print(fragment.content, end="", flush=True)
print() # Advance to a new line at the end of the response

取消聊天响应

有关如何取消正在进行的预测,请参阅取消预测部分。

获取模型

首先,您需要获取一个模型句柄。这可以通过使用顶层llm便捷 API,或在使用作用域资源 API 时通过llm命名空间中的model方法来完成。例如,以下是如何使用 Qwen2.5 7B Instruct。

import lmstudio as lms
model = lms.llm("qwen2.5-7b-instruct")

还有其他获取模型句柄的方法。更多信息请参阅管理内存中的模型

管理聊天上下文

模型的输入被称为“上下文”。从概念上讲,模型接收一个多轮对话作为输入,并被要求预测助手在该对话中的响应。

import lmstudio as lms

# Create a chat with an initial system prompt.
chat = lms.Chat("You are a resident AI philosopher.")

# Build the chat context by adding messages of relevant types.
chat.add_user_message("What is the meaning of life?")
# ... continued in next example

有关管理聊天上下文的更多信息,请参阅使用聊天功能

生成响应

您可以使用respond()方法让 LLM 预测聊天上下文中的下一个响应。

# The `chat` object is created in the previous step.
result = model.respond(chat)

print(result)

自定义推理参数

您可以通过.respond()方法上的config关键字参数传入推理参数。

prediction_stream = model.respond_stream(chat, config={
    "temperature": 0.6,
    "maxTokens": 50,
})

有关可配置内容的更多信息,请参阅配置模型

您还可以打印预测元数据,例如用于生成的模型、生成的标记数量、首个标记的时间以及停止原因。

# After iterating through the prediction fragments,
# the overall prediction result may be obtained from the stream
result = prediction_stream.result()

print("Model used:", result.model_info.display_name)
print("Predicted tokens:", result.stats.predicted_tokens_count)
print("Time to first token (seconds):", result.stats.time_to_first_token_sec)
print("Stop reason:", result.stats.stop_reason)

示例:多轮聊天

import lmstudio as lms

model = lms.llm()
chat = lms.Chat("You are a task focused AI assistant")

while True:
    try:
        user_input = input("You (leave blank to exit): ")
    except EOFError:
        print()
        break
    if not user_input:
        break
    chat.add_user_message(user_input)
    prediction_stream = model.respond_stream(
        chat,
        on_message=chat.append,
    )
    print("Bot: ", end="", flush=True)
    for fragment in prediction_stream:
        print(fragment.content, end="", flush=True)
    print()

进度回调

较长的提示通常需要很长时间才能生成第一个标记,即模型处理您的提示需要很长时间。如果您想获取此过程的进度更新,可以向respond提供一个浮点回调,该回调接收一个 0.0-1.0 之间的浮点数,表示提示处理进度。

import lmstudio as lms

llm = lms.llm()

response = llm.respond(
    "What is LM Studio?",
    on_prompt_processing_progress = (lambda progress: print(f"{progress*100}% complete")),
)

除了on_prompt_processing_progress之外,其他可用的进度回调包括:

  • on_first_token:在提示处理完成且第一个标记被发出后调用。不接收任何参数(使用流迭代 API 或on_prediction_fragment以在标记发出时对其进行处理)。
  • on_prediction_fragment:为客户端接收到的每个预测片段调用。接收的预测片段与通过流迭代 API 迭代时相同。
  • on_message:当预测完成时,会随助手响应消息一起调用。旨在将接收到的消息附加到聊天历史实例中。