文档
模型使用分词器在内部将文本转换为它们能更轻松处理的“标记”(tokens)。LM Studio 提供了此分词器以供实用。
您可以使用 SDK 对已加载的 LLM 或嵌入模型进行字符串分词。在下面的示例中,LLM 引用可以替换为嵌入模型引用,而无需进行任何其他更改。
import lmstudio as lms
model = lms.llm()
tokens = model.tokenize("Hello, world!")
print(tokens) # Array of token IDs.
如果您只关心标记的数量,只需检查结果数组的长度即可。
token_count = len(model.tokenize("Hello, world!"))
print("Token count:", token_count)
您可以通过以下方式确定给定的对话是否符合模型的上下文:
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 上找到