Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2024-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.agentscope.core.internal;

import io.agentscope.core.message.ContentBlock;
import io.agentscope.core.message.MessageMetadataKeys;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;
import io.agentscope.core.message.TextBlock;
import io.agentscope.core.message.ThinkingBlock;
import io.agentscope.core.model.GenerateOptions;
import java.util.List;
import java.util.Map;

/** Internal prompt-caching metadata protocol shared between Harness and model extensions. */
public final class PromptCacheMetadata {

/** Marks a request-only projection placed after durable conversation history. */
public static final String CACHE_CONTROL_PROJECTION = "_cache_control_projection";

private PromptCacheMetadata() {}

public static Boolean directive(Msg msg) {
Map<String, Object> metadata = msg == null ? null : msg.getMetadata();
if (metadata == null) {
return null;
}
Object directive = metadata.get(MessageMetadataKeys.CACHE_CONTROL);
return directive instanceof Boolean value ? value : null;
}

public static boolean hasConversationCacheControl(List<Msg> messages, GenerateOptions options) {
return (options != null && Boolean.TRUE.equals(options.getCacheControl()))
|| (messages != null
&& messages.stream()
.anyMatch(
msg ->
msg != null
&& msg.getRole() != MsgRole.SYSTEM
&& Boolean.TRUE.equals(directive(msg))));
}

public static Boolean projectionDirective(Msg msg, boolean preserveBoundaries) {
Map<String, Object> metadata = msg == null ? null : msg.getMetadata();
if (!preserveBoundaries
|| metadata == null
|| !Boolean.TRUE.equals(metadata.get(CACHE_CONTROL_PROJECTION))) {
return null;
}
Boolean directive = directive(msg);
return directive == null ? Boolean.FALSE : directive;
}

public static boolean isThinkingOnly(List<ContentBlock> blocks) {
return blocks != null
&& blocks.stream().anyMatch(ThinkingBlock.class::isInstance)
&& blocks.stream()
.allMatch(
block ->
block instanceof ThinkingBlock
|| (block instanceof TextBlock text
&& (text.getText() == null
|| text.getText().isEmpty())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,8 @@ private MessageMetadataKeys() {
*
* <p>When set to {@code true}, the formatter adds <code>cache_control:
* {"type": "ephemeral"}</code> to this message's final content block during formatting. When
* set to {@code false}, the message is explicitly excluded from caching: no
* <code>cache_control</code> is emitted for it,
* and the automatic cache control strategy configured via
* {@link io.agentscope.core.model.GenerateOptions#getCacheControl()} skips it.
* set to {@code false}, automatic placement skips this message when selecting a breakpoint.
* A later breakpoint can still cache a prefix containing this message.
*
* <p>Explicitly marked messages (either {@code true} or {@code false}) take priority over the
* automatic strategy — they will not be overwritten.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import io.agentscope.extensions.model.anthropic.formatter.AnthropicChatFormatter;
import io.agentscope.extensions.model.anthropic.formatter.AnthropicResponseParser;
import io.agentscope.extensions.model.anthropic.formatter.AnthropicToolsHelper;
import io.agentscope.extensions.model.anthropic.internal.AnthropicFormatterCacheHooks;
import io.agentscope.extensions.model.anthropic.tool.AnthropicServerTool;
import java.net.Proxy;
import java.time.Instant;
Expand Down Expand Up @@ -315,31 +316,40 @@ protected Flux<ChatResponse> doStream(
conversationMessages = messages.subList(1, messages.size());
}

// Use formatter to convert Msg to Anthropic
// MessageParam
List<MessageParam> formattedMessages =
formatter.format(conversationMessages);

// Apply automatic cache control strategy
// (marks the last message to cache the conversation prefix)
if (cacheControlEnabled) {
formattedMessages =
formatter.applyCacheControl(formattedMessages);
}

for (MessageParam param : formattedMessages) {
paramsBuilder.addMessage(param);
boolean requestScopedCaching =
AnthropicFormatterCacheHooks.usesRequestScopedCacheControl(
formatter);
if (!requestScopedCaching) {
List<MessageParam> formattedMessages =
formatter.format(conversationMessages);
if (cacheControlEnabled) {
formattedMessages =
formatter.applyCacheControl(formattedMessages);
}
for (MessageParam param : formattedMessages) {
paramsBuilder.addMessage(param);
}
}

// Apply generation options via formatter
formatter.applyOptions(paramsBuilder, options, defaultOptions);

// Add client and server tools through one path so name
// validation, tool choice, and parallel tool use cover both.
formatter.applyTools(paramsBuilder, tools, serverTools);

// Create the request
MessageCreateParams params = paramsBuilder.build();
MessageCreateParams params;
if (requestScopedCaching) {
MessageCreateParams prefix =
paramsBuilder.messages(List.of()).build();
List<MessageParam> formattedMessages =
formatter.format(
conversationMessages,
effectiveOptions,
AnthropicToolsHelper
.countNonMessageCacheMarkers(prefix));
params =
AnthropicToolsHelper.applyCacheControlBudget(
prefix, formattedMessages, formatter);
} else {
params = paramsBuilder.build();
}
AnthropicToolsHelper.validateMessageHistory(params);

if (streamEnabled) {
Expand Down
Loading
Loading