文档
基础知识
文本补全
为模型提供字符串输入以完成文本
使用 llm.complete(...)
从已加载的语言模型生成文本补全。文本补全意味着向模型发送未格式化的字符串,期望模型完成文本。
这与多轮聊天对话不同。有关聊天补全的更多信息,请参阅聊天补全。
首先,您需要加载一个模型来生成补全。这可以使用顶级 llm
便捷 API 完成,或者在使用作用域资源 API 时,使用 llm
命名空间中的 model
方法。例如,以下是如何使用 Qwen2.5 7B Instruct。
import lmstudio as lms
model = lms.llm("qwen2.5-7b-instruct")
加载模型后,您可以通过将字符串传递给 llm
句柄上的 complete
方法来生成补全。
# The `chat` object is created in the previous step.
result = model.complete("My name is", config={"maxTokens": 100})
print(result)
您还可以打印预测元数据,例如用于生成的模型、生成的标记数量、第一个标记的时间以及停止原因。
# `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()
方法,该方法在内部处理迭代流直到完成,然后返回结果。
以下是您如何使用 complete
方法模拟终端的示例。
import lmstudio as lms
model = lms.llm()
console_history = []
while True:
try:
user_command = input("$ ")
except EOFError:
print()
break
if user_command.strip() == "exit":
break
console_history.append(f"$ {user_command}")
history_prompt = "\n".join(console_history)
prediction_stream = model.complete_stream(
history_prompt,
config={ "stopStrings": ["$"] },
)
for fragment in prediction_stream:
print(fragment.content, end="", flush=True)
print()
console_history.append(prediction_stream.result().content)
您可以通过 .complete()
上的 config
关键字参数传入推理参数。
result = model.complete(initial_text, config={
"temperature": 0.6,
"maxTokens": 50,
})
有关可配置项的更多信息,请参阅配置模型。
长提示通常需要很长时间才能生成第一个 token,即模型需要很长时间来处理您的提示。如果您想获取此过程的进度更新,您可以向 complete
提供一个浮点回调,该回调接收一个从 0.0-1.0 的浮点数,表示提示处理进度。
import lmstudio as lms
llm = lms.llm()
completion = llm.complete(
"My name is",
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
:在预测完成后,使用助手响应消息调用。旨在将接收到的消息附加到聊天历史实例中。此页面源代码可在 GitHub 上获取