LM StudioLM Studio

对话补全

用于与 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() 方法,该方法在内部处理迭代流直到完成,然后返回结果。

示例:多轮对话

chatbot.py
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()

进度回调

长提示通常需要很长时间才能输出第一个 token,也就是说模型处理您的提示需要很长时间。如果您想获取此过程的进度更新,可以向 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:在提示处理完成并开始输出第一个 token 后调用。不接收任何参数(使用流式迭代 API 或 on_prediction_fragment 在输出 token 时进行处理)。
  • on_prediction_fragment:每当客户端收到预测片段时调用。接收与迭代流式 API 相同的预测片段。
  • on_message:预测完成时,以助手的响应消息作为参数调用。旨在将收到的消息追加到对话历史实例中。
© . This site is unofficial and not affiliated with Element Labs, Inc.