快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索

本文主要是介绍快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Gemini 是 Google DeepMind 开发的多模态大语言模型家族,作为 LaMDA 和 PaLM 2 的后继者。由 Gemini Ultra、Gemini Pro 和 Gemini Nano 组成,于 2023 年 12 月 6 日发布,定位为 OpenAI 的竞争者 GPT-4。

本教程演示如何使用 Gemini API 创建嵌入并将其存储在 Elasticsearch 中。 Elasticsearch 将使我们能够执行向量搜索 (Knn) 来查找相似的文档。

准备

Elasticsearch 及 Kibana

如果你还没有安装好自己的 Elasticsearch 及 Kibana 的话,请参阅如下的文章来进行安装:

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch

  • Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kibana

在安装的时候,请参照 Elastic Stack 8.x 的文章来进行安装。

Gemini 开发者 key

你可以参考文章 来申请一个免费的 key 供下面的开发。你也可以直接去地址进行申请。

设置环境变量

我们在 termnial 中打入如下的命令来设置环境变量:

export ES_USER=elastic
export ES_PASSWORD=-M3aD_m3MHCZNYyJi_V2
export GOOGLE_API_KEY=YourGoogleAPIkey

拷贝 Elasticsearch 证书

我们把 Elasticsearch 的证书拷贝到当前的目录下:

$ pwd
/Users/liuxg/python/elser
$ cp ~/elastic/elasticsearch-8.12.0/config/certs/http_ca.crt .

安装 Python 依赖包

pip3 install -q -U google-generativeai elasticsearch

应用设计

我们在当前的工作目录下打入命令:

jupyter notebook

导入包及环境变量

import google.generativeai as genai
import google.ai.generativelanguage as glm
from elasticsearch import Elasticsearch, helpers
from dotenv import load_dotenv
import osload_dotenv()GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
ES_USER = os.getenv("ES_USER")
ES_PASSWORD = os.getenv("ES_PASSWORD")
elastic_index_name='gemini-demo'

 连接到 Elasticsearch

url = f"https://{ES_USER}:{ES_PASSWORD}@192.168.0.3:9200"es = Elasticsearch(hosts=[url], ca_certs = "./http_ca.crt", verify_certs = True
)
print(es.info())

上面显示我们的 es 连接是成功的。

删除索引

if(es.indices.exists(index=elastic_index_name)):print("The index has already existed, going to remove it")es.options(ignore_status=404).indices.delete(index=elastic_index_name)

使用 Elasticsearch 索引文档

生成一个 title 为 “Beijing” 文档:

genai.configure(api_key=GOOGLE_API_KEY)title = "Beijing"
sample_text = ("Beijing is the capital of China and the center of Chinese politics, culture, and economy. This city has a long history with many ancient buildings and cultural heritage. Beijing is renowned as a cultural city in China, boasting numerous museums, art galleries, and historical landmarks. Additionally, as a modern metropolis, Beijing is a thriving business center with modern architecture and advanced transportation systems. It serves as the seat of the Chinese government, where significant decisions and events often take place. Overall, Beijing holds a crucial position in China, serving as both a preserver of traditional culture and a representative of modern development.")model = 'models/embedding-001'
embedding = genai.embed_content(model=model,content=sample_text,task_type="retrieval_document",title=title)doc = {'text' : sample_text,'text_embedding' : embedding['embedding'] 
}resp = es.index(index=elastic_index_name, document=doc)print(resp)

生成一个 title 为 “Shanghai” 的文档:

title = "Shanghai"
sample_text = ("Shanghai is one of China's largest cities and a significant hub for economy, finance, and trade. This modern city is located in the eastern part of China and serves as an international metropolis. The bustling streets, skyscrapers, and modern architecture in Shanghai showcase the city's prosperity and development. As one of China's economic engines, Shanghai is home to the headquarters of many international companies and various financial institutions. It is also a crucial trading port, connecting with destinations worldwide. Additionally, Shanghai boasts a rich cultural scene, including art galleries, theaters, and historical landmarks. In summary, Shanghai is a vibrant, modern city with international influence.")model = 'models/embedding-001'
embedding = genai.embed_content(model=model,content=sample_text,task_type="retrieval_document",title=title)doc = {'text' : sample_text,'text_embedding' : embedding['embedding'] 
}resp = es.index(index=elastic_index_name, document=doc)print(resp)

我们可以在 Kibana 中进行查看:

使用 Elasticsearch 来搜索文档

def search(question):print("\n\nQuestion: ", question)embedding = genai.embed_content(model=model,content=question,task_type="retrieval_query")resp = es.search(index = elastic_index_name,knn={"field": "text_embedding","query_vector":  embedding['embedding'],"k": 10,"num_candidates": 100})for result in resp['hits']['hits']:pretty_output = (f"\n\nID: {result['_id']}\n\nText: {result['_source']['text']}")print(pretty_output)
search("How do you describe Beijing?")

search("What is Shanghai like?")

从上面的输出中,我们可以看出来,当搜索的句子和文章更为接近时,相关的文档就会排在第一的位置。紧接着的是次之相关的文档。

search("which city is the capital of China?")

search("the economy engine in China")

最后,源码在位置可以进行下载:https://github.com/liu-xiao-guo/semantic_search_es/blob/main/vector-search-using-gemini-elastic.ipynb

这篇关于快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/629615

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

乐鑫 Matter 技术体验日|快速落地 Matter 产品,引领智能家居生态新发展

随着 Matter 协议的推广和普及,智能家居行业正迎来新的发展机遇,众多厂商纷纷投身于 Matter 产品的研发与验证。然而,开发者普遍面临技术门槛高、认证流程繁琐、生产管理复杂等诸多挑战。  乐鑫信息科技 (688018.SH) 凭借深厚的研发实力与行业洞察力,推出了全面的 Matter 解决方案,包含基于乐鑫 SoC 的 Matter 硬件平台、基于开源 ESP-Matter SDK 的一

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

零基础STM32单片机编程入门(一)初识STM32单片机

文章目录 一.概要二.单片机型号命名规则三.STM32F103系统架构四.STM32F103C8T6单片机启动流程五.STM32F103C8T6单片机主要外设资源六.编程过程中芯片数据手册的作用1.单片机外设资源情况2.STM32单片机内部框图3.STM32单片机管脚图4.STM32单片机每个管脚可配功能5.单片机功耗数据6.FALSH编程时间,擦写次数7.I/O高低电平电压表格8.外设接口

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

大语言模型(LLMs)能够进行推理和规划吗?

大语言模型(LLMs),基本上是经过强化训练的 n-gram 模型,它们在网络规模的语言语料库(实际上,可以说是我们文明的知识库)上进行了训练,展现出了一种超乎预期的语言行为,引发了我们的广泛关注。从训练和操作的角度来看,LLMs 可以被认为是一种巨大的、非真实的记忆库,相当于为我们所有人提供了一个外部的系统 1(见图 1)。然而,它们表面上的多功能性让许多研究者好奇,这些模型是否也能在通常需要系

ps基础入门

1.基础      1.1新建文件      1.2创建指定形状      1.4移动工具          1.41移动画布中的任意元素          1.42移动画布          1.43修改画布大小          1.44修改图像大小      1.5框选工具      1.6矩形工具      1.7图层          1.71图层颜色修改          1