Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix invalid message format when using OpenAIServerModel #584

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/smolagents/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,25 @@ def remove_stop_sequences(content: str, stop_sequences: List[str]) -> str:
return content


def has_image_in_messages(message_list: List[Dict[str, str]]) -> bool:
"""
Check if any message in the provided list contains an image element.

Args:
message_list (`list[dict[str, str]]`): List of chat messages.

Returns:
bool: True if an image element is found in any message, False otherwise.

"""
for message in message_list:
if isinstance(message["content"], list):
for element in message["content"]:
if element["type"] == "image":
return True
return False


def get_clean_message_list(
message_list: List[Dict[str, str]],
role_conversions: Dict[MessageRole, MessageRole] = {},
Expand Down Expand Up @@ -770,6 +789,7 @@ def __call__(
tools_to_call_from: Optional[List[Tool]] = None,
**kwargs,
) -> ChatMessage:
messages_contain_image = has_image_in_messages(messages)
completion_kwargs = self._prepare_completion_kwargs(
messages=messages,
stop_sequences=stop_sequences,
Expand All @@ -778,6 +798,7 @@ def __call__(
model=self.model_id,
custom_role_conversions=self.custom_role_conversions,
convert_images_to_image_urls=True,
flatten_messages_as_text=not messages_contain_image,
**kwargs,
)
response = self.client.chat.completions.create(**completion_kwargs)
Expand Down