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
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
16 changes: 15 additions & 1 deletion shiny/ui/_chat_normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,28 @@ def can_normalize_chunk(self, chunk: Any) -> bool:
# The actual MessageStreamEvent is a generic, so isinstance() can't
# be used to check the type. Instead, we manually construct the relevant
# union of relevant classes...
return (
if (
isinstance(chunk, RawContentBlockDeltaEvent)
or isinstance(chunk, RawContentBlockStartEvent)
or isinstance(chunk, RawContentBlockStopEvent)
or isinstance(chunk, RawMessageDeltaEvent)
or isinstance(chunk, RawMessageStartEvent)
or isinstance(chunk, RawMessageStopEvent)
):
return True

# Older versions of the anthropic library don't have the beta prompt caching
# types, so we need to check for them separately. If this import fails or
# errors, then we'll end up in the Exception handler and return False.
from anthropic.types.beta.prompt_caching import (
RawPromptCachingBetaMessageStartEvent,
)

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))


except Exception:
return False

Expand Down
Loading