嵌入向量(Embeddings)將文本轉換為數值向量,您可以將其存儲在向量資料庫中、使用餘弦相似度進行搜索,或在 RAG 流水線中使用。向量長度取決於模型(通常為 384–1024 維)。
推薦模型
生成嵌入向量
CLI
直接從命令列生成嵌入向量:
shell
ollama run embeddinggemma "Hello world"您也可以透過管道(pipe)傳送文本來生成嵌入向量:
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 lengthNote
提示:/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提示
- 在大多數語義搜索場景中,請使用餘弦相似度(cosine similarity)。
- 請在索引和查詢時使用相同的嵌入模型。