文档
使用 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 上获取