跳到主要内容

向量与重排序

在你自己的文档里做搜索,通常分两步:用向量找出和问题相近的段落,再用重排序把最好的排到前面。下面两个示例都是真实的文件,发布前我们都会实际运行一遍。

向量​

# Embeddings for search and retrieval.
curl -sS "${OCEANTOKEN_BASE_URL:-https://api.oceantoken.ai/v1}/embeddings" \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "baai/bge-m3",
"input": "The lighthouse keeper rowed out before dawn."
}'

POST /v1/embeddings 遵循 OpenAI 的 Embeddings API,所以 client.embeddings.create() 改一下基础地址就能用。

字段作用
model向量模型的 ID。
input一个字符串,或一次请求里要处理的字符串列表。
dimensions更短的向量,适用于提供这个选项的模型,比如 openai/text-embedding-3-small。
encoding_formatfloat(默认)或 base64,适用于提供这个选项的模型。

返回内容中每个输入对应一个向量,顺序不变,放在 data[].embedding 里,另有 usage.prompt_tokens。

  • 批量发送:一个请求带一组输入,比每段文字发一个请求更快、更简单。
  • 文档和用来搜索的问题要用同一个模型。不同模型的向量不能互相比较。
  • 向量按输入 token 计费。
response = client.embeddings.create(
model="openai/text-embedding-3-small",
input=["退款需要 10 天。", "发货需要 3 天。"],
)
vectors = [item.embedding for item in response.data]

重排序​

# Rerank: order documents by how well they answer the query. Cohere's request
# shape; the answer lists each document's index with its relevance score.
curl -sS --fail-with-body "${OCEANTOKEN_BASE_URL:-https://api.oceantoken.ai/v1}/rerank" \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "cohere/rerank-v3.5",
"query": "How long do refunds take?",
"documents": [
"Shipping takes three to five working days.",
"Refunds reach your card within 10 days of the return arriving.",
"Gift cards cannot be exchanged for cash."
],
"top_n": 2
}'

POST /v1/rerank 遵循 Cohere 的重排序请求:model(重排序模型的 ID)、query、documents(字符串列表),以及可选的 top_n(返回几条)。返回内容按相关程度从高到低列出文档:

{
"results": [
{"index": 1, "relevance_score": 0.92},
{"index": 0, "relevance_score": 0.08}
],
"meta": {"billed_units": {"search_units": 1}}
}

index 是文档在你的列表中的位置。重排序按搜索单位计费,数量见 meta.billed_units.search_units(计费方式)。

下一步​