ドキュメント

基本

チャット補完

LLMとのマルチターンのチャット会話のための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);

例:マルチターンのチャット

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");
}

このページのソースはGitHubで利用可能です。