文档

DashScopeEmbedding

更新时间:
一键部署

本文档介绍使用DashScopeEmbedding服务来在Llama Index中构建向量索引服务的使用方法。

开始

前提条件

pip install llama-index-core
pip install llama-index-embeddings-dashscope

示例代码

以下示例展示了在Llama-Index中调用DashscopeEmbedding服务

说明

需要使用您的API-KEY替换示例中的 YOUR_DASHSCOPE_API_KEY,代码才能正常运行。

设置API-KEY

export DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY
# imports
from llama_index.embeddings.dashscope import (
    DashScopeEmbedding,
    DashScopeTextEmbeddingModels,
    DashScopeTextEmbeddingType,
)

# Create embeddings
# text_type=`document` to build index
embedder = DashScopeEmbedding(
    model_name=DashScopeTextEmbeddingModels.TEXT_EMBEDDING_V2,
    text_type=DashScopeTextEmbeddingType.TEXT_TYPE_DOCUMENT,
)
text_to_embedding = ["风急天高猿啸哀", "渚清沙白鸟飞回", "无边落木萧萧下", "不尽长江滚滚来"]
# Call text Embedding
result_embeddings = embedder.get_text_embedding_batch(text_to_embedding)
# requests and embedding result index is correspond to.
for index, embedding in enumerate(result_embeddings):
    if (
        embedding is None
    ):  # if the the correspondence request is embedding failed.
        print("The %s embedding failed." % text_to_embedding[index])
    else:
        print("Dimension of embeddings: %s" % len(embedding))
        print(
            "Input: %s, embedding is: %s"
            % (text_to_embedding[index], embedding[:5])
        )

示例代码输出

Dimension of embeddings: 1536
Input: 风急天高猿啸哀, embedding is: [-0.0016666285653348784, 0.008690492014557004, 0.02894828715284365, -0.01774133615134858, 0.03627544697161321]
Dimension of embeddings: 1536
Input: 渚清沙白鸟飞回, embedding is: [0.018255604113922633, 0.030631669725945727, 0.0031333343045102462, 0.014323813963475412, 0.009666154862176396]
Dimension of embeddings: 1536
Input: 无边落木萧萧下, embedding is: [-0.01270165436681136, 0.011355212676752505, -0.007090375205285297, 0.008317427977013809, 0.0341982923839579]
Dimension of embeddings: 1536
Input: 不尽长江滚滚来, embedding is: [0.003449439128962428, 0.02667092110022496, -0.0010223853088419568, -0.00971414215183749, 0.0035561228133633277]

了解更多

更多内容,请参考LlamaIndex官方文档和示例: