ドキュメンテーション

チャット補完

チャットの会話に対する補完を生成するには、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");
}