快速入门:使用 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 os

load_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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/337263.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

浅析Java中volatile关键字

认识volatile关键字 Java中的volatile关键字用于修饰一个变量,当这个变量被多个线程共享时,这个变量的值如果发生更新,每个线程都能获取到最新的值。volatile关键字在多线程环境下还会禁止指令重排序,确保变量的赋值操作按照代码的…

书生·浦语大模型实战营-学习笔记4

XTuner 大模型单卡低成本微调实战 Finetune简介 常见的两种微调策略:增量预训练、指令跟随 指令跟随微调 数据是一问一答的形式 对话模板构建 每个开源模型使用的对话模板都不相同 指令微调原理: 由于只有答案部分是我们期望模型来进行回答的内容…

敏捷测试和DevOpes自动化测试的区别

敏捷测试和DevOps自动化测试在以下方面存在区别👇 1️⃣目标 🎈敏捷测试的主要目标是提供快速的反馈和持续的改进,以便在开发过程中尽早发现和解决问题,从而提高软件的质量和可靠性。 🌈DevOps自动化测试的目标是提高软…

C语言算法赛——蓝桥杯(省赛试题)

一、十四届C/C程序设计C组试题 十四届程序C组试题A#include <stdio.h> int main() {long long sum 0;int n 20230408;int i 0;// 累加从1到n的所有整数for (i 1; i < n; i){sum i;}// 输出结果printf("%lld\n", sum);return 0; }//十四届程序C组试题B…

统计学-R语言-7.1

文章目录 前言假设检验的原理假设检验的原理提出假设做出决策表述结果效应量 总体均值的检验总体均值的检验(一个总体均值的检验) 练习 前言 本章主题是假设检验(hypothesis testing)。与参数估计一样&#xff0c;假设检验也是对总体参数感兴趣&#xff0c;如比例、比例间的差…

负载均衡流程

1、负载均衡流程图 2、触发负载均衡函数trigger_load_balance void trigger_load_balance(struct rq *rq) { /* Dont need to rebalance while attached to NULL domain */ if (unlikely(on_null_domain(rq)))//当前调度队列中的调度域是空的则返回 return; i…

SpringMVC数据校验

导包 配置springmvc.xml <bean id"validator" class" org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"><property name"providerClass" value"org.hibernate.validator.HibernateValidator ">…

『C++成长记』模板

&#x1f525;博客主页&#xff1a;小王又困了 &#x1f4da;系列专栏&#xff1a;C &#x1f31f;人之为学&#xff0c;不日近则日退 ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 目录 一、泛型编程 二、函数模板 &#x1f4d2;2.1函数模板概念 &#x1f4d2;2.2函数…

羊驼系列大模型LLaMa、Alpaca、Vicuna

羊驼系列大模型&#xff1a;大模型的安卓系统 GPT系列&#xff1a;类比ios系统&#xff0c;不开源 LLaMa让大模型平民化 LLaMa优势 用到的数据&#xff1a;大部分英语、西班牙语&#xff0c;少中文 模型下载地址 https://huggingface.co/meta-llama Alpaca模型 Alpaca是斯…

ELK之Grafana读取ES-Nginx数据后地图不展示的问题

一、背景&#xff1a;Grafana读取ES-Nginx数据后地图不展示 二、解决方法 [rootsg grafana-worldmap-panel]# pwd /var/lib/grafana/plugins/grafana-worldmap-panel [rootsg grafana-worldmap-panel]# [rootsg grafana-worldmap-panel]# sed -i s/https:\/\/cartodb-basemap…

基于SpringBoot Vue高校失物招领系统

大家好✌&#xff01;我是Dwzun。很高兴你能来阅读我&#xff0c;我会陆续更新Java后端、前端、数据库、项目案例等相关知识点总结&#xff0c;还为大家分享优质的实战项目&#xff0c;本人在Java项目开发领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目&#x…

Python-基础篇-数据结构-列表、元组、字典、集合

文章目录 思维导图❓ 大抵是何物数据结构切片 &#x1f4ac;具体是何物列表&#x1f4bb; list&#x1f4bb; [ ]自我介绍精神面貌使用说明生理体征增删查改 方法汇总 元组&#x1f4bb; tuple&#x1f4bb; ( )自我介绍使用说明精神面貌生理体征增删查改 字典&#x1f4bb; di…

有什么提高编程能力的书籍推荐吗?

数据密集型应用系统设计 原文完整版PDF&#xff1a;https://pan.quark.cn/s/d5a34151fee9 这本书的作者是少有的从工业界干到学术界的牛人&#xff0c;知识面广得惊人&#xff0c;也善于举一反三&#xff0c;知识之间互相关联&#xff0c;比如有个地方把读路径比作programming …

qt学习:QT对话框+颜色+文件+字体+输入

目录 概述 继承图 QColorDialog 颜色对话框 QFileDialog 文件对话框 保存文件对话框 QFontDialog 字体对话框 QInputDialog 输入对话框 概述 对于对话框的功能&#xff0c;在GUI图形界面开发过程&#xff0c;使用是非常多&#xff0c;那么Qt也提供了丰富的对话框类QDia…

R2DBC-响应式数据库

简单查询 基于全异步,响应式,消息驱动 用法: 1.导入驱动:导入连接池(r2dbc-pool),导入驱动(r2dbc-mysql) 2. 使用驱动提供的api操作 pom.xml <properties><r2dbc-mysql.version>1.0.5</r2dbc-mysql.version> </properties><dependencies><d…

【目标检测】YOLOv5算法实现(九):模型预测

本系列文章记录本人硕士阶段YOLO系列目标检测算法自学及其代码实现的过程。其中算法具体实现借鉴于ultralytics YOLO源码Github&#xff0c;删减了源码中部分内容&#xff0c;满足个人科研需求。   本系列文章主要以YOLOv5为例完成算法的实现&#xff0c;后续修改、增加相关模…

成绩等级分数段查询(python条件分支语句match...case...)

根据有效分数序列及等级差值&#xff0c;计算并打印等级相应分数区间。 (笔记模板由python脚本于2024年01月20日 23:57:32创建&#xff0c;本篇笔记适合会条件分支语句的初学者的coder翻阅) 【学习的细节是欢悦的历程】 Python 官网&#xff1a;https://www.python.org/ Free&…

视频怎么添加字幕?这几款工具很实用

视频怎么添加字幕&#xff1f;现在&#xff0c;视频已经成为人们获取信息和娱乐的主要方式之一。然而&#xff0c;很多时候&#xff0c;我们想要更深入地理解视频内容&#xff0c;或者为听力障碍者提供帮助&#xff0c;就需要添加字幕。那么&#xff0c;如何为视频添加字幕呢&a…

《游戏-02_2D-开发》

基于《游戏-01_2D-开发》&#xff0c; 继续制作游戏&#xff1a; 首先给人物添加一个2D重力效果 在编辑的项目设置中&#xff0c; 可以看出unity默认给的2D重力数值是-9.81&#xff0c;模拟现实社会中的重力效果 下方可以设置帧率 而Gravity Scale代表 这个数值会 * 重力 还…

Git将某个文件合并到指定分支

企业开发中&#xff0c;经常会单独拉分支去做自己的需求开发&#xff0c;但是某些时候一些公共的配置我们需要从主线pull&#xff0c;这时候整个分支merge显然不合适 1.切换至待合并文件的分支 git checkout <branch>2.将目标分支的单个文件合并到当前分支 git checkou…
最新文章