@@ -155,6 +155,53 @@ def _safe_json_serialize(obj) -> str:
155155 return str (obj )
156156
157157
158+ def _part_has_payload (part : types .Part ) -> bool :
159+ """Checks whether a Part contains usable payload for the model."""
160+ if part .text :
161+ return True
162+ if part .inline_data and part .inline_data .data :
163+ return True
164+ if part .file_data and (part .file_data .file_uri or part .file_data .data ):
165+ return True
166+ return False
167+
168+
169+ def _append_fallback_user_content_if_missing (
170+ llm_request : LlmRequest ,
171+ ) -> None :
172+ """Ensures there is a user message with content for LiteLLM backends.
173+
174+ Args:
175+ llm_request: The request that may need a fallback user message.
176+ """
177+ for content in reversed (llm_request .contents ):
178+ if content .role == "user" :
179+ parts = content .parts or []
180+ if any (_part_has_payload (part ) for part in parts ):
181+ return
182+ if not parts :
183+ content .parts = []
184+ content .parts .append (
185+ types .Part .from_text (
186+ text = "Handle the requests as specified in the System Instruction."
187+ )
188+ )
189+ return
190+ llm_request .contents .append (
191+ types .Content (
192+ role = "user" ,
193+ parts = [
194+ types .Part .from_text (
195+ text = (
196+ "Handle the requests as specified in the System"
197+ " Instruction."
198+ )
199+ ),
200+ ],
201+ )
202+ )
203+
204+
158205def _content_to_message_param (
159206 content : types .Content ,
160207) -> Union [Message , list [Message ]]:
@@ -818,6 +865,7 @@ async def generate_content_async(
818865 """
819866
820867 self ._maybe_append_user_content (llm_request )
868+ _append_fallback_user_content_if_missing (llm_request )
821869 logger .debug (_build_request_log (llm_request ))
822870
823871 messages , tools , response_format , generation_params = (
0 commit comments