ドキュメンテーション
エージェントフロー
テキスト埋め込み
トークン化
モデルの管理
モデル情報
APIリファレンス
エージェントフロー
テキスト埋め込み
トークン化
モデルの管理
モデル情報
APIリファレンス
チャット補完
チャットの会話に対する補完を生成するには、llm.respond(...)
を使用します。
以下のスニペットは、AIの応答をクイックチャットプロンプトにストリーミングする方法を示しています。
import { LMStudioClient } from "@lmstudio/sdk";
const client = new LMStudioClient();
const model = await client.llm.model();
for await (const fragment of model.respond("What is the meaning of life?")) {
process.stdout.write(fragment.content);
}
まず、モデルハンドルを取得する必要があります。これは、llm
名前空間のmodel
メソッドを使用して行えます。例えば、Qwen2.5 7B Instructの使用方法は以下の通りです。
import { LMStudioClient } from "@lmstudio/sdk";
const client = new LMStudioClient();
const model = await client.llm.model("qwen2.5-7b-instruct");
モデルハンドルを取得する方法は他にもあります。詳細については、メモリ内のモデル管理を参照してください。
モデルへの入力は「コンテキスト」と呼ばれます。概念的には、モデルは複数ターンの会話を入力として受け取り、その会話におけるアシスタントの応答を予測するよう求められます。
import { Chat } from "@lmstudio/sdk";
// Create a chat object from an array of messages.
const chat = Chat.from([
{ role: "system", content: "You are a resident AI philosopher." },
{ role: "user", content: "What is the meaning of life?" },
]);
チャットコンテキストの管理に関する詳細については、チャットの操作を参照してください。
respond()
メソッドを使用して、チャットコンテキストにおける次の応答をLLMに予測させることができます。
// The `chat` object is created in the previous step.
const prediction = model.respond(chat);
for await (const { content } of prediction) {
process.stdout.write(content);
}
console.info(); // Write a new line to prevent text from being overwritten by your shell.
推論パラメータは、.respond()
の第2パラメータとして渡すことができます。
const prediction = model.respond(chat, {
temperature: 0.6,
maxTokens: 50,
});
設定可能な項目に関する詳細については、モデルの設定を参照してください。
生成に使用されたモデル、生成されたトークン数、最初のトークンまでの時間、停止理由など、予測のメタデータも表示できます。
// If you have already iterated through the prediction fragments,
// doing this will not result in extra waiting.
const result = await prediction.result();
console.info("Model used:", result.modelInfo.displayName);
console.info("Predicted tokens:", result.stats.predictedTokensCount);
console.info("Time to first token (seconds):", result.stats.timeToFirstTokenSec);
console.info("Stop reason:", result.stats.stopReason);
TODO: ここは修正が必要かもしれません
import { Chat, LMStudioClient } from "@lmstudio/sdk";
import { createInterface } from "readline/promises";
const rl = createInterface({ input: process.stdin, output: process.stdout });
const client = new LMStudioClient();
const model = await client.llm.model();
const chat = Chat.empty();
while (true) {
const input = await rl.question("You: ");
// Append the user input to the chat
chat.append("user", input);
const prediction = model.respond(chat, {
// When the model finish the entire message, push it to the chat
onMessage: (message) => chat.append(message),
});
process.stdout.write("Bot: ");
for await (const { content } of prediction) {
process.stdout.write(content);
}
process.stdout.write("\n");
}
このページの内容
クイック例: チャット応答の生成
モデルの取得
チャットコンテキストの管理
応答の生成
推論パラメータのカスタマイズ
予測統計の表示
例: 複数ターンチャット