Skip to content

anthropic prompt caching for tool result and tool use#1141

Merged
VisargD merged 3 commits into
Portkey-AI:mainfrom
narengogi:chore/anthropic-prompt-caching-tool-result
Jun 24, 2025
Merged

anthropic prompt caching for tool result and tool use#1141
VisargD merged 3 commits into
Portkey-AI:mainfrom
narengogi:chore/anthropic-prompt-caching-tool-result

Conversation

@narengogi

@narengogi narengogi commented Jun 16, 2025

Copy link
Copy Markdown
Member

#1140

documentation for prompt caching from anthropic: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
https://docs.anthropic.com/en/api/messages#body-messages-content-cache-control

example payload

{
    "model": "claude-3-5-sonnet-20240620",
    "max_tokens": 200,
    "stream": false,
    "messages": [
        {
            "role": "user",
            "content": "Based on the temperature and time in California what do you suggest I wear?"
        },
        {
            "role": "assistant",
            "content": "Certainly! I'd be happy to provide you with the current temperature and time in San Francisco. To get this information, I'll need to use two separate tools. Let me fetch that data for you.",
            "tool_calls": [
                {
                    "id": "toolu_01BspjPLY4dtHkKGurn8q9A6",
                    "type": "function",
                    "function": {
                        "name": "get_current_temperature",
                        "arguments": ""
                    },
                    "cache_control": {
                        "type": "ephemeral"
                    }
                },
                {
                    "id": "toolu_014jEfKqGbfFvRaKfiauxgPv",
                    "type": "function",
                    "function": {
                        "name": "get_current_time",
                        "arguments": "{\"location\":\"San Francisco, CA\"}"
                    }
                }
            ]
        },
        {
            "role": "tool",
            "content": [
                {
                    "type": "text",
                    "text": "15 degrees",
                    "cache_control": {
                        "type": "ephemeral"
                    }
                }
            ],
            "tool_call_id": "toolu_01BspjPLY4dtHkKGurn8q9A6"
        },
        {
            "role": "tool",
            "content": "10 PM",
            "tool_call_id": "toolu_014jEfKqGbfFvRaKfiauxgPv"
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_current_temperature",
                "description": "Get the current temperature for a specific location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g., San Francisco, CA"
                        },
                        "unit": {
                            "type": "string",
                            "enum": [
                                "Celsius",
                                "Fahrenheit"
                            ],
                            "description": "The temperature unit to use. Infer this from the user's location."
                        }
                    },
                    "required": [
                        "location",
                        "unit"
                    ]
                }
            }
        },
        {
            "type": "function",
            "function": {
                "name": "get_current_time",
                "description": "Get the current time for a specific location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g., San Francisco, CA"
                        }
                    },
                    "required": [
                        "location"
                    ]
                }
            }
        }
    ]
}

@narengogi narengogi requested review from VisargD and csgulati09 June 16, 2025 14:07
@matterai-app

matterai-app Bot commented Jun 16, 2025

Copy link
Copy Markdown
Contributor

Code Quality new feature

Description

Summary By MatterAI MatterAI logo

🔄 What Changed

This pull request introduces support for Anthropic's prompt caching for tool results and tool use. Key changes include:

  • Type Definition Update: The content property within AnthropicToolResultContentItem has been expanded to accept a more complex structure (an array of objects with type, text, and cache_control properties) or a simple string, instead of just a string.
  • Assistant Message Transformation: The transformAssistantMessage function now includes a cache_control property in the tool_code object if it's present in the incoming toolCall.
  • Tool Message Transformation: The transformToolMessage function now directly passes msg.content without casting it to a string, accommodating the new complex content type for tool results.
  • Message Processing Order: The handling of tool role messages within AnthropicChatCompleteConfig has been reordered to appear earlier in the message processing logic.

🔍 Impact of the Change

These changes enable the system to leverage Anthropic's prompt caching capabilities for tool interactions, potentially improving performance and reducing token usage for repeated tool calls or results. It also enhances type safety and flexibility for tool result content.

📁 Total Files Changed

  • src/providers/anthropic/chatComplete.ts: 1 file changed.

🧪 Test Added

The PR description includes an example JSON payload demonstrating the new tool role message structure with complex content, implying manual or integration testing was performed to verify the changes. No explicit unit tests were mentioned as added.

🔒Security Vulnerabilities

No new security vulnerabilities were detected in the provided code changes.

Motivation

This PR is motivated by the need to implement Anthropic prompt caching for tool results and tool use, as referenced by #1140.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

How Has This Been Tested?

  • Unit Tests
  • Integration Tests
  • Manual Testing (Implied by example payload in PR body)

Screenshots (if applicable)

N/A

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Related Issues

#1140

Tip

Quality Recommendations

  1. Consider adding specific unit tests for the new cache_control property handling in transformAssistantMessage to ensure it's correctly applied under various conditions.

  2. For AnthropicToolResultContentItem.content, while the type widening is necessary, ensure that the msg.content coming into transformToolMessage is always validated against this new complex type structure to prevent runtime errors if unexpected content is received.

  3. The duplicated comment // even though anthropic supports images in tool results, openai doesn't support it yet could be refactored or placed in a more central location if this limitation applies broadly, or clarified if it's specific to this context.

Sequence Diagram

sequenceDiagram
    participant User
    participant AnthropicChatCompleteConfig
    participant transformAssistantMessage
    participant transformToolMessage
    participant AnthropicAPI

    User->>AnthropicChatCompleteConfig: Sends Chat Completion Request (messages)
    AnthropicChatCompleteConfig->>AnthropicChatCompleteConfig: Iterates through messages

    alt Message Role is 'assistant'
        AnthropicChatCompleteConfig->>transformAssistantMessage: Call transformAssistantMessage(msg: Message)
        transformAssistantMessage-->>AnthropicChatCompleteConfig: Returns AnthropicMessage (with tool_code and optional cache_control)
    end

    alt Message Role is 'tool'
        AnthropicChatCompleteConfig->>transformToolMessage: Call transformToolMessage(msg: Message)
        transformToolMessage-->>AnthropicChatCompleteConfig: Returns AnthropicMessage (with tool_result and potentially complex content)
    end

    AnthropicChatCompleteConfig->>AnthropicAPI: Sends Transformed Messages to /chat/completions
    AnthropicAPI-->>AnthropicChatCompleteConfig: Returns API Response
    AnthropicChatCompleteConfig-->>User: Returns Chat Completion Response
Loading

@matterai-app matterai-app Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds support for Anthropic prompt caching for tool results and tool use. The implementation looks good overall, but I have a few suggestions to improve error handling and documentation.

Comment on lines 44 to +46
type: 'tool_result';
tool_use_id: string;
content?: string;
content?:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Optional Recommendation

Issue: The cache_control property is added without validation or documentation.
Fix: Add JSDoc comments explaining the purpose and structure of the cache_control property.
Impact: Improves code maintainability and helps other developers understand the feature's purpose and usage.

Suggested change
type: 'tool_result';
tool_use_id: string;
content?: string;
content?:
type: 'tool_result';
tool_use_id: string;
/**
* Content for the tool result, which can include cache control directives
* to optimize API usage by caching responses when appropriate.
*
* @property {Object} cache_control - Controls caching behavior
* @property {string} cache_control.type - Type of caching directive
* @property {number} cache_control.ttl - Time to live in seconds
*/
content?:

Comment on lines +150 to +152
...(toolCall.cache_control && {
cache_control: toolCall.cache_control,
}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Optional Recommendation

Issue: The cache_control property is passed directly without validation.
Fix: Add validation to ensure cache_control has the expected structure before passing it to the API.
Impact: Prevents potential runtime errors if cache_control has an unexpected format.

Suggested change
...(toolCall.cache_control && {
cache_control: toolCall.cache_control,
}),
...(toolCall.cache_control && {
cache_control: validateCacheControl(toolCall.cache_control),
}),

Comment on lines +265 to +267
} else if (msg.role === 'tool') {
// even though anthropic supports images in tool results, openai doesn't support it yet
messages.push(transformToolMessage(msg));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Code Refactor

Issue: The comment about Anthropic supporting images in tool results is incomplete and could be more informative.
Fix: Expand the comment to provide more context about the current limitations and future compatibility.
Impact: Improves code documentation and helps other developers understand the implementation decisions.

Suggested change
} else if (msg.role === 'tool') {
// even though anthropic supports images in tool results, openai doesn't support it yet
messages.push(transformToolMessage(msg));
} else if (msg.role === 'tool') {
// Anthropic supports images in tool results, but OpenAI doesn't support it yet.
// We're transforming the tool message to ensure cross-provider compatibility.
messages.push(transformToolMessage(msg));

@VisargD VisargD merged commit d7a2686 into Portkey-AI:main Jun 24, 2025
2 checks passed
@matterai-app

matterai-app Bot commented Jun 24, 2025

Copy link
Copy Markdown
Contributor

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@jczstudios

Copy link
Copy Markdown

@VisargD the example posted is returning a 500 for me:
Screenshot 2025-06-27 at 3 04 34 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants