文档

基础知识

取消预测

停止 lmstudio-js 中正在进行的预测

有时您可能希望在预测完成之前停止它。例如,用户可能会改变主意,或者您的 UI 可能会导航离开。lmstudio-js 提供了两种简单的方法来取消正在运行的预测。

1. 在预测上调用 .cancel()

每个预测方法都返回一个 OngoingPrediction 实例。调用 .cancel() 会停止生成,并导致最终的 stopReason"userStopped"。在下面的示例中,我们使用计时器安排取消调用。

import { LMStudioClient } from "@lmstudio/sdk";

const client = new LMStudioClient();
const model = await client.llm.model("qwen2.5-7b-instruct");

const prediction = model.respond("What is the meaning of life?", {
  maxTokens: 50,
});
setTimeout(() => prediction.cancel(), 1000); // cancel after 1 second

const result = await prediction.result();
console.info(result.stats.stopReason); // "userStopped"

2. 使用 AbortController

如果您的应用程序已经使用 AbortController 来传播取消,您可以将其 signal 传递给预测方法。中止控制器会以相同的 stopReason 停止预测。

import { LMStudioClient } from "@lmstudio/sdk";

const client = new LMStudioClient();
const model = await client.llm.model("qwen2.5-7b-instruct");

const controller = new AbortController();
const prediction = model.respond("What is the meaning of life?", {
  maxTokens: 50,
  signal: controller.signal,
});
setTimeout(() => controller.abort(), 1000); // cancel after 1 second

const result = await prediction.result();
console.info(result.stats.stopReason); // "userStopped"

这两种方法都会立即停止生成,并且返回的统计信息表明预测因您停止它而结束。

本页源代码可在 GitHub 上获取