Cohere
Cohere 的內嵌模型用來產生文字內嵌,也就是捕捉文字語意資訊的浮點數字清單。這些嵌入資料可用於文字分類和語意搜尋等任務。
Milvus 使用CohereEmbeddingFunction
類與 Cohere 的嵌入模型整合。這個類別處理嵌入的計算,並將它們以與 Milvus 相容的格式傳回,以便進行索引和搜尋。
要使用此功能,請安裝必要的相依性:
pip install --upgrade pymilvus
pip install "pymilvus[model]"
然後,實體化CohereEmbeddingFunction
:
from pymilvus.model.dense import CohereEmbeddingFunction
cohere_ef = CohereEmbeddingFunction(
model_name="embed-english-light-v3.0",
api_key="YOUR_COHERE_API_KEY",
input_type="search_document",
embedding_types=["float"]
)
參數:
model_name
(字串)用於編碼的 Cohere 嵌入模型名稱。您可以指定任何可用的 Cohere 嵌入模型名稱,例如
embed-english-v3.0
,embed-multilingual-v3.0
等。如果不指定此參數,則會使用embed-english-light-v3.0
。如需可用模型的清單,請參閱Embed。api_key
(字串)存取 Cohere API 的 API 金鑰。
input_type
(字串)傳送到模型的輸入類型。嵌入模型 v3 及更高版本必須使用。
"search_document"
:用於儲存在向量資料庫中的嵌入,用於搜索用例。"search_query"
:用於對向量資料庫執行搜尋查詢的嵌入,以尋找相關文件。"classification"
:用於通過文字分類器的嵌入。"clustering"
:用於通過聚類演算法運行的嵌入。
embedding_types
(List[str])您想要獲取的嵌入式資料類型。非必要,預設為 None,會返回 Embed Floats 回應類型。目前,您只能指定此參數的單一值。可能的值:
"float"
:當您想要回傳預設的浮動嵌入時,請使用此值。對所有模型都有效。"binary"
:當您想要取回有符號的二進位內嵌時,請使用此項。僅對 v3 模型有效。"ubinary"
:當您想要取回無符號的二進位嵌入時,請使用此項。僅對 v3 模型有效。
要為文件建立嵌入式資料,請使用encode_documents()
方法:
docs = [
"Artificial intelligence was founded as an academic discipline in 1956.",
"Alan Turing was the first person to conduct substantial research in AI.",
"Born in Maida Vale, London, Turing was raised in southern England.",
]
docs_embeddings = cohere_ef.encode_documents(docs)
# Print embeddings
print("Embeddings:", docs_embeddings)
# Print dimension and shape of embeddings
print("Dim:", cohere_ef.dim, docs_embeddings[0].shape)
預期的輸出與以下相似:
Embeddings: [array([ 3.43322754e-02, 1.16252899e-03, -5.25207520e-02, 1.32846832e-03,
-6.80541992e-02, 6.10961914e-02, -7.06176758e-02, 1.48925781e-01,
1.54174805e-01, 1.98516846e-02, 2.43835449e-02, 3.55224609e-02,
1.82952881e-02, 7.57446289e-02, -2.40783691e-02, 4.40063477e-02,
...
0.06359863, -0.01971436, -0.02253723, 0.00354195, 0.00222015,
0.00184727, 0.03408813, -0.00777817, 0.04919434, 0.01519775,
-0.02862549, 0.04760742, -0.07891846, 0.0124054 ], dtype=float32)]
Dim: 384 (384,)
若要為查詢建立嵌入式資料,請使用encode_queries()
方法:
queries = ["When was artificial intelligence founded",
"Where was Alan Turing born?"]
query_embeddings = cohere_ef.encode_queries(queries)
print("Embeddings:", query_embeddings)
print("Dim", cohere_ef.dim, query_embeddings[0].shape)
預期輸出與下列內容相似:
Embeddings: [array([-1.33361816e-02, 9.79423523e-04, -7.28759766e-02, -1.93786621e-02,
-9.71679688e-02, 4.34875488e-02, -9.81445312e-02, 1.16882324e-01,
5.89904785e-02, -4.19921875e-02, 4.95910645e-02, 5.83496094e-02,
3.47595215e-02, -5.87463379e-03, -7.30514526e-03, 2.92816162e-02,
...
0.00749969, -0.01192474, 0.02719116, 0.03347778, 0.07696533,
0.01409149, 0.00964355, -0.01681519, -0.0073204 , 0.00043154,
-0.04577637, 0.03591919, -0.02807617, -0.04812622], dtype=float32)]
Dim 384 (384,)