generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 461
feat(models): allow SystemContentBlocks in LiteLLMModel #1141
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
Open
dbschmigelski
wants to merge
4
commits into
strands-agents:main
Choose a base branch
from
dbschmigelski:litellm-caching
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,9 +14,10 @@ | |
| from typing_extensions import Unpack, override | ||
|
|
||
| from ..tools import convert_pydantic_to_tool_spec | ||
| from ..types.content import ContentBlock, Messages | ||
| from ..types.content import ContentBlock, Messages, SystemContentBlock | ||
| from ..types.event_loop import Usage | ||
| from ..types.exceptions import ContextWindowOverflowException | ||
| from ..types.streaming import StreamEvent | ||
| from ..types.streaming import MetadataEvent, StreamEvent | ||
| from ..types.tools import ToolChoice, ToolSpec | ||
| from ._validation import validate_config_keys | ||
| from .openai import OpenAIModel | ||
|
|
@@ -81,11 +82,12 @@ def get_config(self) -> LiteLLMConfig: | |
|
|
||
| @override | ||
| @classmethod | ||
| def format_request_message_content(cls, content: ContentBlock) -> dict[str, Any]: | ||
| def format_request_message_content(cls, content: ContentBlock, **kwargs: Any) -> dict[str, Any]: | ||
| """Format a LiteLLM content block. | ||
|
|
||
| Args: | ||
| content: Message content. | ||
| **kwargs: Additional keyword arguments for future extensibility. | ||
|
|
||
| Returns: | ||
| LiteLLM formatted content block. | ||
|
|
@@ -131,6 +133,111 @@ def _stream_switch_content(self, data_type: str, prev_data_type: str | None) -> | |
|
|
||
| return chunks, data_type | ||
|
|
||
| @override | ||
| @classmethod | ||
| def _format_system_messages( | ||
| cls, | ||
| system_prompt: Optional[str] = None, | ||
| *, | ||
| system_prompt_content: Optional[list[SystemContentBlock]] = None, | ||
| ) -> list[dict[str, Any]]: | ||
| """Format system messages for LiteLLM with cache point support. | ||
|
|
||
| Args: | ||
| system_prompt: System prompt to provide context to the model. | ||
| system_prompt_content: System prompt content blocks to provide context to the model. | ||
|
|
||
| Returns: | ||
| List of formatted system messages. | ||
| """ | ||
| # Handle backward compatibility: if system_prompt is provided but system_prompt_content is None | ||
| if system_prompt and system_prompt_content is None: | ||
| system_prompt_content = [{"text": system_prompt}] | ||
|
|
||
| system_content: list[dict[str, Any]] = [] | ||
| for block in system_prompt_content or []: | ||
| if "text" in block: | ||
| system_content.append({"type": "text", "text": block["text"]}) | ||
| elif "cachePoint" in block and block["cachePoint"].get("type") == "default": | ||
| # Apply cache control to the immediately preceding content block | ||
| # for LiteLLM/Anthropic compatibility | ||
| if system_content: | ||
| system_content[-1]["cache_control"] = {"type": "ephemeral"} | ||
|
|
||
| # Create single system message with content array rather than mulitple system messages | ||
| return [{"role": "system", "content": system_content}] if system_content else [] | ||
|
|
||
| @override | ||
| @classmethod | ||
| def format_request_messages( | ||
| cls, | ||
| messages: Messages, | ||
| system_prompt: Optional[str] = None, | ||
| *, | ||
| system_prompt_content: Optional[list[SystemContentBlock]] = None, | ||
| **kwargs: Any, | ||
| ) -> list[dict[str, Any]]: | ||
| """Format a LiteLLM compatible messages array with cache point support. | ||
|
|
||
| Args: | ||
| messages: List of message objects to be processed by the model. | ||
| system_prompt: System prompt to provide context to the model (for legacy compatibility). | ||
| system_prompt_content: System prompt content blocks to provide context to the model. | ||
| **kwargs: Additional keyword arguments for future extensibility. | ||
|
|
||
| Returns: | ||
| A LiteLLM compatible messages array. | ||
| """ | ||
| formatted_messages = cls._format_system_messages(system_prompt, system_prompt_content=system_prompt_content) | ||
| formatted_messages.extend(cls._format_regular_messages(messages)) | ||
|
|
||
| return [message for message in formatted_messages if message["content"] or "tool_calls" in message] | ||
|
|
||
| @override | ||
| def format_chunk(self, event: dict[str, Any], **kwargs: Any) -> StreamEvent: | ||
| """Format a LiteLLM response event into a standardized message chunk. | ||
|
|
||
| This method overrides OpenAI's format_chunk to handle the metadata case | ||
| with prompt caching support. All other chunk types use the parent implementation. | ||
|
|
||
| Args: | ||
| event: A response event from the LiteLLM model. | ||
| **kwargs: Additional keyword arguments for future extensibility. | ||
|
|
||
| Returns: | ||
| The formatted chunk. | ||
|
|
||
| Raises: | ||
| RuntimeError: If chunk_type is not recognized. | ||
| """ | ||
| # Handle metadata case with prompt caching support | ||
| if event["chunk_type"] == "metadata": | ||
| usage_data: Usage = { | ||
| "inputTokens": event["data"].prompt_tokens, | ||
| "outputTokens": event["data"].completion_tokens, | ||
| "totalTokens": event["data"].total_tokens, | ||
| } | ||
|
|
||
| # Only LiteLLM over Anthropic supports cache cache write tokens | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: "cache cache ..." |
||
| # Waiting until a more general approach is available to set cacheWriteInputTokens | ||
|
|
||
| if tokens_details := getattr(event["data"], "prompt_tokens_details", None): | ||
| if cached := getattr(tokens_details, "cached_tokens", None): | ||
| usage_data["cacheReadInputTokens"] = cached | ||
| if creation := getattr(tokens_details, "cache_creation_tokens", None): | ||
| usage_data["cacheWriteInputTokens"] = creation | ||
|
|
||
| return StreamEvent( | ||
| metadata=MetadataEvent( | ||
| metrics={ | ||
| "latencyMs": 0, # TODO | ||
| }, | ||
| usage=usage_data, | ||
| ) | ||
| ) | ||
| # For all other cases, use the parent implementation | ||
| return super().format_chunk(event) | ||
|
|
||
| @override | ||
| async def stream( | ||
| self, | ||
|
|
@@ -139,6 +246,7 @@ async def stream( | |
| system_prompt: Optional[str] = None, | ||
| *, | ||
| tool_choice: ToolChoice | None = None, | ||
| system_prompt_content: Optional[list[SystemContentBlock]] = None, | ||
| **kwargs: Any, | ||
| ) -> AsyncGenerator[StreamEvent, None]: | ||
| """Stream conversation with the LiteLLM model. | ||
|
|
@@ -148,13 +256,16 @@ async def stream( | |
| tool_specs: List of tool specifications to make available to the model. | ||
| system_prompt: System prompt to provide context to the model. | ||
| tool_choice: Selection strategy for tool invocation. | ||
| system_prompt_content: System prompt content blocks to provide context to the model. | ||
| **kwargs: Additional keyword arguments for future extensibility. | ||
|
|
||
| Yields: | ||
| Formatted message chunks from the model. | ||
| """ | ||
| logger.debug("formatting request") | ||
| request = self.format_request(messages, tool_specs, system_prompt, tool_choice) | ||
| request = self.format_request( | ||
| messages, tool_specs, system_prompt, tool_choice, system_prompt_content=system_prompt_content | ||
| ) | ||
| logger.debug("request=<%s>", request) | ||
|
|
||
| logger.debug("invoking model") | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we know the other types? What if we set type to
block["cachePoint"].get("type", "ephemeral")?