嵌入(Embeddings)将文本转换为数值向量,您可以将其存储在向量数据库中、使用余弦相似度进行搜索,或用于 RAG 流水线。向量长度取决于模型(通常为 384–1024 维)。
推荐模型
生成嵌入
CLI
直接从命令行生成嵌入:
shell
ollama run embeddinggemma "Hello world"您还可以通过管道传递文本来生成嵌入:
shell
echo "Hello world" | ollama run embeddinggemma输出为 JSON 数组。
cURL
shell
curl -X POST http://localhost:11434/api/embed \
-H "Content-Type: application/json" \
-d '{
"model": "embeddinggemma",
"input": "The quick brown fox jumps over the lazy dog."
}'Python
python
import ollama
single = ollama.embed(
model='embeddinggemma',
input='The quick brown fox jumps over the lazy dog.'
)
print(len(single['embeddings'][0])) # vector lengthJavaScript
javascript
import ollama from 'ollama'
const single = await ollama.embed({
model: 'embeddinggemma',
input: 'The quick brown fox jumps over the lazy dog.',
})
console.log(single.embeddings[0].length) // vector length注意
/api/embed 端点返回经过 L2 归一化(单位长度)的向量。
生成批量嵌入
将字符串数组传递给 input。
cURL
shell
curl -X POST http://localhost:11434/api/embed \
-H "Content-Type: application/json" \
-d '{
"model": "embeddinggemma",
"input": [
"First sentence",
"Second sentence",
"Third sentence"
]
}'Python
python
import ollama
batch = ollama.embed(
model='embeddinggemma',
input=[
'The quick brown fox jumps over the lazy dog.',
'The five boxing wizards jump quickly.',
'Jackdaws love my big sphinx of quartz.',
]
)
print(len(batch['embeddings'])) # number of vectorsJavaScript
javascript
import ollama from 'ollama'
const batch = await ollama.embed({
model: 'embeddinggemma',
input: [
'The quick brown fox jumps over the lazy dog.',
'The five boxing wizards jump quickly.',
'Jackdaws love my big sphinx of quartz.',
],
})
console.log(batch.embeddings.length) // number of vectors提示
- 在大多数语义搜索场景中使用余弦相似度。
- 在索引和查询时使用相同的嵌入模型。