message.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. # NOTE: this is not the same as EventSource
  39. # These are the roles in the LLM's APIs
  40. role: Literal['user', 'system', 'assistant', 'tool']
  41. content: list[TextContent | ImageContent] = Field(default_factory=list)
  42. cache_enabled: bool = False
  43. vision_enabled: bool = False
  44. # function calling
  45. # - tool calls (from LLM)
  46. tool_calls: list[ChatCompletionMessageToolCall] | None = None
  47. # - tool execution result (to LLM)
  48. tool_call_id: str | None = None
  49. name: str | None = None # name of the tool
  50. @property
  51. def contains_image(self) -> bool:
  52. return any(isinstance(content, ImageContent) for content in self.content)
  53. @model_serializer
  54. def serialize_model(self) -> dict:
  55. # We need two kinds of serializations:
  56. # - into a single string: for providers that don't support list of content items (e.g. no vision, no tool calls)
  57. # - into a list of content items: the new APIs of providers with vision/prompt caching/tool calls
  58. # NOTE: remove this when litellm or providers support the new API
  59. if self.cache_enabled or self.vision_enabled or self.tool_call_id is not None:
  60. return self._list_serializer()
  61. return self._string_serializer()
  62. def _string_serializer(self):
  63. content = '\n'.join(
  64. item.text for item in self.content if isinstance(item, TextContent)
  65. )
  66. return {'content': content, 'role': self.role}
  67. def _list_serializer(self):
  68. content: list[dict] = []
  69. role_tool_with_prompt_caching = False
  70. for item in self.content:
  71. d = item.model_dump()
  72. # We have to remove cache_prompt for tool content and move it up to the message level
  73. # See discussion here for details: https://github.com/BerriAI/litellm/issues/6422#issuecomment-2438765472
  74. if self.role == 'tool' and item.cache_prompt:
  75. role_tool_with_prompt_caching = True
  76. d.pop('cache_control')
  77. if isinstance(item, TextContent):
  78. content.append(d)
  79. elif isinstance(item, ImageContent) and self.vision_enabled:
  80. content.extend(d)
  81. ret: dict = {'content': content, 'role': self.role}
  82. if role_tool_with_prompt_caching:
  83. ret['cache_control'] = {'type': 'ephemeral'}
  84. if self.tool_call_id is not None:
  85. assert (
  86. self.name is not None
  87. ), 'name is required when tool_call_id is not None'
  88. ret['tool_call_id'] = self.tool_call_id
  89. ret['name'] = self.name
  90. if self.tool_calls:
  91. ret['tool_calls'] = self.tool_calls
  92. return ret