Docs 菜单
Docs 主页
/

分词器

给定输入,嵌入和重新排名进程的第一步是将其分割为 个词元列表。当您调用API时,我们的服务器会自动执行此分词步骤。 Python客户端包含允许您在调用API之前尝试分词器的方法。

使用 tokenize 方法对特定模型的文本列表进行分词。

例子

import voyageai
# Initialize client (uses VOYAGE_API_KEY environment variable)
vo = voyageai.Client()
texts = [
"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.",
"Photosynthesis in plants converts light energy into glucose and produces essential oxygen."
]
# Tokenize the texts
tokenized = vo.tokenize(texts, model="voyage-4-large")
for i in range(len(texts)):
print(tokenized[i].tokens)
['The', 'ĠMediterranean', 'Ġdiet', 'Ġemphasizes', 'Ġfish', ',', 'Ġolive', 'Ġoil', ',', 'Ġand', 'Ġvegetables', ',', 'Ġbelieved', 'Ġto', 'Ġreduce', 'Ġchronic', 'Ġdiseases', '.']
['Photos', 'ynthesis', 'Ġin', 'Ġplants', 'Ġconverts', 'Ġlight', 'Ġenergy', 'Ġinto', 'Ġglucose', 'Ġand', 'Ġproduces', 'Ġessential', 'Ġoxygen', '.']

使用 count_tokens 方法计算特定模型的文本列表中的词元数量。

例子

import voyageai
# Initialize client (uses VOYAGE_API_KEY environment variable)
vo = voyageai.Client()
texts = [
"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.",
"Photosynthesis in plants converts light energy into glucose and produces essential oxygen."
]
# Count total tokens
total_tokens = vo.count_tokens(texts, model="voyage-4-large")
print(total_tokens)
32

使用 count_usage 方法计算特定模型的输入列表中词元和像素的数量。

注意

Voyage 嵌入模型具有上下文长度限制。如果文本超出限制,请在调用API之前截断文本,或将truncation 参数指定为True

例子

import voyageai
import PIL
# Initialize client (uses VOYAGE_API_KEY environment variable)
vo = voyageai.Client()
# Create input with text and image
inputs = [
["This is a banana.", PIL.Image.open('banana.jpg')]
]
# Count tokens and pixels
usage = vo.count_usage(inputs, model="voyage-multimodal-3.5")
print(usage)
{'text_tokens': 5, 'image_pixels': 2000000, 'total_tokens': 3576}

使用分词器时请考虑以下事项:

  • 现代 NLP 模型通常将文本字符串转换为词元列表。 “you”和“apple”等常用词本身就是词元。相反,罕见或长的单词会被分解为多个词元,示例,“uncharacteristically”被分解为四个词元:“un”、“character”、“ist”和“ically”。一个单词平均大致对应于 1.2 到 1.5 个词元,具体取决于域的复杂性。

    我们的分词器生成的词元平均有 5 个字符,这表明您可以通过将文本字符串中的字符数除以 5 来粗略估计词元数量。要确定令牌的确切数量,请使用 count_tokens() 方法。

  • Voyage 的分词器也可在 Huging Face 上使用。您可以使用以下代码访问权限与特定模型关联的分词器:

    from transformers import AutoTokenizer
    tokenizer = AutoTokenizer.from_pretrained('voyageai/voyage-4-large')
  • tiktoken 是一个流行的开源分词器。 Voyage 模型使用不同的分词器。因此,与 tiktoken 相比,我们的分词器为给定文本生成不同的词元列表。根据统计,我们的分词器生成的词元数量平均是 tiktoken 的 1.1 到 1.2 倍。要确定令牌的确切数量,请使用 count_tokens() 方法。

后退

RAG

在此页面上