-
Notifications
You must be signed in to change notification settings - Fork 0
/
AiServiceChat.java
69 lines (60 loc) · 2.3 KB
/
AiServiceChat.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS dev.langchain4j:langchain4j:0.29.1
//DEPS dev.langchain4j:langchain4j-ollama:0.29.1
import java.util.*;
import java.util.function.*;
import dev.langchain4j.data.message.*;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.ollama.OllamaStreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.TokenStream;
public class AiServiceChat {
ChatbotAgent chatbotAgent;
private void setup() {
StreamingChatLanguageModel llm = OllamaStreamingChatModel.builder()
.baseUrl("http://localhost:11434/")
.modelName("mistral")
.build();
ChatMemory chatMemory = MessageWindowChatMemory.builder()
.maxMessages(20)
.id("default")
.build();
chatMemory.add(new SystemMessage("Respond briefly, like a backend developer."));
chatbotAgent = AiServices.builder(ChatbotAgent.class)
.streamingChatLanguageModel(llm)
.chatMemory(chatMemory)
.build();
}
public interface ChatbotAgent {
TokenStream respond(String userMessage);
}
private void streamingChat(Function<AiMessage, String> aiMessageHandler) {
try (var scanner = new Scanner(System.in)) {
System.out.print("user message to llm > ");
while (true) {
String line = scanner.nextLine();
if (line == null || line.isEmpty()) {
break;
}
chatbotAgent.respond(line)
.onNext(token -> System.out.print(token))
.onComplete(response -> {
aiMessageHandler.apply(response.content());
System.out.print("\nuser message to llm > ");
})
.onError(error -> System.out.println("\n... oops, something went wrong!"))
.start();
}
}
}
public static void main(String[] args) {
var chat = new AiServiceChat();
chat.setup();
chat.streamingChat(
aiMessage -> aiMessage.text()
);
System.exit(0);
}
}