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