文档

基础知识

聊天补全

用于与大型语言模型 (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()

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 上获取