Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Anthropic prompt caching #1755

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

wch
Copy link
Collaborator

@wch wch commented Nov 2, 2024

This change adds support for Anthopic's beta prompt caching feature.

@cpsievert
Copy link
Collaborator

Here's a minimal example derived https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching

from anthropic import AsyncAnthropic
from app_utils import load_dotenv

from shiny.express import ui

load_dotenv()
llm = AsyncAnthropic()

chat = ui.Chat(id="chat")
chat.ui()
chat.update_user_input(value="Analyze the major themes in 'Pride and Prejudice'")


@chat.on_user_submit
async def _():
    response = await llm.beta.prompt_caching.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1024,
        stream=True,
        system=[
            {
                "type": "text",
                "text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n",
            },
            {
                "type": "text",
                "text": "<the entire contents of 'Pride and Prejudice'>",
                "cache_control": {"type": "ephemeral"},
            },
        ],
        messages=[{"role": "user", "content": chat.user_input()}],
    )
    await chat.append_message_stream(response)

if isinstance(chunk, RawPromptCachingBetaMessageStartEvent):
return True

return False
Copy link
Collaborator

@cpsievert cpsievert Nov 4, 2024

Choose a reason for hiding this comment

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

This change to can_normalize_chunk() looks good.

If we want to also support this feature for the non-streaming case, we'll want to also update can_normalize() to know about PromptCachingBetaMessage (i.e., the return that you get with llm.beta.prompt_caching.messages.create(..., stream=False))

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.

2 participants