LM StudioLM Studio

文本补全

为模型提供字符串输入以完成文本

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

示例:让LLM模拟终端

这是一个如何使用 complete 方法模拟终端的示例。

terminal-sim.py
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:在预测完成后,用助手响应消息调用。旨在将接收到的消息附加到聊天历史实例中。
© . This site is unofficial and not affiliated with Element Labs, Inc.