项目源码解析
前端代码:
<div class="container"><h1>Spring Cloud Alibaba AI Example</h1><form id="form"><label for="message">User Message:</label><input type="text" id="message" name="message" placeholder="Entry your question...(make api key is effective)!"><br><br><input type="submit" value="Send"></form><br><div id="loader" class="loader" style="display: none;"></div><div id="chat-box" class="chat-box"></div>
</div>
该代码引入一个form表单,供用户进行信息输入
chat-box为AI机器回复后,自动补充的div,可为用户展示对应的AI消息。
JavaScript代码
var loader = document.getElementById("loader");document.getElementById("form").addEventListener("submit", function(event) {event.preventDefault();var messageInput = document.getElementById("message");var message = messageInput.value;messageInput.value = "";var chatBox = document.getElementById("chat-box");var userMessage = document.createElement("div");userMessage.className = "message user-message";userMessage.textContent = "User: " + message;chatBox.appendChild(userMessage);chatBox.scrollTop = chatBox.scrollHeight;loader.style.display = "block";var xhr = new XMLHttpRequest();xhr.open("GET", "http://localhost:8080/ai/example?message=" + encodeURIComponent(message), true);xhr.onreadystatechange = function() {if (xhr.readyState === 4) {loader.style.display = "none";if (xhr.status === 200) {var response = xhr.responseText;var botMessage = document.createElement("div");botMessage.className = "message bot-message";var botMessageText = document.createElement("span");botMessageText.className = "message-text";botMessage.appendChild(botMessageText);botMessageText.innerHTML = marked.marked(response);chatBox.appendChild(botMessage);chatBox.scrollTop = chatBox.scrollHeight;} else if (xhr.status === 400) {var error = JSON.parse(xhr.responseText);var errorMessage = document.createElement("div");errorMessage.className = "message bot-message";errorMessage.textContent = "Bot: " + error.message;chatBox.appendChild(errorMessage);chatBox.scrollTop = chatBox.scrollHeight;} else {var errorMessage = document.createElement("div");errorMessage.className = "message bot-message";errorMessage.textContent = "Bot: Failed to connect to the backend service. Please make sure the backend service is running.";chatBox.appendChild(errorMessage);chatBox.scrollTop = chatBox.scrollHeight;}}};xhr.onloadstart = function() {loader.style.display = "block";};xhr.onloadend = function() {loader.style.display = "none";};xhr.send();
});
以上代码编写了一个前后端的请求方法,请求后端/example接口,当用户点击消息发送时候实时和后端接口进行交互,后台接口获取到请求后,根据AI大模型返回给前端消息。
后端代码
controller层
("tongYiSimpleServiceImpl")
private TongYiService tongYiSimpleService;("/example")
public String completion((value = "message", defaultValue = "Tell me a joke")String message
) {return tongYiSimpleService.completion(message);
}
("/stream")
public Map<String, String> streamCompletion((value = "message", defaultValue = "请告诉我西红柿炖牛腩怎么做?")String message
) {return tongYiSimpleService.streamCompletion(message);
}
service层
public interface TongYiService {/*** Hello World example.** @param message conversation content question.* @return AI answer.*/String completion(String message);}/*** Stream call.** @param message conversation content question.* @return AI answer.*/Map<String, String> streamCompletion(String message);
impl层
编写聊天服务实现类,由 Spring AI 自动注入 ChatClient、StreamingChatClient,ChatClient 屏蔽底层通义大模型交互细节。
class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {private final ChatClient chatClient;private final StreamingChatClient streamingChatClient; public TongYiSimpleServiceImpl(ChatClient chatClient, StreamingChatClient streamingChatClient) {this.chatClient = chatClient;this.streamingChatClient = streamingChatClient;}
} public String completion(String message) {Prompt prompt = new Prompt(new UserMessage(message));return chatClient.call(prompt).getResult().getOutput().getContent();} public Map<String, String> streamCompletion(String message) {StringBuilder fullContent = new StringBuilder();streamingChatClient.stream(new Prompt(message)).flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults())).map(content -> content.getOutput().getContent()).doOnNext(fullContent::append).last().map(lastContent -> Map.of(message, fullContent.toString())).block();log.info(fullContent.toString());return Map.of(message, fullContent.toString());}
public
结语
自此一个简单的Spring Cloud Alibaba AI的聊天机器人就集成好了,后续会继续跟进讲解如何实现文生图等其余AI功能。