文档
文本补全
使用 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)
这是一个如何使用 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
关键字参数传入推理参数。
prediction_stream = model.complete_stream(initial_text, config={
"temperature": 0.6,
"maxTokens": 50,
})
有关可配置内容的更多信息,请参阅配置模型。
长提示通常需要很长时间才能生成第一个令牌,即模型需要很长时间来处理您的提示。如果您想获取此过程的进度更新,可以向 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
:在提示处理完成并发出第一个令牌后调用。不接收任何参数(使用流式迭代 API 或 on_prediction_fragment
来处理发出的令牌)。on_prediction_fragment
:针对客户端接收的每个预测片段调用。接收与流式迭代 API 迭代相同的预测片段。on_message
:当预测完成时,使用助手响应消息调用。旨在将接收到的消息追加到聊天历史实例中。本页内容
1. 实例化模型
2. 生成补全
3. 打印预测统计信息
示例:让 LLM 模拟终端
自定义推理参数
进度回调