message.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from enum import Enum
  2. from typing import Literal
  3. from litellm import ChatCompletionMessageToolCall
  4. from pydantic import BaseModel, Field, model_serializer
  5. class ContentType(Enum):
  6. TEXT = 'text'
  7. IMAGE_URL = 'image_url'
  8. class Content(BaseModel):
  9. type: str
  10. cache_prompt: bool = False
  11. @model_serializer
  12. def serialize_model(self):
  13. raise NotImplementedError('Subclasses should implement this method.')
  14. class TextContent(Content):
  15. type: str = ContentType.TEXT.value
  16. text: str
  17. @model_serializer
  18. def serialize_model(self):
  19. data: dict[str, str | dict[str, str]] = {
  20. 'type': self.type,
  21. 'text': self.text,
  22. }
  23. if self.cache_prompt:
  24. data['cache_control'] = {'type': 'ephemeral'}
  25. return data
  26. class ImageContent(Content):
  27. type: str = ContentType.IMAGE_URL.value
  28. image_urls: list[str]
  29. @model_serializer
  30. def serialize_model(self):
  31. images: list[dict[str, str | dict[str, str]]] = []
  32. for url in self.image_urls:
  33. images.append({'type': self.type, 'image_url': {'url': url}})
  34. if self.cache_prompt and images:
  35. images[-1]['cache_control'] = {'type': 'ephemeral'}
  36. return images
  37. class Message(BaseModel):
  38. role: Literal['user', 'system', 'assistant', 'tool']
  39. content: list[TextContent | ImageContent] = Field(default_factory=list)
  40. cache_enabled: bool = False
  41. vision_enabled: bool = False
  42. # function calling
  43. # - tool calls (from LLM)
  44. tool_calls: list[ChatCompletionMessageToolCall] | None = None
  45. # - tool execution result (to LLM)
  46. tool_call_id: str | None = None
  47. name: str | None = None # name of the tool
  48. @property
  49. def contains_image(self) -> bool:
  50. return any(isinstance(content, ImageContent) for content in self.content)
  51. @model_serializer
  52. def serialize_model(self) -> dict:
  53. content: list[dict] = []
  54. role_tool_with_prompt_caching = False
  55. for item in self.content:
  56. d = item.model_dump()
  57. # We have to remove cache_prompt for tool content and move it up to the message level
  58. # See discussion here for details: https://github.com/BerriAI/litellm/issues/6422#issuecomment-2438765472
  59. if self.role == 'tool' and item.cache_prompt:
  60. role_tool_with_prompt_caching = True
  61. d.pop('cache_control')
  62. if isinstance(item, TextContent):
  63. content.append(d)
  64. elif isinstance(item, ImageContent) and self.vision_enabled:
  65. content.extend(d)
  66. ret: dict = {'content': content, 'role': self.role}
  67. if role_tool_with_prompt_caching:
  68. ret['cache_control'] = {'type': 'ephemeral'}
  69. if self.tool_call_id is not None:
  70. assert (
  71. self.name is not None
  72. ), 'name is required when tool_call_id is not None'
  73. ret['tool_call_id'] = self.tool_call_id
  74. ret['name'] = self.name
  75. if self.tool_calls:
  76. ret['tool_calls'] = self.tool_calls
  77. return ret