资讯动态

使用 OpenAI 服务通过 Inference API 实现语义搜索

发布时间:2026/8/4 5:42:13 来源:尧图企业网站定制
了解如何使用 OpenAI 服务通过 Inference API 实现语义搜索。在本示例中你需要准备一个 Elastic 部署本示例将使用 Elastic Cloud提供免费试用。Elasticsearch 8.12 或更高版本。你也可以参考文章 “如何在 LinuxMacOS 及 Windows 上进行安装 Elasticsearch” 创建一个本地部署的 Elasticsearch 集群使用 OpenAI 服务的 Inference API 需要一个付费的 OpenAI 账户因为 OpenAI 免费试用提供的 API 使用额度有限。注意你可以使用任何一个服务提供商所提供的 inference API。在本文章里我们使用默认的 E5 多语言嵌入模型来进行展示。如果你还没有 Elastic Cloud 部署可以在这里注册免费试用。开始之前我们需要使用 Python 客户端8.12.0 或更高版本连接到我们的 Elastic 部署。由于我们使用的是 Elastic Cloud 部署因此将使用 Cloud ID 来标识该部署。参考代码https://github.com/liu-xiao-guo/elastic_multimodal_search如果你想是如下的代码工作于 .multilingual-e5-small 模型你可以参考代码 https://github.com/liu-xiao-guo/search_inference首先我们需要使用pip安装以下软件包elasticsearch!pip install elasticsearch接下来我们需要导入所需的模块。 注意getpass使我们能够安全地提示用户输入凭据而不会将输入内容回显到终端也不会将其存储在内存中。from elasticsearch import Elasticsearch, helpers, exceptions from urllib.request import urlopen from getpass import getpass import json import time现在我们可以实例化 Python Elasticsearch 客户端。首先提示用户输入密码和 Cloud ID。然后创建一个客户端对象以实例化Elasticsearch类的一个实例。# https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#finding-your-cloud-id ELASTIC_CLOUD_ID getpass(Elastic Cloud ID: ) # https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#creating-an-api-key ELASTIC_API_KEY getpass(Elastic Api Key: ) # Create the client instance client Elasticsearch( # For local development # hosts[http://localhost:9200] cloud_idELASTIC_CLOUD_ID, api_keyELASTIC_API_KEY, )启用遥测了解你正在使用此 Notebook有助于我们决定将精力投入到哪些方面来改进我们的产品。我们希望你运行以下代码以便我们收集匿名使用统计信息。有关详细信息请参阅telemetry.py。谢谢!curl -O -s https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/telemetry/telemetry.py from telemetry import enable_telemetry client enable_telemetry(client, 07-inference)测试客户端在继续之前请通过此测试确认客户端已成功连接。print(client.info())请参阅文档了解如何连接到自托管部署。阅读此页面了解如何使用 API Key 进行连接。创建推理端点下面我们将使用Create inference API创建推理端点。为此你需要一个 OpenAI API Key。你可以在 OpenAI 账户中的API keys 页面找到它。完成本 Notebook 中的步骤需要一个付费的 OpenAI 会员因为 OpenAI 免费试用提供的 API 使用额度有限。API_KEY getpass(OpenAI API key: ) client.inference.put( task_typetext_embedding, inference_idmy_openai_embedding_model, body{ service: openai, service_settings: {api_key: API_KEY}, task_settings: {model: text-embedding-ada-002}, }, )注意如果你使用的是 Elasticsearch 8.12则必须将上述代码片段中的inference_id修改为model_id同时将inference.put修改为inference.put_model。创建包含推理处理器的 Ingest Pipeline使用put_pipeline方法创建一个包含推理处理器 inference processor 的 Ingest Pipeline。在model_id中引用上面创建的推理端点以便在数据通过该 Pipeline 导入时对数据执行推理。client.ingest.put_pipeline( idopenai_embeddings_pipeline, descriptionIngest pipeline for OpenAI inference., processors[ { inference: { model_id: my_openai_embedding_model, input_output: { input_field: plot, output_field: plot_embedding, }, } } ], )下面说明该 API 调用中的几个重要参数inference使用机器学习模型执行推理的处理器。model_id指定要使用的推理端点 ID。在本示例中推理 ID 设置为my_openai_embedding_model。请使用你在创建推理任务时定义的推理 ID。input_output指定输入字段和输出字段。input_field用于生成dense_vector表示的字段名称。output_field包含推理结果的字段名称。创建索引需要先创建目标索引即存储模型根据输入文本生成的向量嵌入的索引的映射。目标索引必须包含一个dense_vector类型的字段用于索引 OpenAI 模型生成的输出。下面我们创建一个名为openai-movie-embeddings的索引并配置所需的映射。client.indices.delete(indexopenai-movie-embeddings, ignore_unavailableTrue) client.indices.create( indexopenai-movie-embeddings, settings{index: {default_pipeline: openai_embeddings_pipeline}}, mappings{ properties: { plot_embedding: { type: dense_vector, dims: 1536, similarity: dot_product, }, plot: {type: text}, } }, )插入文档下面插入包含 12 部电影的示例数据集。完成此步骤需要一个付费的 OpenAI 账户否则由于 OpenAI API 请求速率限制文档导入过程将会超时。url https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/notebooks/search/movies.json response urlopen(url) # Load the response data into a JSON object data_json json.loads(response.read()) # Prepare the documents to be indexed documents [] for doc in data_json: documents.append( { _index: openai-movie-embeddings, _source: doc, } ) # Use helpers.bulk to index helpers.bulk(client, documents) print(Done indexing documents into openai-movie-embeddings index!) time.sleep(3)语义搜索在数据集通过嵌入向量完成增强后你可以使用语义搜索查询数据。向 k 近邻kNN向量搜索 API 传递query_vector_builder并提供查询文本以及用于创建嵌入向量的模型。response client.search( indexopenai-movie-embeddings, size3, knn{ field: plot_embedding, query_vector_builder: { text_embedding: { model_id: my_openai_embedding_model, model_text: Fighting movie, } }, k: 10, num_candidates: 100, }, ) for hit in response[hits][hits]: doc_id hit[_id] score hit[_score] title hit[_source][title] plot hit[_source][plot] print(fScore: {score}\nTitle: {title}\nPlot: {plot}\n)得分0.91674197标题搏击俱乐部剧情一个失眠的办公室职员和一个我行我素的肥皂制造商创建了一个地下搏击俱乐部并逐渐发展成一个更加复杂、影响深远的组织。得分0.9069592标题低俗小说剧情两个黑帮杀手、一个拳击手、一个黑帮老大及其妻子以及一对餐馆抢劫犯的生活在四个充满暴力与救赎的故事中交织在一起。得分0.8992071标题黑暗骑士剧情当被称为小丑的恶势力在哥谭市制造混乱和灾难时蝙蝠侠必须接受自己对抗不公能力的一次重大心理和身体考验。注意query_vector_builder中model_id的值必须与第一步中创建的inference_id的值匹配。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价