@@ -516,14 +516,17 @@ def __init__(
516516 def _call_api (self , messages : list [dict | MessageBuilder ]) -> dict :
517517 input = []
518518
519- for msg in messages :
519+ sys_msg , other_msgs = self .filter_system_messages (messages )
520+ sys_msg_text = "\n " .join (c ['text' ] for m in sys_msg for c in m .content )
521+ for msg in other_msgs :
520522 input .extend (msg .prepare_message () if isinstance (msg , MessageBuilder ) else [msg ])
521523
522524 api_params : Dict [str , Any ] = {
523525 "model" : self .model_name ,
524526 "messages" : input ,
525527 "temperature" : self .temperature ,
526528 "max_tokens" : self .max_tokens ,
529+ "system" : sys_msg_text , # Anthropic API expects system message as a string
527530 ** self .extra_kwargs , # Pass tools, tool_choice, etc. here
528531 }
529532 if self .tools is not None :
@@ -535,6 +538,23 @@ def _call_api(self, messages: list[dict | MessageBuilder]) -> dict:
535538
536539 return response
537540
541+ @staticmethod
542+ def filter_system_messages (messages : list [dict | MessageBuilder ]) -> tuple [MessageBuilder ]:
543+ """Filter system messages from the list of messages."""
544+ # System message cannot have an image in the middle of the text sequences.
545+ # Images can be appended in the end of the system message.
546+
547+ sys_msgs , other_msgs = [], []
548+ for msg in messages :
549+ if isinstance (msg , MessageBuilder ) and msg .role == "system" :
550+ sys_msgs .append (msg )
551+ for c in msg .content :
552+ if c .get ("type" ) == "image" :
553+ raise TypeError ("System messages cannot contain images." )
554+ else :
555+ other_msgs .append (msg )
556+ return sys_msgs , other_msgs
557+
538558 def _parse_response (self , response : dict ) -> dict :
539559 result = LLMOutput (
540560 raw_response = response ,
0 commit comments