这是indexloc提供的服务,不要输入任何密码
Skip to content

More user-friendly way to create image messages from local image files #58

@bertilmuth

Description

@bertilmuth

Creating an user image message from a URL is straight forward using UserMessage.buildImageMessage.

Creating an user image message from a local image file is much more tedious, here's some sample code:

public void postDiagramImage(String userMessageText, Path diagramImagePath) {
  List<ChatMessage> messages = ...
  UserMessage imageMessage = createImageMessage(userMessageText, diagramImagePath);
  messages.add(imageMessage);
  ...
}

private UserMessage createImageMessage(String userMessageText, Path imagePath) {
  ImageContent userMessageContent = new ImageContent(userMessageText);
  String imagePathString = imagePath.toAbsolutePath().toString();
  String extension = imagePathString.substring(imagePathString.lastIndexOf('.') + 1);
  String imageUrl = "data:image/" + extension + ";base64," + encodeImage(imagePath);
  ImageContent imageContent = new ImageContent(new ImageUrl(imageUrl));
  UserMessage imageMessage = new UserMessage(List.of(userMessageContent, imageContent));
  return imageMessage;
}
	
private String encodeImage(Path imagePath) {
  byte[] fileContent;
      try {
            fileContent = Files.readAllBytes(imagePath);
            return Base64.getEncoder().encodeToString(fileContent);
      } catch (IOException e){
        throw new RuntimeException(e);
      }
}

It would be great if code like this could be encapsulated, and provided to the user in a friendly manner.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions