¶Ô±ÈÐÂÎļþ |
| | |
| | | package org.ruoyi.chat.service.chat.impl; |
| | | |
| | | import io.modelcontextprotocol.client.McpSyncClient; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.ruoyi.chat.config.ChatConfig; |
| | | import org.ruoyi.chat.enums.ChatModeType; |
| | | import org.ruoyi.chat.listener.SSEEventSourceListener; |
| | | import org.ruoyi.chat.service.chat.IChatService; |
| | | import org.ruoyi.common.chat.entity.chat.ChatCompletion; |
| | | import org.ruoyi.common.chat.entity.chat.Message; |
| | | import org.ruoyi.common.chat.openai.OpenAiStreamClient; |
| | | import org.ruoyi.common.chat.request.ChatRequest; |
| | | import org.ruoyi.domain.vo.ChatModelVo; |
| | | import org.ruoyi.service.IChatModelService; |
| | | import org.springframework.ai.chat.client.ChatClient; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Service; |
| | | import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; |
| | | |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * å¾çè¯å«æ¨¡å |
| | | */ |
| | | @Service |
| | | @Slf4j |
| | | public class ImageOpenAiServiceImpl implements IChatService { |
| | | |
| | | @Autowired |
| | | private IChatModelService chatModelService; |
| | | |
| | | private final ChatClient chatClient; |
| | | |
| | | public ImageOpenAiServiceImpl(ChatClient.Builder chatClientBuilder) { |
| | | this.chatClient = chatClientBuilder.build(); |
| | | } |
| | | |
| | | @Override |
| | | public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter) { |
| | | // 仿°æ®åºè·å image ç±»åçæ¨¡åé
ç½® |
| | | ChatModelVo chatModelVo = chatModelService.selectModelByCategory(ChatModeType.IMAGE.getCode()); |
| | | if (chatModelVo == null) { |
| | | log.error("æªæ¾å° image ç±»åçæ¨¡åé
ç½®"); |
| | | emitter.completeWithError(new IllegalStateException("æªæ¾å° image ç±»åçæ¨¡åé
ç½®")); |
| | | return emitter; |
| | | } |
| | | |
| | | // å建 OpenAI æµå®¢æ·ç«¯ |
| | | OpenAiStreamClient openAiStreamClient = ChatConfig.createOpenAiStreamClient(chatModelVo.getApiHost(), chatModelVo.getApiKey()); |
| | | List<Message> messages = chatRequest.getMessages(); |
| | | |
| | | // å建 SSE äºä»¶æºçå¬å¨ |
| | | SSEEventSourceListener listener = new SSEEventSourceListener(emitter, chatRequest.getUserId(), chatRequest.getSessionId()); |
| | | |
| | | // æå»ºèå¤©å®æè¯·æ± |
| | | ChatCompletion completion = ChatCompletion |
| | | .builder() |
| | | .messages(messages) |
| | | .model(chatModelVo.getModelName()) // ä½¿ç¨æ°æ®åºä¸é
ç½®çæ¨¡ååç§° |
| | | .stream(true) |
| | | .build(); |
| | | |
| | | // åèµ·æµå¼èå¤©å®æè¯·æ± |
| | | openAiStreamClient.streamChatCompletion(completion, listener); |
| | | |
| | | return emitter; |
| | | } |
| | | |
| | | |
| | | @Override |
| | | public String getCategory() { |
| | | return ChatModeType.IMAGE.getCode(); |
| | | } |
| | | } |