@@ -220,6 +220,30 @@ def format_gemini_response(response: Any) -> List[FormattedMessage]:
220220 return output
221221
222222
223+ def extract_gemini_system_instruction (config : Any ) -> Optional [str ]:
224+ """
225+ Extract system instruction from Gemini config parameter.
226+
227+ Args:
228+ config: Config object or dict that may contain system instruction
229+
230+ Returns:
231+ System instruction string if present, None otherwise
232+ """
233+ if config is None :
234+ return None
235+
236+ # Handle different config formats
237+ if hasattr (config , "system_instruction" ):
238+ return config .system_instruction
239+ elif isinstance (config , dict ) and "system_instruction" in config :
240+ return config ["system_instruction" ]
241+ elif isinstance (config , dict ) and "systemInstruction" in config :
242+ return config ["systemInstruction" ]
243+
244+ return None
245+
246+
223247def extract_gemini_tools (kwargs : Dict [str , Any ]) -> Optional [Any ]:
224248 """
225249 Extract tool definitions from Gemini API kwargs.
@@ -237,6 +261,32 @@ def extract_gemini_tools(kwargs: Dict[str, Any]) -> Optional[Any]:
237261 return None
238262
239263
264+ def format_gemini_input_with_system (contents : Any , config : Any = None ) -> List [FormattedMessage ]:
265+ """
266+ Format Gemini input contents into standardized message format, including system instruction handling.
267+
268+ Args:
269+ contents: Input contents in various possible formats
270+ config: Config object or dict that may contain system instruction
271+
272+ Returns:
273+ List of formatted messages with role and content fields, with system message prepended if needed
274+ """
275+ formatted_messages = format_gemini_input (contents )
276+
277+ # Check if system instruction is provided in config parameter
278+ system_instruction = extract_gemini_system_instruction (config )
279+
280+ if system_instruction is not None :
281+ has_system = any (msg .get ("role" ) == "system" for msg in formatted_messages )
282+ if not has_system :
283+ from posthog .ai .types import FormattedMessage
284+ system_message : FormattedMessage = {"role" : "system" , "content" : system_instruction }
285+ formatted_messages = [system_message ] + list (formatted_messages )
286+
287+ return formatted_messages
288+
289+
240290def format_gemini_input (contents : Any ) -> List [FormattedMessage ]:
241291 """
242292 Format Gemini input contents into standardized message format for PostHog tracking.
0 commit comments