ChatMessage.java
1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.hjx.parent.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ChatMessage {
public ChatMessage() {
}
public ChatMessage(String role, Object content) {
this.role = role;
this.content = content;
}
public String role;
public Object content;
public static ChatMessage fromImage(String role, String text, String... urls) {
List<ContentItem> items = new ArrayList<>();
if (text != null && !text.isEmpty()) {
items.add(new ContentItem(ContentItem.TYPE_TEXT, text));
}
for (String it: urls) {
ContentItem.ContentImage image = new ContentItem.ContentImage(it);
items.add(new ContentItem(ContentItem.TYPE_IMAGE, image));
}
return new ChatMessage(role, items);
}
public String getTextContent() {
if (content == null) return null;
if (content instanceof String) return (String) content;
ContentItem item = firstText();
return item == null ? null : item.text;
}
private ContentItem firstText() {
if (!(content instanceof List<?>)) return null;
List<?> anyList = (List<?>) content;
return anyList.stream()
.map(ContentItem::reSerialize)
.filter(Objects::nonNull)
.findFirst().orElse(null);
}
}