此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Redis

本节将指导您设置 RedisVectorStore 以存储文档嵌入并执行相似性搜索。spring-doc.cadn.net.cn

Redis 是一个开源(BSD许可)、内存中的数据结构存储系统,可用作数据库、缓存、消息代理和流引擎。Redis提供了诸如字符串、哈希、列表、集合、带范围查询的有序集合、位图、超日志、地理空间索引和流等数据结构。spring-doc.cadn.net.cn

Redis 搜索与查询 扩展了 Redis OSS 的核心功能,并允许您将 Redis 用作向量数据库:spring-doc.cadn.net.cn

前置条件

  1. 一个 Redis Stack 实例spring-doc.cadn.net.cn

  2. EmbeddingModel 实例用于计算文档嵌入。有几种选项可供选择:spring-doc.cadn.net.cn

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

Spring AI 为 Redis 向量存储提供了 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 文件中:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-redis</artifactId>
</dependency>

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。
请参阅 构件仓库 部分,将 Maven 中央仓库和/或快照仓库添加到您的构建文件中。

向量存储实现可以为您初始化所需的架构,但您必须通过在适当的构造函数中指定 initializeSchema 布尔值或在 application.properties 文件中设置 …​initialize-schema=true 来选择加入。spring-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此架构初始化是默认发生的。

请查看 向量存储的配置参数 列表,以了解默认值和配置选项。spring-doc.cadn.net.cn

此外,您还需要一个已配置的 EmbeddingModel bean。有关更多信息,请参阅 EmbeddingModel 部分。spring-doc.cadn.net.cn

现在你可以在你的应用程序中自动装配RedisVectorStore作为向量存储。spring-doc.cadn.net.cn

@Autowired VectorStore vectorStore;

// ...

List <Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to Redis
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置属性

要连接到 Redis 并使用 RedisVectorStore,您需要提供实例的访问详细信息。 可以通过 Spring Boot 的 application.yml 提供简单的配置,spring-doc.cadn.net.cn

spring:
  data:
    redis:
      url: <redis instance url>
  ai:
    vectorstore:
      redis:
        initialize-schema: true
        index-name: custom-index
        prefix: custom-prefix

对于 Redis 连接配置,也可以通过 Spring Boot 的 application.properties 提供简单的配置。spring-doc.cadn.net.cn

spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.username=default
spring.data.redis.password=

spring.ai.vectorstore.redis.* 开头的属性用于配置 RedisVectorStorespring-doc.cadn.net.cn

<property> </property> <description> </description> 默认值

spring.ai.vectorstore.redis.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.redis.index-namespring-doc.cadn.net.cn

用于存储向量的索引名称spring-doc.cadn.net.cn

spring-ai-indexspring-doc.cadn.net.cn

spring.ai.vectorstore.redis.prefixspring-doc.cadn.net.cn

Redis 键的前缀spring-doc.cadn.net.cn

embedding:spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.distance-metricspring-doc.cadn.net.cn

向量相似度的距离度量(COSINE、L2、IP)spring-doc.cadn.net.cn

COSINEspring-doc.cadn.net.cn

spring.ai.vectorstore.redis.vector-algorithmspring-doc.cadn.net.cn

向量索引算法 (HNSW, FLAT)spring-doc.cadn.net.cn

HNSWspring-doc.cadn.net.cn

spring.ai.vectorstore.redis.hnsw-mspring-doc.cadn.net.cn

HNSW:最大传出连接数spring-doc.cadn.net.cn

16spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.hnsw-ef-constructionspring-doc.cadn.net.cn

HNSW:索引构建期间的最大连接数spring-doc.cadn.net.cn

200spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.hnsw-ef-runtimespring-doc.cadn.net.cn

HNSW:搜索过程中要考虑的连接数spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.default-range-thresholdspring-doc.cadn.net.cn

范围搜索的默认半径阈值spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.text-scorerspring-doc.cadn.net.cn

文本评分算法(BM25、TFIDF、BM25STD、DISMAX、DOCSCORE)spring-doc.cadn.net.cn

BM25spring-doc.cadn.net.cn

元数据过滤

您也可以利用通用的、可移植的 元数据过滤器 与 Redis 一起使用。spring-doc.cadn.net.cn

例如,您可以使用文本表达式语言:spring-doc.cadn.net.cn

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("country in ['UK', 'NL'] && year >= 2020").build());

或以编程方式使用 Filter.Expression DSL:spring-doc.cadn.net.cn

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression(b.and(
                b.in("country", "UK", "NL"),
                b.gte("year", 2020)).build()).build());
那些(可移植的)过滤器表达式会自动转换为 Redis 搜索查询

例如,此可移植的过滤器表达式:spring-doc.cadn.net.cn

country in ['UK', 'NL'] && year >= 2020

被转换为专有的 Redis 过滤器格式:spring-doc.cadn.net.cn

@country:{UK | NL} @year:[2020 inf]

手动配置

不使用 Spring Boot 自动配置,您可以手动配置 Redis 向量存储。为此,您需要将 spring-ai-redis-store 添加到您的项目中:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-redis-store</artifactId>
</dependency>

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-redis-store'
}

创建一个 JedisPooled bean:spring-doc.cadn.net.cn

@Bean
public JedisPooled jedisPooled() {
    return new JedisPooled("<host>", 6379);
}

然后使用构建器模式创建 RedisVectorStore bean:spring-doc.cadn.net.cn

@Bean
public VectorStore vectorStore(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
    return RedisVectorStore.builder(jedisPooled, embeddingModel)
        .indexName("custom-index")                // Optional: defaults to "spring-ai-index"
        .prefix("custom-prefix")                  // Optional: defaults to "embedding:"
        .contentFieldName("content")              // Optional: field for document content
        .embeddingFieldName("embedding")          // Optional: field for vector embeddings
        .vectorAlgorithm(Algorithm.HNSW)          // Optional: HNSW or FLAT (defaults to HNSW)
        .distanceMetric(DistanceMetric.COSINE)    // Optional: COSINE, L2, or IP (defaults to COSINE)
        .hnswM(16)                                // Optional: HNSW connections (defaults to 16)
        .hnswEfConstruction(200)                  // Optional: HNSW build parameter (defaults to 200)
        .hnswEfRuntime(10)                        // Optional: HNSW search parameter (defaults to 10)
        .defaultRangeThreshold(0.8)               // Optional: default radius for range searches
        .textScorer(TextScorer.BM25)              // Optional: text scoring algorithm (defaults to BM25)
        .metadataFields(                          // Optional: define metadata fields for filtering
            MetadataField.tag("country"),
            MetadataField.numeric("year"),
            MetadataField.text("description"))
        .initializeSchema(true)                   // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}

您必须明确列出所有元数据字段名称和类型(TAGTEXTNUMERIC),用于在过滤表达式中使用的任何元数据字段。 上面的 metadataFields 注册了可过滤的元数据字段:类型为 TAGcountry,类型为 NUMERICyearspring-doc.cadn.net.cn

访问原生客户端

Redis 向量存储实现通过 JedisPooled 方法提供对底层原生 Redis 客户端(JedisPooled)的访问:spring-doc.cadn.net.cn

RedisVectorStore vectorStore = context.getBean(RedisVectorStore.class);
Optional<JedisPooled> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    JedisPooled jedis = nativeClient.get();
    // Use the native client for Redis-specific operations
}

原生客户端使您能够访问可能无法通过 VectorStore 接口暴露的 Redis 特定功能和操作。spring-doc.cadn.net.cn

距离度量

Redis 向量存储支持三种用于向量相似度的距离度量:spring-doc.cadn.net.cn

每个指标都会自动归一化为 0-1 的相似度分数,其中 1 表示最相似。spring-doc.cadn.net.cn

RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
    .distanceMetric(DistanceMetric.COSINE)  // or L2, IP
    .build();

HNSW 算法配置

Redis 向量存储默认使用 HNSW(分层可导航小世界)算法,以实现高效的近似最近邻搜索。您可以根据具体用例调整 HNSW 参数:spring-doc.cadn.net.cn

RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
    .vectorAlgorithm(Algorithm.HNSW)
    .hnswM(32)                    // Maximum outgoing connections per node (default: 16)
    .hnswEfConstruction(100)      // Connections during index building (default: 200)
    .hnswEfRuntime(50)            // Connections during search (default: 10)
    .build();

参数指南:spring-doc.cadn.net.cn

  • M: 较高的值可以提高召回率,但会增加内存使用和索引时间。典型值:12-48。spring-doc.cadn.net.cn

  • EF_CONSTRUCTION:较高的值会提高索引质量,但会增加构建时间。典型值:100-500。spring-doc.cadn.net.cn

  • EF_RUNTIME: 较高的值可以提高搜索准确性,但会增加延迟。典型值:10-100。spring-doc.cadn.net.cn

对于较小的数据集或需要精确结果时,请改用 FLAT 算法:spring-doc.cadn.net.cn

RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
    .vectorAlgorithm(Algorithm.FLAT)
    .build();

Redis 向量存储利用 Redis 查询引擎的全文搜索功能提供文本搜索能力。这使您能够根据 TEXT 字段中的关键词和短语查找文档:spring-doc.cadn.net.cn

// Search for documents containing specific text
List<Document> textResults = vectorStore.searchByText(
    "machine learning",   // search query
    "content",            // field to search (must be TEXT type)
    10,                   // limit
    "category == 'AI'"    // optional filter expression
);

文本搜索支持:spring-doc.cadn.net.cn

在构建时配置文本搜索行为:spring-doc.cadn.net.cn

RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
    .textScorer(TextScorer.TFIDF)                    // Text scoring algorithm
    .inOrder(true)                                   // Match terms in order
    .stopwords(Set.of("is", "a", "the", "and"))      // Ignore common words
    .metadataFields(MetadataField.text("description")) // Define TEXT fields
    .build();

文本评分算法

提供了几种文本评分算法:spring-doc.cadn.net.cn

分数被标准化到 0-1 范围,以与向量相似度分数保持一致。spring-doc.cadn.net.cn

范围搜索返回指定半径阈值内的所有文档,而不是固定数量的最近邻居:spring-doc.cadn.net.cn

// Search with explicit radius
List<Document> rangeResults = vectorStore.searchByRange(
    "AI and machine learning",  // query
    0.8,                        // radius (similarity threshold)
    "category == 'AI'"          // optional filter expression
);

您还可以在构造时设置默认范围阈值:spring-doc.cadn.net.cn

RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
    .defaultRangeThreshold(0.8)  // Set default threshold
    .build();

// Use default threshold
List<Document> results = vectorStore.searchByRange("query");

范围搜索在您希望检索所有高于相似度阈值的相关文档时非常有用,而不是限制为特定的数量。spring-doc.cadn.net.cn

语义缓存

语义缓存是一种强大的优化技术,利用 Redis 向量搜索功能,根据用户查询的语义相似性而非精确字符串匹配来缓存和检索 AI 聊天响应。 这使得即使用户以不同方式表达相似问题,也能智能地重用响应。spring-doc.cadn.net.cn

为什么使用语义缓存?

传统缓存依赖于精确的键匹配,当用户用不同的措辞提出语义等效的问题时,这种方法会失效:spring-doc.cadn.net.cn

所有三个查询都有相同的答案,但传统缓存会将它们视为不同的请求,导致冗余的 LLM API 调用。 语义缓存通过使用向量嵌入比较查询的含义来解决这个问题。spring-doc.cadn.net.cn

Auto-configuration

Spring AI 为 Redis 语义缓存提供了 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-redis-semantic-cache</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis-semantic-cache'
}
自动配置提供了一个默认的嵌入模型,该模型针对语义缓存进行了优化(redis/langcache-embed-v1)。 您可以通过提供自己的 EmbeddingModel bean 来覆盖它。

配置属性

spring.ai.vectorstore.redis.semantic-cache.* 开头的属性配置语义缓存:spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认值

spring.ai.vectorstore.redis.semantic-cache.enabledspring-doc.cadn.net.cn

启用或禁用语义缓存spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.vectorstore.redis.semantic-cache.hostspring-doc.cadn.net.cn

Redis 服务器主机spring-doc.cadn.net.cn

localhostspring-doc.cadn.net.cn

spring.ai.vectorstore.redis.semantic-cache.portspring-doc.cadn.net.cn

Redis 服务器端口spring-doc.cadn.net.cn

6379spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.semantic-cache.similarity-thresholdspring-doc.cadn.net.cn

缓存命中的相似度阈值(0.0-1.0)。较高的值需要更接近的语义匹配。spring-doc.cadn.net.cn

0.95spring-doc.cadn.net.cn

spring.ai.vectorstore.redis.semantic-cache.index-namespring-doc.cadn.net.cn

用于缓存条目的 Redis 搜索索引名称spring-doc.cadn.net.cn

semantic-cache-indexspring-doc.cadn.net.cn

spring.ai.vectorstore.redis.semantic-cache.prefixspring-doc.cadn.net.cn

Redis 中缓存条目的键前缀spring-doc.cadn.net.cn

semantic-cache:spring-doc.cadn.net.cn

application.yml 中的示例配置:spring-doc.cadn.net.cn

spring:
  ai:
    vectorstore:
      redis:
        semantic-cache:
          enabled: true
          host: localhost
          port: 6379
          similarity-threshold: 0.85
          index-name: my-app-cache
          prefix: "my-app:semantic-cache:"

使用 SemanticCacheAdvisor

SemanticCacheAdvisor 与 Spring AI 的 ChatClient 顾问模式无缝集成。 它会自动缓存响应并为类似查询返回缓存结果:spring-doc.cadn.net.cn

@Autowired
private SemanticCache semanticCache;

@Autowired
private ChatModel chatModel;

public void example() {
    // Create the cache advisor
    SemanticCacheAdvisor cacheAdvisor = SemanticCacheAdvisor.builder()
        .cache(semanticCache)
        .build();

    // First query - calls the LLM and caches the response
    ChatResponse response1 = ChatClient.builder(chatModel)
        .build()
        .prompt("What is the capital of France?")
        .advisors(cacheAdvisor)
        .call()
        .chatResponse();

    // Similar query - returns cached response (no LLM call)
    ChatResponse response2 = ChatClient.builder(chatModel)
        .build()
        .prompt("Tell me the capital city of France")
        .advisors(cacheAdvisor)
        .call()
        .chatResponse();

    // response1 and response2 contain the same cached answer
}

该顾问自动执行以下操作:spring-doc.cadn.net.cn

  1. 在调用 LLM 之前检查缓存中是否存在语义相似的查询spring-doc.cadn.net.cn

  2. 当找到高于相似度阈值的匹配项时,返回缓存的响应spring-doc.cadn.net.cn

  3. 在成功的 LLM 调用后缓存新响应spring-doc.cadn.net.cn

  4. 支持同步和流式聊天操作spring-doc.cadn.net.cn

直接缓存使用

您也可以直接与 SemanticCache 交互以进行细粒度控制:spring-doc.cadn.net.cn

@Autowired
private SemanticCache semanticCache;

// Store a response with a query
semanticCache.set("What is the capital of France?", chatResponse);

// Store with TTL (time-to-live) for automatic expiration
semanticCache.set("What's the weather today?", weatherResponse, Duration.ofHours(1));

// Retrieve a semantically similar response
Optional<ChatResponse> cached = semanticCache.get("Tell me France's capital");

if (cached.isPresent()) {
    // Use the cached response
    String answer = cached.get().getResult().getOutput().getText();
}

// Clear all cached entries
semanticCache.clear();

手动配置

为了获得更多控制权,您可以手动配置语义缓存组件:spring-doc.cadn.net.cn

@Configuration
public class SemanticCacheConfig {

    @Bean
    public JedisPooled jedisPooled() {
        return new JedisPooled("localhost", 6379);
    }

    @Bean
    public SemanticCache semanticCache(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
        return DefaultSemanticCache.builder()
            .jedisClient(jedisPooled)
            .embeddingModel(embeddingModel)
            .distanceThreshold(0.3)           // Lower = stricter matching
            .indexName("my-semantic-cache")
            .prefix("cache:")
            .build();
    }

    @Bean
    public SemanticCacheAdvisor semanticCacheAdvisor(SemanticCache cache) {
        return SemanticCacheAdvisor.builder()
            .cache(cache)
            .build();
    }
}

使用命名空间进行缓存隔离

对于多租户应用程序或当您需要单独的缓存空间时,请使用不同的索引名称来隔离缓存条目:spring-doc.cadn.net.cn

// Create isolated caches for different users or contexts
SemanticCache user1Cache = DefaultSemanticCache.builder()
    .jedisClient(jedisPooled)
    .embeddingModel(embeddingModel)
    .indexName("user-1-cache")
    .build();

SemanticCache user2Cache = DefaultSemanticCache.builder()
    .jedisClient(jedisPooled)
    .embeddingModel(embeddingModel)
    .indexName("user-2-cache")
    .build();

// Each user gets their own isolated cache space
SemanticCacheAdvisor user1Advisor = SemanticCacheAdvisor.builder()
    .cache(user1Cache)
    .build();

系统提示词隔离

SemanticCacheAdvisor 根据系统提示自动隔离缓存响应。 这确保了具有不同系统提示的相同用户查询返回不同的缓存响应,这对于具有多个 AI 人格或依赖于上下文行为的应用程序至关重要。spring-doc.cadn.net.cn

SemanticCacheAdvisor cacheAdvisor = SemanticCacheAdvisor.builder()
    .cache(semanticCache)
    .build();

// Query with technical support persona
ChatResponse technicalResponse = ChatClient.builder(chatModel)
    .build()
    .prompt()
    .system("You are a technical support specialist. Provide detailed technical answers.")
    .user("How do I reset my password?")
    .advisors(cacheAdvisor)
    .call()
    .chatResponse();

// Same query with customer service persona - cache MISS (different context)
ChatResponse serviceResponse = ChatClient.builder(chatModel)
    .build()
    .prompt()
    .system("You are a friendly customer service agent. Keep responses brief and helpful.")
    .user("How do I reset my password?")
    .advisors(cacheAdvisor)
    .call()
    .chatResponse();

// Same query with technical support persona again - cache HIT
ChatResponse technicalAgain = ChatClient.builder(chatModel)
    .build()
    .prompt()
    .system("You are a technical support specialist. Provide detailed technical answers.")
    .user("How do I reset my password?")
    .advisors(cacheAdvisor)
    .call()
    .chatResponse();
// Returns the cached technical response

工作原理:spring-doc.cadn.net.cn

顾问会计算系统提示的确定性哈希值,并在存储和检索缓存响应时将其用作元数据过滤器:spring-doc.cadn.net.cn

上下文感知缓存 API

对于高级用例,您可以直接使用上下文感知的缓存方法:spring-doc.cadn.net.cn

// Store with explicit context hash
String contextHash = "technical-support-context";
semanticCache.set("How do I reset my password?", response, contextHash);

// Retrieve with context filtering
Optional<ChatResponse> cached = semanticCache.get("How do I reset my password?", contextHash);

// Different context hash returns empty (no match)
Optional<ChatResponse> otherContext = semanticCache.get("How do I reset my password?", "billing-context");

调整相似度阈值

相似度阈值决定了查询必须与缓存条目匹配到何种程度才能被视为命中。 该阈值表示为 0.0 到 1.0 之间的值:spring-doc.cadn.net.cn

  • 更高的阈值(例如,0.95): 需要非常接近的语义匹配。 减少误报,但可能会遗漏有效的缓存命中。spring-doc.cadn.net.cn

  • 下限阈值(例如,0.70):允许更广泛的语义匹配。 提高缓存命中率,但可能会返回相关性较低的缓存响应。spring-doc.cadn.net.cn

// Strict matching - only very similar queries hit the cache
SemanticCache strictCache = DefaultSemanticCache.builder()
    .jedisClient(jedisPooled)
    .embeddingModel(embeddingModel)
    .distanceThreshold(0.2)  // Strict (distance-based, lower = stricter)
    .build();

// Lenient matching - broader semantic similarity accepted
SemanticCache lenientCache = DefaultSemanticCache.builder()
    .jedisClient(jedisPooled)
    .embeddingModel(embeddingModel)
    .distanceThreshold(0.5)  // Lenient
    .build();
从更高的阈值(更严格的匹配)开始,并根据您的应用程序对语义变化的容忍度逐渐降低它。

TTL 和缓存过期

缓存响应可以配置生存时间(TTL)以实现自动过期。 这对于时间敏感的数据至关重要:spring-doc.cadn.net.cn

// Cache weather data for 1 hour
semanticCache.set("What's the weather in New York?", weatherResponse, Duration.ofHours(1));

// Cache general knowledge indefinitely (no TTL)
semanticCache.set("What is photosynthesis?", scienceResponse);

// Redis automatically removes expired entries

工作原理

语义缓存按照以下流程运行:spring-doc.cadn.net.cn

  1. 查询嵌入:当查询到达时,它会被转换为向量嵌入,使用配置的 EmbeddingModelspring-doc.cadn.net.cn

  2. 向量搜索:Redis 执行基于范围的向量搜索(VECTOR_RANGE)以查找相似度阈值内的缓存条目spring-doc.cadn.net.cn

  3. 缓存命中:如果找到语义相似的查询,则立即返回缓存的 ChatResponsespring-doc.cadn.net.cn

  4. 缓存未命中: 如果未找到匹配项,查询将进入 LLM,并且响应将被缓存以供将来使用spring-doc.cadn.net.cn

The implementation leverages Redis’s efficient vector indexing (HNSW algorithm) for fast similarity searches, even with large cache sizes.spring-doc.cadn.net.cn