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

Bedrock converse API

亚马逊 Bedrock Converse API 提供了一个增强功能的统一界面,支持对话式 AI 模型,包括函数/工具调用、多模态输入和流式响应。spring-doc.cadn.net.cn

Bedrock Converse API 的高阶功能包括:spring-doc.cadn.net.cn

bedsrock converse api 提供了一个多模型提供者之间的统一接口,同时处理了aws特定的认证和基础设施问题。 目前, converse api 支持的模型 包括: Amazon TitanAmazon NovaAI21 LabsAnthropic ClaudeCohere CommandMeta LlamaMistral AI

遵循 Bedrock 的推荐,Spring AI 正在采用亚马逊 Bedrock 的 converse API 作为所有 Spring AI 应用中的聊天会话实现的基础。 虽然现有的 InvokeModel API 支持聊天应用,但我们强烈推荐为所有 Chat 会话模型采用 converse API。spring-doc.cadn.net.cn

converse 平台不支持嵌入操作,因此这些功能将继续存在于现有版本中,并继续维护模型功能spring-doc.cadn.net.cn

前提条件

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

Add the spring-ai-starter-model-bedrock-converse dependency to your project’s Maven pom.xml or Gradle build.gradle build files:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-bedrock-converse</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-bedrock-converse'
}
参考以下依赖管理部分,添加Spring AI BOM到你的构建文件中。

聊天属性

前缀 spring.ai.bedrock.aws 是配置到亚马逊 Bedrock 连接的属性前缀。spring-doc.cadn.net.cn

属性 描述 默认

spring.ai.bedrock.aws.regionspring-doc.cadn.net.cn

AWS可用区用于Spring Bootspring-doc.cadn.net.cn

us-east-1spring-doc.cadn.net.cn

spring.ai.bedrock.aws.timeoutspring-doc.cadn.net.cn

整个API调用的最大调用时长spring-doc.cadn.net.cn

5mspring-doc.cadn.net.cn

spring.ai.bedrock.aws.connectionTimeoutspring-doc.cadn.net.cn

在建立连接时等待的最大时间spring-doc.cadn.net.cn

5sspring-doc.cadn.net.cn

spring.ai.bedrock.aws.connectionAcquisitionTimeoutspring-doc.cadn.net.cn

池中新连接的最大等待时间spring-doc.cadn.net.cn

30sspring-doc.cadn.net.cn

spring.ai.bedrock.aws.asyncReadTimeoutspring-doc.cadn.net.cn

最长处理异步响应的时间spring-doc.cadn.net.cn

30sspring-doc.cadn.net.cn

spring.ai.bedrock.aws.access-keyspring-doc.cadn.net.cn

AWS访问密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.secret-keyspring-doc.cadn.net.cn

亚马逊 Web 服务的安全密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.session-tokenspring-doc.cadn.net.cn

AWS会话Tokens用于临时凭证spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.profile.namespring-doc.cadn.net.cn

AWS配置文件名。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.profile.credentials-pathspring-doc.cadn.net.cn

AWS凭证文件路径。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.profile.configuration-pathspring-doc.cadn.net.cn

AWS 配置文件的路径。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

启用和禁用聊天自动配置现在通过顶级属性使用前缀 spring.ai.model.chat 配置完成。spring-doc.cadn.net.cn

要启用,spring.ai.model.chat=bedrock-converse(这是默认启用的)spring-doc.cadn.net.cn

要禁用,设置为 {none}(或者任何不匹配 bedrock-converse 的值)spring-doc.cadn.net.cn

这种修改是为了允许配置多个模型。spring-doc.cadn.net.cn

The prefix spring.ai.bedrock.converse.chat is the property prefix that configures the chat model implementation for the Converse API.spring-doc.cadn.net.cn

属性 描述 默认

Spring.ai Bedsrock Converse Chat Enabled (已移除,不再有效)spring-doc.cadn.net.cn

启用 Bedrock 息聊模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用 Bedrock 息聊模型。spring-doc.cadn.net.cn

bedrock-conversespring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.modelspring-doc.cadn.net.cn

模型ID设置。您可以使用支持的模型和模型功能spring-doc.cadn.net.cn

没有模型选择。从AWS Bedrock控制台选择您的 modelIdspring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.temperaturespring-doc.cadn.net.cn

控制输出的随机性。值的范围可以是[0.0,1.0]spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.top-pspring-doc.cadn.net.cn

在采样时考虑的Tokens的最大累积概率。spring-doc.cadn.net.cn

AWS Bedrock默认配置spring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.top-kspring-doc.cadn.net.cn

生成下一个token所需的token选择数量。spring-doc.cadn.net.cn

AWS Bedrock默认配置spring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.max-tokensspring-doc.cadn.net.cn

最大生成响应中的微服务Token数量限制。spring-doc.cadn.net.cn

500spring-doc.cadn.net.cn

运行时选项

使用便携的 ChatOptionsBedrockChatOptions 便携构建器来创建模型配置,例如温度、maxToken、topP等。spring-doc.cadn.net.cn

On start-up, the default options can be configured with the BedrockConverseProxyChatModel(api, options) constructor or the spring.ai.bedrock.converse.chat.options.* properties.spring-doc.cadn.net.cn

在运行时,你可以通过在 Prompt 调用中添加新的、针对请求的特殊选项来 override 默认选项:spring-doc.cadn.net.cn

var options = BedrockChatOptions.builder()
        .model("anthropic.claude-haiku-4-5-20251001-v1:0")
        .temperature(0.6)
        .maxTokens(300)
        .toolCallbacks(List.of(FunctionToolCallback.builder("getCurrentWeather", new WeatherService())
            .description("Get the weather in location. Return temperature in 36°F or 36°C format. Use multi-turn if needed.")
            .inputType(WeatherService.Request.class)
            .build()))
        .build();

String response = ChatClient.create(this.chatModel)
    .prompt("What is current weather in Amsterdam?")
    .options(options)
    .call()
    .content();

提示缓存

AWS Bedrock的提示缓存功能允许您缓存频繁使用的提示以减少成本并提高重复交互中的响应时间。 当您缓存一个提示时,后续的相同请求可以重新使用缓存内容,显著减少了输入Tokens的处理数量。spring-doc.cadn.net.cn

支持的模型spring-doc.cadn.net.cn

提示缓存功能在Claude 3.x、Claude 4.x和亚马逊Nova模型中被支持,这些模型可通过AWS Bedrock获得。spring-doc.cadn.net.cn

不同模型的缓存有效性的最小字节数有所不同: - Claude Sonnet 4及大多数模型:1024+ tokens - 模型特定要求可能有所不同 - 参阅AWS Bedrock文档spring-doc.cadn.net.cn

缓存策略

Spring AI提供战略级缓存放置策略通过BedrockCacheStrategy枚举实现:spring-doc.cadn.net.cn

该战略性的方法在不超出AWS Bedrock的4个断点限制的情况下,确保了最优缓存断点放置。spring-doc.cadn.net.cn

亚马逊 Nova 限制spring-doc.cadn.net.cn

亚马逊诺瓦系列(包括诺瓦微、轻、精、极版)仅支持缓存 systemmessages 内容。他们不支持缓存 toolsspring-doc.cadn.net.cn

如果尝试使用TOOLS_ONLYSYSTEM_AND_TOOLS策略配合牛蛙模型,亚马逊将返回一个ValidationException。使用SYSTEM_ONLY策略配合亚马逊牛蛙。spring-doc.cadn.net.cn

启用提示缓存Enabling Prompt Caching

设置为0在1上,并选择一个2以启用提示缓存。spring-doc.cadn.net.cn

系统专有缓存

最常见的用例是在多个请求中缓存系统指令:spring-doc.cadn.net.cn

// Cache system message content
ChatResponse response = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage("You are a helpful AI assistant with extensive knowledge..."),
            new UserMessage("What is machine learning?")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                .build())
            .maxTokens(500)
            .build()
    )
);

工具唯一缓存工具唯一缓存

缓存大型工具定义,同时保持系统提示的动态性(仅适用于Claude模型:)spring-doc.cadn.net.cn

// Cache tool definitions only
ChatResponse response = chatModel.call(
    new Prompt(
        "What's the weather in San Francisco?",
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.TOOLS_ONLY)
                .build())
            .toolCallbacks(weatherToolCallbacks)  // Large tool definitions
            .maxTokens(500)
            .build()
    )
);
亚马逊Claude模型支持此策略。亚马逊Nova模型将返回一个ValidationException

系统和工具缓存

缓存系统指令和工具定义,以最大化复用为目标(仅适用于Claude模型):spring-doc.cadn.net.cn

// Cache system message and tool definitions
ChatResponse response = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage("You are a weather analysis assistant..."),
            new UserMessage("What's the weather like in Tokyo?")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_AND_TOOLS)
                .build())
            .toolCallbacks(weatherToolCallbacks)
            .maxTokens(500)
            .build()
    )
);
该策略采用2个缓存断点(一个用于工具,一个用于系统)。仅适用于Claude模型。

会话历史缓存

缓存对话历史,用于多轮对话的聊天机器人和助手:spring-doc.cadn.net.cn

// Cache conversation history with ChatClient and memory
ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultSystem("You are a personalized career counselor...")
    .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory)
        .conversationId(conversationId)
        .build())
    .build();

String response = chatClient.prompt()
    .user("What career advice would you give me?")
    .options(BedrockChatOptions.builder()
        .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
        .cacheOptions(BedrockCacheOptions.builder()
            .strategy(BedrockCacheStrategy.CONVERSATION_HISTORY)
            .build())
        .maxTokens(500)
        .build())
    .call()
    .content();

使用ChatClient fluent API

String response = ChatClient.create(chatModel)
    .prompt()
    .system("You are an expert document analyst...")
    .user("Analyze this large document: " + document)
    .options(BedrockChatOptions.builder()
        .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
        .cacheOptions(BedrockCacheOptions.builder()
            .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
            .build())
        .build())
    .call()
    .content();

使用示例

这是一个完整的示例,演示了带成本跟踪的提示缓存:spring-doc.cadn.net.cn

// Create system content that will be reused multiple times
String largeSystemPrompt = "You are an expert software architect specializing in distributed systems...";
// (Ensure this is 1024+ tokens for cache effectiveness)

// First request - creates cache
ChatResponse firstResponse = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage(largeSystemPrompt),
            new UserMessage("What is microservices architecture?")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                .build())
            .maxTokens(500)
            .build()
    )
);

// Access cache-related token usage from metadata
Integer cacheWrite1 = (Integer) firstResponse.getMetadata()
    .getMetadata()
    .get("cacheWriteInputTokens");
Integer cacheRead1 = (Integer) firstResponse.getMetadata()
    .getMetadata()
    .get("cacheReadInputTokens");

System.out.println("Cache creation tokens: " + cacheWrite1);
System.out.println("Cache read tokens: " + cacheRead1);

// Second request with same system prompt - reads from cache
ChatResponse secondResponse = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage(largeSystemPrompt),  // Same prompt - cache hit
            new UserMessage("What are the benefits of event sourcing?")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                .build())
            .maxTokens(500)
            .build()
    )
);

Integer cacheWrite2 = (Integer) secondResponse.getMetadata()
    .getMetadata()
    .get("cacheWriteInputTokens");
Integer cacheRead2 = (Integer) secondResponse.getMetadata()
    .getMetadata()
    .get("cacheReadInputTokens");

System.out.println("Cache creation tokens: " + cacheWrite2); // Should be 0
System.out.println("Cache read tokens: " + cacheRead2);      // Should be > 0

计数器使用跟踪

AWS Bedrock 提供了通过响应提供的缓存特定度量。 缓存度量有三条获取方式:spring-doc.cadn.net.cn

为观测者处理器和元数据收集,通过本地TokenUsage对象访问缓存元数据:spring-doc.cadn.net.cn

import software.amazon.awssdk.services.bedrockruntime.model.TokenUsage;

ChatResponse response = chatModel.call(/* ... */);

// Access cache metrics from native TokenUsage object
TokenUsage tokenUsage = (TokenUsage) response.getMetadata()
    .getUsage()
    .getNativeUsage();

if (tokenUsage != null) {
    Integer cacheWrite = tokenUsage.cacheWriteInputTokens();
    Integer cacheRead = tokenUsage.cacheReadInputTokens();
    System.out.println("Cache write: " + cacheWrite + ", Cache read: " + cacheRead);
}

元数据映射(向后兼容)

缓存度量信息也可通过元数据映射获取,以确保兼容性保留。spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(/* ... */);

// Access cache metrics from metadata Map
Integer cacheWrite = (Integer) response.getMetadata()
    .getMetadata()
    .get("cacheWriteInputTokens");
Integer cacheRead = (Integer) response.getMetadata()
    .getMetadata()
    .get("cacheReadInputTokens");

缓存相关的特定度量指标包括:spring-doc.cadn.net.cn

当您首次发送缓存提示时: - cacheWriteInputTokens 将大于 0 - cacheReadInputTokens 将等于 0spring-doc.cadn.net.cn

当您再次发送相同的缓存提示时(在5分钟的TTL内): - cacheWriteInputTokens 将为 0 - cacheReadInputTokens 将大于 0spring-doc.cadn.net.cn

真实世界用例

通过在多个问题之间缓存文档内容,高效分析大型法律合同或合规文件:spring-doc.cadn.net.cn

// Load a legal contract (PDF or text)
String legalContract = loadDocument("merger-agreement.pdf"); // ~3000 tokens

// System prompt with legal expertise
String legalSystemPrompt = "You are an expert legal analyst specializing in corporate law. " +
    "Analyze the following contract and provide precise answers about terms, obligations, and risks: " +
    legalContract;

// First analysis - creates cache
ChatResponse riskAnalysis = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage(legalSystemPrompt),
            new UserMessage("What are the key termination clauses and associated penalties?")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                .build())
            .maxTokens(1000)
            .build()
    )
);

// Subsequent questions reuse cached document - 90% cost savings
ChatResponse obligationAnalysis = chatModel.call(
    new Prompt(
        List.of(
            new SystemMessage(legalSystemPrompt), // Same content - cache hit
            new UserMessage("List all financial obligations and payment schedules.")
        ),
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                .build())
            .maxTokens(1000)
            .build()
    )
);

批量代码审查

使用一致的评审标准处理多个代码文件,同时缓存评审指南:spring-doc.cadn.net.cn

// Define comprehensive code review guidelines
String reviewGuidelines = """
    You are a senior software engineer conducting code reviews. Apply these criteria:
    - Security vulnerabilities and best practices
    - Performance optimizations and memory usage
    - Code maintainability and readability
    - Testing coverage and edge cases
    - Design patterns and architecture compliance
    """;

List<String> codeFiles = Arrays.asList(
    "UserService.java", "PaymentController.java", "SecurityConfig.java"
);

List<String> reviews = new ArrayList<>();

for (String filename : codeFiles) {
    String sourceCode = loadSourceFile(filename);

    ChatResponse review = chatModel.call(
        new Prompt(
            List.of(
                new SystemMessage(reviewGuidelines), // Cached across all reviews
                new UserMessage("Review this " + filename + " code:\n\n" + sourceCode)
            ),
            BedrockChatOptions.builder()
                .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
                .cacheOptions(BedrockCacheOptions.builder()
                    .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                    .build())
                .maxTokens(800)
                .build()
        )
    );

    reviews.add(review.getResult().getOutput().getText());
}

// Guidelines cached after first request, subsequent reviews are faster and cheaper

客户支持与知识库

创建一个客户支持系统,该系统会缓存您的产品知识库,以提供一致、准确的响应:spring-doc.cadn.net.cn

// Load comprehensive product knowledge
String knowledgeBase = """
    PRODUCT DOCUMENTATION:
    - API endpoints and authentication methods
    - Common troubleshooting procedures
    - Billing and subscription details
    - Integration guides and examples
    - Known issues and workarounds
    """ + loadProductDocs(); // ~2500 tokens

@Service
public class CustomerSupportService {

    public String handleCustomerQuery(String customerQuery, String customerId) {
        ChatResponse response = chatModel.call(
            new Prompt(
                List.of(
                    new SystemMessage("You are a helpful customer support agent. " +
                        "Use this knowledge base to provide accurate solutions: " + knowledgeBase),
                    new UserMessage("Customer " + customerId + " asks: " + customerQuery)
                ),
                BedrockChatOptions.builder()
                    .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
                    .cacheOptions(BedrockCacheOptions.builder()
                        .strategy(BedrockCacheStrategy.SYSTEM_ONLY)
                        .build())
                    .maxTokens(600)
                    .build()
            )
        );

        return response.getResult().getOutput().getText();
    }
}

// Knowledge base is cached across all customer queries
// Multiple support agents can benefit from the same cached content

多租户SaaS应用

在为每个租户自定义系统提示的同时,跨不同租户缓存共享的工具定义:spring-doc.cadn.net.cn

// Shared tool definitions (cached once, used across all tenants)
List<FunctionToolCallback> sharedTools = createLargeToolRegistry(); // ~2000 tokens

// Tenant-specific configuration
@Service
public class MultiTenantAIService {

    public String processRequest(String tenantId, String userQuery) {
        // Load tenant-specific system prompt (changes per tenant)
        String tenantPrompt = loadTenantSystemPrompt(tenantId);

        ChatResponse response = chatModel.call(
            new Prompt(
                List.of(
                    new SystemMessage(tenantPrompt), // Tenant-specific, not cached
                    new UserMessage(userQuery)
                ),
                BedrockChatOptions.builder()
                    .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
                    .cacheOptions(BedrockCacheOptions.builder()
                        .strategy(BedrockCacheStrategy.TOOLS_ONLY)
                        .build())
                    .toolCallbacks(sharedTools) // Shared tools - cached
                    .maxTokens(500)
                    .build()
            )
        );

        return response.getResult().getOutput().getText();
    }
}

// Tools cached once, each tenant gets customized system prompt

最佳实践

  1. 选择正确的策略spring-doc.cadn.net.cn

  2. 满足Tokens要求:专注于缓存满足最低Tokens要求的内容(大多数模型的最低要求为1024个Tokens)。spring-doc.cadn.net.cn

  3. 重复使用相同内容:缓存最适合与提示内容的完全匹配。 即使是很小的更改也会需要一个新的缓存条目。spring-doc.cadn.net.cn

  4. 监控Tokens使用情况:使用元数据指标跟踪缓存有效性:spring-doc.cadn.net.cn

    Integer cacheWrite = (Integer) response.getMetadata().getMetadata().get("cacheWriteInputTokens");
    Integer cacheRead = (Integer) response.getMetadata().getMetadata().get("cacheReadInputTokens");
    if (cacheRead != null && cacheRead > 0) {
        System.out.println("Cache hit: " + cacheRead + " tokens saved");
    }
  5. 战略性缓存放置:该实现会根据您选择的策略自动将缓存断点放置在最佳位置,确保符合 AWS Bedrock 的 4 个断点限制。spring-doc.cadn.net.cn

  6. 缓存生命周期:AWS Bedrock 缓存具有固定的 5 分钟 TTL(生存时间)。 每次访问缓存都会重置计时器。spring-doc.cadn.net.cn

  7. 模型兼容性:请注意特定模型的限制:spring-doc.cadn.net.cn

  8. 工具稳定性:在使用 TOOLS_ONLYSYSTEM_AND_TOOLSCONVERSATION_HISTORY 策略时,确保工具保持稳定。 更改工具定义将导致所有下游缓存断点因级联失效而失效。spring-doc.cadn.net.cn

缓存失效与级联行为

AWS Bedrock 采用分层缓存模型,并支持级联失效机制:spring-doc.cadn.net.cn

缓存层次结构: Tools → System → Messagesspring-doc.cadn.net.cn

每一级的更改都会使该级别及其后续所有级别失效:spring-doc.cadn.net.cn

有哪些变化 工具缓存 系统缓存 消息缓存

工具spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

系统spring-doc.cadn.net.cn

✅ 有效spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

消息spring-doc.cadn.net.cn

✅ 有效spring-doc.cadn.net.cn

✅ 有效spring-doc.cadn.net.cn

❌ 无效spring-doc.cadn.net.cn

使用SYSTEM_AND_TOOLS策略的示例spring-doc.cadn.net.cn

// Request 1: Cache both tools and system
ChatResponse r1 = chatModel.call(
    new Prompt(
        List.of(new SystemMessage("System prompt"), new UserMessage("Question")),
        BedrockChatOptions.builder()
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_AND_TOOLS)
                .build())
            .toolCallbacks(tools)
            .build()
    )
);
// Result: Both caches created

// Request 2: Change only system prompt (tools same)
ChatResponse r2 = chatModel.call(
    new Prompt(
        List.of(new SystemMessage("DIFFERENT system prompt"), new UserMessage("Question")),
        BedrockChatOptions.builder()
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_AND_TOOLS)
                .build())
            .toolCallbacks(tools) // SAME tools
            .build()
    )
);
// Result: Tools cache HIT (reused), system cache MISS (recreated)

// Request 3: Change tools (system same as Request 2)
ChatResponse r3 = chatModel.call(
    new Prompt(
        List.of(new SystemMessage("DIFFERENT system prompt"), new UserMessage("Question")),
        BedrockChatOptions.builder()
            .cacheOptions(BedrockCacheOptions.builder()
                .strategy(BedrockCacheStrategy.SYSTEM_AND_TOOLS)
                .build())
            .toolCallbacks(newTools) // DIFFERENT tools
            .build()
    )
);
// Result: BOTH caches MISS (tools change invalidates everything downstream)

实现细节

Spring AI 中的提示缓存实现遵循以下关键设计原则:spring-doc.cadn.net.cn

  1. 战略性缓存放置:根据所选策略,缓存断点会自动放置在最佳位置,确保符合 AWS Bedrock 的 4 个断点限制。spring-doc.cadn.net.cn

  2. 提供商可移植性:缓存配置通过BedrockChatOptions进行,而非单独的消息,从而在切换不同AI提供商时保持兼容性。spring-doc.cadn.net.cn

  3. 线程安全:缓存断点跟踪采用线程安全机制实现,以正确处理并发请求。spring-doc.cadn.net.cn

  4. UNION 类型模式:AWS SDK 在添加缓存点时使用 UNION 类型,将其作为独立的块而非属性。 这与直接的 API 方法不同,但能确保类型安全和 API 合规性。spring-doc.cadn.net.cn

  5. 增量缓存CONVERSATION_HISTORY 策略会在最后一条用户消息上设置缓存断点,从而实现增量缓存,使每次对话轮次都基于之前的已缓存前缀进行构建。spring-doc.cadn.net.cn

成本考虑

AWS Bedrock 提示缓存定价(近似值,因模型而异):spring-doc.cadn.net.cn

示例成本计算spring-doc.cadn.net.cn

// System prompt: 2000 tokens
// User question: 50 tokens

// Without caching (5 requests):
// Cost: 5 × (2000 + 50) = 10,250 tokens at base rate

// With caching (5 requests):
// Request 1: 2000 tokens × 1.25 (cache write) + 50 = 2,550 tokens
// Requests 2-5: 4 × (2000 × 0.10 (cache read) + 50) = 4 × 250 = 1,000 tokens
// Total: 2,550 + 1,000 = 3,550 tokens equivalent

// Savings: (10,250 - 3,550) / 10,250 = 65% cost reduction

工具调用

Bedrock Converse API 支持工具调用功能,允许模型在对话过程中使用工具。 以下是定义和使用基于 @Tool 的工具的示例:spring-doc.cadn.net.cn

public class WeatherService {

    @Tool(description = "Get the weather in location")
    public String weatherByLocation(@ToolParam(description= "City or state name") String location) {
        ...
    }
}

String response = ChatClient.create(this.chatModel)
        .prompt("What's the weather like in Boston?")
        .tools(new WeatherService())
        .call()
        .content();

您也可以将 java.util.function 包中的 beans 用作工具:spring-doc.cadn.net.cn

@Bean
@Description("Get the weather in location. Return temperature in 36°F or 36°C format.")
public Function<Request, Response> weatherFunction() {
    return new MockWeatherService();
}

String response = ChatClient.create(this.chatModel)
        .prompt("What's the weather like in Boston?")
        .toolNames("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

工具文档中查找更多信息。spring-doc.cadn.net.cn

结构化输出

AWS Bedrock 通过 JSON Schema 支持原生结构化输出,确保模型生成的响应严格符合您指定的结构。 此功能适用于 支持的模型,包括 Anthropic Claude 和 Amazon Nova。spring-doc.cadn.net.cn

使用ChatClient搭配原生结构化输出

使用结构化输出的最简单方法是借助 ChatClient 高级API和ENABLE_NATIVE_STRUCTURED_OUTPUT 顾问:spring-doc.cadn.net.cn

record ActorsFilms(String actor, List<String> movies) {}

ActorsFilms actorsFilms = ChatClient.create(chatModel).prompt()
    .options(ToolCallingChatOptions.builder()
        .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
        .build())
    .advisors(AdvisorParams.ENABLE_NATIVE_STRUCTURED_OUTPUT)
    .user("Generate the filmography for a random actor.")
    .call()
    .entity(ActorsFilms.class);

这种方法会自动:spring-doc.cadn.net.cn

直接使用outputSchema

为了获得更精细的控制,您可以直接在 BedrockChatOptions 上设置 JSON 模式:spring-doc.cadn.net.cn

String jsonSchema = """
        {
            "type": "object",
            "properties": {
                "actor": { "type": "string" },
                "movies": {
                    "type": "array",
                    "items": { "type": "string" }
                }
            },
            "required": ["actor", "movies"],
            "additionalProperties": false
        }
        """;

ChatResponse response = chatModel.call(
    new Prompt("Generate the filmography for a random actor.",
        BedrockChatOptions.builder()
            .model("us.anthropic.claude-haiku-4-5-20251001-v1:0")
            .outputSchema(jsonSchema)
            .build()));

String content = response.getResult().getOutput().getText();
AWS Bedrock 结构化输出在构建 OutputConfig 时内部使用固定的模式名称 response_schema。 该模式 JSON 直接传递给 AWS SDK 的 JsonSchemaDefinition

有关更多信息,请参阅结构化输出转换器文档。spring-doc.cadn.net.cn

多模态

多模态是指模型同时理解和处理来自多种来源的信息的能力,包括文本、图像、视频、PDF、DOC、HTML、MD 以及其他多种数据格式。spring-doc.cadn.net.cn

Bedrock Converse API 支持多模态输入,包括文本和图像输入,并可根据组合后的输入生成文本响应。spring-doc.cadn.net.cn

你需要一个支持多模态输入的模型,例如 Anthropic 的 Claude 或 Amazon 的 Nova 模型。spring-doc.cadn.net.cn

图片

对于支持视觉多模态的< a t="C0">模型,例如 Amazon Nova、Anthropic Claude、Llama 3.2 和 Bedrock Converse API,Amazon 允许您在有效载荷中包含多张图像。这些模型可以分析传入的图像并回答问题、对图像进行分类,以及根据提供的指令对图像进行总结。spring-doc.cadn.net.cn

目前,Bedrock Converse 支持 base64 编码的 image/jpegimage/pngimage/gifimage/webp 种 MIME 类型的图像。spring-doc.cadn.net.cn

Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。 它包含有关消息中媒体附件的数据和信息,使用 Spring 的 org.springframework.util.MimeType 和一个 java.lang.Object 来存储原始媒体数据。spring-doc.cadn.net.cn

以下是一个简单的代码示例,演示如何将用户文本与图像结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text("Explain what do you see on this picture?")
        .media(Media.Format.IMAGE_PNG, new ClassPathResource("/test.png")))
    .call()
    .content();

logger.info(response);

它以 test.png 图像作为输入:spring-doc.cadn.net.cn

Multimodal Test Image

以及文本消息“解释一下你在这张图片上看到了什么?”,并生成类似如下的回复:spring-doc.cadn.net.cn

The image shows a close-up view of a wire fruit basket containing several pieces of fruit.
...

视频

The Amazon Nova models allow you to include a single video in the payload, which can be provided either in base64 format or through an Amazon S3 URI.spring-doc.cadn.net.cn

目前,Bedrock Nova 支持 video/x-matroskavideo/quicktimevideo/mp4video/webmvideo/x-flvvideo/mpegvideo/x-ms-wmvvideo/3gpp 种 MIME 类型的视频。spring-doc.cadn.net.cn

Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。 它包含有关消息中媒体附件的数据和信息,使用 Spring 的 org.springframework.util.MimeType 和一个 java.lang.Object 来存储原始媒体数据。spring-doc.cadn.net.cn

以下是一个简单的代码示例,演示如何将用户文本与视频相结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text("Explain what do you see in this video?")
        .media(Media.Format.VIDEO_MP4, new ClassPathResource("/test.video.mp4")))
    .call()
    .content();

logger.info(response);

它以 test.video.mp4 图像作为输入:spring-doc.cadn.net.cn

Multimodal Test Video

以及文本消息“解释一下你在这个视频中看到了什么?”,并生成类似如下的回复:spring-doc.cadn.net.cn

The video shows a group of baby chickens, also known as chicks, huddled together on a surface
...

文档

对于某些模型,Bedrock 允许您通过 Converse API 的文档支持在有效负载中包含文档,该文档可以以字节形式提供。 文档支持有两种不同的变体,如下所述:spring-doc.cadn.net.cn

  • 文本文档类型(txt、csv、html、md 等),重点在于文本理解。这些用例包括基于文档的文本元素进行回答。spring-doc.cadn.net.cn

  • 媒体文档类型(pdf、docx、xlsx),重点在于基于视觉的理解来回答问题。这些用例包括根据图表、图形等进行问答。spring-doc.cadn.net.cn

目前,Anthropic 的 PDF 支持(测试版) 和 Amazon Bedrock Nova 模型支持文档多模态。spring-doc.cadn.net.cn

以下是一个简单的代码示例,演示如何将用户文本与媒体文档相结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text(
            "You are a very professional document summarization specialist. Please summarize the given document.")
        .media(Media.Format.DOC_PDF, new ClassPathResource("/spring-ai-reference-overview.pdf")))
    .call()
    .content();

logger.info(response);

它以 spring-ai-reference-overview.pdf 文档作为输入:spring-doc.cadn.net.cn

Multimodal Test PNG

与文本消息“您是一位非常专业的文档摘要专家。请对给定的文档进行摘要。”一起,并生成类似如下的回复:spring-doc.cadn.net.cn

**Introduction:**
- Spring AI is designed to simplify the development of applications with artificial intelligence (AI) capabilities, aiming to avoid unnecessary complexity.
...

示例控制器

创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-bedrock-converse 添加到您的依赖项中。spring-doc.cadn.net.cn

添加一个 application.properties 文件到 src/main/resourcesspring-doc.cadn.net.cn

spring.ai.bedrock.aws.region=eu-central-1
spring.ai.bedrock.aws.timeout=10m
spring.ai.bedrock.aws.access-key=${AWS_ACCESS_KEY_ID}
spring.ai.bedrock.aws.secret-key=${AWS_SECRET_ACCESS_KEY}
# session token is only required for temporary credentials
spring.ai.bedrock.aws.session-token=${AWS_SESSION_TOKEN}

spring.ai.bedrock.converse.chat.options.temperature=0.8
spring.ai.bedrock.converse.chat.options.top-k=15

以下是一个使用聊天模型的示例控制器:spring-doc.cadn.net.cn

@RestController
public class ChatController {

    private final ChatClient chatClient;

    @Autowired
    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", this.chatClient.prompt(message).call().content());
    }

    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return this.chatClient.prompt(message).stream().content();
    }
}