All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fi.evolver.ai.spring.chat.prompt.Message Maven / Gradle / Ivy

package fi.evolver.ai.spring.chat.prompt;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * @see fi.evolver.ai.spring.serialization.MessageSerializer
 * @see fi.evolver.ai.spring.serialization.MessageDeserializer
 */
public class Message {
	public enum Role {
		SYSTEM("system"),
		USER("user"),
		ASSISTANT("assistant");


		private final String code;

		Role(String code) {
			this.code = code;
		}

		@JsonValue
		public String getCode() {
			return code;
		}


		public static Role of(String code) {
			for (Role role: values()) {
				if (role.code.equals(code))
					return role;
			}
			throw new IllegalArgumentException("Invalid role '%s'".formatted(code));
		}
	}

	private final Role role;
	private final List content;

	public Message(Role role, List content) {
		this.role = role;
		this.content = content;
	}

	public Message(Role role, MessageContent content) {
		this(role, List.of(content));
	}

	public Message(Role role, String content) {
		this(role, MessageContent.text(content));
	}

	@JsonProperty("content")
	public List getContents() {
		return content;
	}

	@JsonIgnore
	public String getContent() {
		return String.join("\n", content.stream().map(MessageContent::asText).toList());
	}

	public Role getRole() {
		return role;
	}

	@JsonIgnore
	public boolean isSystem() {
		return role == Role.SYSTEM;
	}

	@JsonIgnore
	public boolean isUser() {
		return role == Role.USER;
	}

	@JsonIgnore
	public boolean isAssistant() {
		return role == Role.ASSISTANT;
	}

	@JsonIgnore
	public boolean isContent(Class contentType) {
		return content.size() == 1 && contentType.isInstance(content.get(0));
	}

	@Override
	public String toString() {
		return "Message [role=" + role + ", content=" + content + "]";
	}

	public static Message system(List content) {
		return new Message(Role.SYSTEM, content);
	}

	public static Message system(MessageContent content) {
		return new Message(Role.SYSTEM, content);
	}

	public static Message system(String content) {
		return new Message(Role.SYSTEM, content);
	}


	public static Message assistant(List content) {
		return new Message(Role.ASSISTANT, content);
	}

	public static Message assistant(MessageContent content) {
		return new Message(Role.ASSISTANT, content);
	}

	public static Message assistant(String content) {
		return new Message(Role.ASSISTANT, content);
	}


	public static Message user(List content) {
		return new Message(Role.USER, content);
	}

	public static Message user(MessageContent content) {
		return new Message(Role.USER, content);
	}

	public static Message user(String content) {
		return new Message(Role.USER, content);
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy