文档
取消预测
有时您可能希望在预测完成之前停止它。例如,用户可能会改变主意,或者您的界面可能会导航到其他页面。lmstudio-js
提供了两种简单的方法来取消正在进行的预测。
.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"
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"
这两种方法都会立即停止生成,并且返回的统计数据表明预测因您的停止而结束。
本页内容
1. 在预测上调用 .cancel()
2. 使用 AbortController