Embeddings和Vector入门

Embeddings

文本嵌入(Embeddings)将文本转换为数值数组或向量,使人工智能模型能够处理和理解语言数据。这种从文本到数字的转换以及反向转换,是人工智能如何与人类语言互动和理解它的关键要素。

文本嵌入在诸如检索增强生成 (RAG) 模式等实际应用中尤为重要。将参考文档转换为向量保存在向量数据库中,将输入内容经过同样的嵌入处理,得到一个向量,并计算两者向量的距离得到相似性。

Vector Databases

向量数据库(Vector Databases)是一种在人工智能应用中扮演着重要角色的特殊数据库类型。与传统的关系型数据库不同,向量数据库中的查询不是进行精确匹配,而是执行相似性搜索。当使用向量作为查询时,向量数据库会返回与查询向量"相似"的向量。

向量数据库用于将您的数据与人工智能模型集成。使用它们的第一步是将您的数据加载到向量数据库中。然后,当用户查询需要发送到人工智能模型时,首先会检索一组相似的文档。然后,这些文档连同用户的查询一起作为用户问题的上下文发送到人工智能模型。这种技术称为检索增强生成 (Retrieval Augmented Generation, RAG)。

RAG 处理流程

环境准备

项目pom增加向量数据库依赖:

xml 复制代码
<!-- redis ai-->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

Docker搭建RedisVectorStore

shell 复制代码
sudo docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 -v redis-stack-data:/data redis/redis-stack:latest

命令解释: -d:在容器后台运行; -p 6379:6379:端口映射(Redis端口) -p [宿主机端口]:[容器端口]; -p 8001:8001:端口映射(RedisInsight可视化工具端口) -p [宿主机端口]:[容器端口]; -v redis-stack-data:/data:数据卷挂载 -v [数据卷]:[容器目录\文件]; --name redis-stack:设置容器名称 --name [容器名称]; redis/redis-stack:latest:镜像版本名称;

部署实例

配置信息

yaml 复制代码
redis:
  url: redis://172.31.14.139:6379
  index: post
  numeric: year

创建RedisConfig配置类

java 复制代码
@Data
@Component
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {

    private String url;

    private String index;

    private String tag;

    private String text;

    private String numeric;
}

创建Redis向量数据库和内存向量数据库对象

java 复制代码
@Configuration
public class VectorStoreConfig {

    @Bean
    public SimpleVectorStore simpleVectorStore(OllamaEmbeddingClient embeddingClient) {
        return new SimpleVectorStore(embeddingClient);
    }

    @Bean
    public JedisPooled jedisPooled(RedisConfig redisConfig) {
        return new JedisPooled(redisConfig.getUrl());
    }

    @Bean
    public RedisVectorStore redisVectorStore(RedisConfig redisConfig, OllamaEmbeddingClient embeddingClient) {
        RedisVectorStore.RedisVectorStoreConfig config = RedisVectorStore.RedisVectorStoreConfig.builder()
                .withURI(redisConfig.getUrl()).withIndexName(redisConfig.getIndex())
                .withMetadataFields(RedisVectorStore.MetadataField.numeric(redisConfig.getNumeric())).build();
        RedisVectorStore redisVectorStore = new RedisVectorStore(config, embeddingClient);
        return redisVectorStore;
    }
}

单元测试

示例一

controller代码

java 复制代码
@GetMapping("/chat/call3")
public List<List<Double>> call3() {
    return embeddingClient.embed(List.of("Hello World", "World is big and salvation is near"));
}

测试用例

java 复制代码
@Test
public void call3Test() throws Exception {
    String url = "/chat/call3";
    mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}

执行结果

示例二

controller代码

java 复制代码
@GetMapping("/chat/call4")
public List<List<Double>> call4() {
    return embeddingClient.embed(List.of("MyBatis 分页插件 PageHelper", "MyBatis 通用Mapper", "MyBatis 最新的 mybatis-mapper"));
}

测试用例

java 复制代码
@Test
public void call4Test() throws Exception {
    String url = "/chat/call4";
    mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}

执行结果

示例三

controller代码

java 复制代码
@GetMapping("/chat/call5")
public EmbeddingResponse call5() {
    return embeddingClient.embedForResponse(List.of("Hello World", "World is big and salvation is near"));
}

测试用例

java 复制代码
@Test
public void call5Test() throws Exception {
    String url = "/chat/call5";
    mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}

执行结果

示例四

controller代码

java 复制代码
@GetMapping("/chat/call6")
public List<Document> call6() {
    List<Document> documents = List.of(new Document("MyBatis 分页插件 PageHelper", Map.of("year", 2014)), 
            new Document("MyBatis 通用Mapper", Map.of("year", 2014)), 
            new Document("MyBatis 最新的 mybatis-mapper", Map.of("year", 2019)));
    vectorStore.add(documents);
    return vectorStore.similaritySearch(SearchRequest.query("插件").withTopK(2));
}

测试用例

java 复制代码
@Test
public void call6Test() throws Exception {
    String url = "/chat/call6";
    mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}

执行结果

java 复制代码
MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = [{"embedding":[],"content":"MyBatis 通用Mapper","id":"00245bd0-ce14-4a75-82aa-dde3015ede37","metadata":{"year":"2014","vector_score":0.22201413}},{"embedding":[],"content":"MyBatis 分页插件 PageHelper","id":"c072fb56-7daf-42ef-aa6f-7c4551eedc0e","metadata":{"year":"2014","vector_score":0.30925614}}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

示例五

controller代码

java 复制代码
@GetMapping("/chat/call7")
public List<Embedding> call7() {
    OllamaOptions ollamaOptions = OllamaOptions.create();
    ollamaOptions.withModel("qwen:latest").setTemperature(0.7f);
    List<String> message = List.of("Hello World", "World is big and salvation is near");
    EmbeddingRequest request = new EmbeddingRequest(message, ollamaOptions);
    EmbeddingResponse embeddingResponse = embeddingClient.call(request);
    return embeddingResponse.getResults();
}

测试用例

java 复制代码
@Test
public void call7Test() throws Exception {
    String url = "/chat/call7";
    mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}

执行结果

相关推荐
小众AI2 小时前
AI-on-the-edge-device - 将“旧”设备接入智能世界
人工智能·开源·ai编程
舟寒、2 小时前
【论文分享】Ultra-AV: 一个规范化自动驾驶汽车纵向轨迹数据集
人工智能·自动驾驶·汽车
梦云澜5 小时前
论文阅读(十二):全基因组关联研究中生物通路的图形建模
论文阅读·人工智能·深度学习
远洋录6 小时前
构建一个数据分析Agent:提升分析效率的实践
人工智能·ai·ai agent
IT古董7 小时前
【深度学习】常见模型-Transformer模型
人工智能·深度学习·transformer
沐雪架构师7 小时前
AI大模型开发原理篇-2:语言模型雏形之词袋模型
人工智能·语言模型·自然语言处理
python算法(魔法师版)8 小时前
深度学习深度解析:从基础到前沿
人工智能·深度学习
kakaZhui9 小时前
【llm对话系统】大模型源码分析之 LLaMA 位置编码 RoPE
人工智能·深度学习·chatgpt·aigc·llama
struggle202510 小时前
一个开源 GenBI AI 本地代理(确保本地数据安全),使数据驱动型团队能够与其数据进行互动,生成文本到 SQL、图表、电子表格、报告和 BI
人工智能·深度学习·目标检测·语言模型·自然语言处理·数据挖掘·集成学习
佛州小李哥10 小时前
通过亚马逊云科技Bedrock打造自定义AI智能体Agent(上)
人工智能·科技·ai·语言模型·云计算·aws·亚马逊云科技