文档
聊天补全
使用 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);
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");
}
本页内容
快速示例:生成聊天响应
获取模型
管理聊天上下文
生成响应
自定义推理参数
打印预测统计信息
示例:多轮聊天