文档
模型信息
获取上下文长度
获取模型最大上下文长度的 API。
LLM 和嵌入模型由于其基本架构,具有一个称为上下文长度
的属性,更具体地说是最大上下文长度。粗略地说,这是模型在生成文本或嵌入时可以“记住”的令牌数量。超过此限制将导致模型行为异常。
getContextLength()
函数能够检查模型的上下文长度很有用,尤其是在向模型提供可能很长的输入之前作为额外的检查。
const contextLength = await model.getContextLength();
上述代码片段中的model
是您从llm.model
方法获取的已加载模型实例。有关更多信息,请参阅内存中的模型管理。
您可以通过以下方式确定给定的对话是否符合模型的上下文:
import { Chat, type LLM, LMStudioClient } from "@lmstudio/sdk";
async function doesChatFitInContext(model: LLM, chat: Chat) {
// Convert the conversation to a string using the prompt template.
const formatted = await model.applyPromptTemplate(chat);
// Count the number of tokens in the string.
const tokenCount = await model.countTokens(formatted);
// Get the current loaded context length of the model
const contextLength = await model.getContextLength();
return tokenCount < contextLength;
}
const client = new LMStudioClient();
const model = await client.llm.model();
const chat = Chat.from([
{ role: "user", content: "What is the meaning of life." },
{ role: "assistant", content: "The meaning of life is..." },
// ... More messages
]);
console.info("Fits in context:", await doesChatFitInContext(model, chat));
此页面的源代码可在GitHub上获取