ドキュメント

エージェント的フロー

テキスト埋め込み

トークン化

モデルの管理

モデル情報

APIリファレンス

予測のキャンセル

予測が完了する前に停止したい場合があります。例えば、ユーザーが気が変わったり、UIが別のページに移動したりするケースです。lmstudio-js は、実行中の予測をキャンセルする2つの簡単な方法を提供します。

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"

どちらの方法でも生成は即座に停止し、返される統計情報には、予測がユーザーによって停止されたことが示されます。