-
Notifications
You must be signed in to change notification settings - Fork 468
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
base: main
Are you sure you want to change the base?
Changes from all commits
8d99df5
264e137
8b4b7ad
5daebc5
83db6b1
7a5bfe8
676ad12
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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,113 @@ 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, | ||
| **kwargs: Any, | ||
| ) -> 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. | ||
| **kwargs: Additional keyword arguments for future extensibility. | ||
|
|
||
| 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"} | ||
pgrayy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # 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, | ||
|
Member
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. Let's say that someone did override this before. I presume it would be broken now? Should we do a runtime check to see "if the method has 3 parameters, use only 3 args, else use 4+"?
Member
Author
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. They would be. I'm more on the side that we need to make these one-time light breaking changes. We made the mistake of not doing a proper audit of these when we launched, but doing this for the missing kwargs everywhere is going to be unmanageable |
||
| ) -> 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": | ||
|
Member
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. Is this new? Or is this just part of the cache support?
Member
Author
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. This is from openai, its basically us overriding the mapping of just the metadata case, then for the rest we use the "default" openai version format_chunk |
||
| usage_data: Usage = { | ||
| "inputTokens": event["data"].prompt_tokens, | ||
| "outputTokens": event["data"].completion_tokens, | ||
| "totalTokens": event["data"].total_tokens, | ||
| } | ||
|
|
||
| # Only LiteLLM over Anthropic supports cache write tokens | ||
| # 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 | ||
|
Member
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. TODO?
Member
Author
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. Copied from |
||
| }, | ||
| usage=usage_data, | ||
| ) | ||
| ) | ||
| # For all other cases, use the parent implementation | ||
| return super().format_chunk(event) | ||
|
|
||
| @override | ||
| async def stream( | ||
| self, | ||
|
|
@@ -139,6 +248,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 +258,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") | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.