1
1
package com .javaaidev .agent ;
2
2
3
+ import com .javaaidev .chatagent .model .ChatRequest ;
4
+ import com .javaaidev .chatagent .model .ChatResponse ;
5
+ import com .javaaidev .chatagent .model .TextContentPart ;
6
+ import com .javaaidev .chatagent .model .ThreadAssistantMessage ;
7
+ import com .javaaidev .chatagent .model .ThreadUserMessage ;
8
+ import java .util .List ;
9
+ import java .util .stream .Stream ;
3
10
import org .springframework .ai .chat .client .ChatClient ;
11
+ import org .springframework .ai .chat .messages .AssistantMessage ;
12
+ import org .springframework .ai .chat .messages .Message ;
13
+ import org .springframework .ai .chat .messages .UserMessage ;
4
14
import org .springframework .web .bind .annotation .PostMapping ;
5
15
import org .springframework .web .bind .annotation .RequestBody ;
6
16
import org .springframework .web .bind .annotation .RequestMapping ;
10
20
@ RequestMapping ("/chat" )
11
21
public class ChatAgentController {
12
22
13
- public record ChatRequest (String input ) {
14
-
15
- }
16
-
17
- public record ChatResponse (String output ) {
18
-
19
- }
20
23
21
24
private static final String SYSTEM_TEXT = "You are a chef who is proficient in various cuisines. Please answer users' questions about cooking." ;
22
25
private final ChatClient chatClient ;
@@ -27,10 +30,28 @@ public ChatAgentController(ChatClient.Builder builder) {
27
30
28
31
@ PostMapping
29
32
public ChatResponse chat (@ RequestBody ChatRequest request ) {
33
+ var messages = request .messages ().stream ().flatMap (message -> {
34
+ if (message instanceof ThreadUserMessage userMessage ) {
35
+ return userMessage .content ().stream ().map (part -> {
36
+ if (part instanceof TextContentPart textContentPart ) {
37
+ return new UserMessage (textContentPart .text ());
38
+ }
39
+ return null ;
40
+ });
41
+ } else if (message instanceof ThreadAssistantMessage assistantMessage ) {
42
+ return assistantMessage .content ().stream ().map (part -> {
43
+ if (part instanceof TextContentPart textContentPart ) {
44
+ return new AssistantMessage (textContentPart .text ());
45
+ }
46
+ return null ;
47
+ });
48
+ }
49
+ return Stream .of ();
50
+ }).toList ();
30
51
var output = chatClient .prompt ().system (SYSTEM_TEXT )
31
- .user ( request . input ( ))
52
+ .messages ( messages . toArray ( new Message [ 0 ] ))
32
53
.call ()
33
54
.content ();
34
- return new ChatResponse (output );
55
+ return new ChatResponse (List . of ( new TextContentPart ( output )) );
35
56
}
36
57
}
0 commit comments