文档
基础知识
聊天补全
用于与大型语言模型(LLM)进行多轮聊天对话的 API
使用 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
关键字参数传入推理参数。
result = model.respond(chat, config={
"temperature": 0.6,
"maxTokens": 50,
})
有关可配置项的更多信息,请参阅配置模型。
您还可以打印预测元数据,例如用于生成的模型、生成的标记数量、第一个标记的时间以及停止原因。
# `result` is the response from the model.
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)
非流式和流式结果访问在同步和异步 API 中保持一致,因为 prediction_stream.result()
是一个非阻塞 API,如果结果不可用(因为预测仍在运行,或者预测请求失败),它将引发异常。预测流还提供了一个阻塞(同步 API)或可等待(异步 API)的 prediction_stream.wait_for_result()
方法,该方法在内部处理迭代流直到完成,然后返回结果。
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
:当预测完成时,使用助手回复消息调用。旨在将接收到的消息附加到聊天历史记录实例。此页面的源代码可在 GitHub 上获取