JDK8项目简单快速接入AI大模型(无需强制使用JDK17)
最近AI风头越来越火,好多项目都需要接入AI接口,但Spring-AI强制绑定JDK17这些,导致以前的很多JDK8项目不太方便
找到个办法,使用AI4J来接入
1.本地部署Ollama,这个属于部署本地大模型,网上随便就能搜到,非本文重点(比如本站这位博主的博文1 使用ollama完成DeepSeek本地部署 - wrj的博客 - 博客园)
2.开始,引入ai4j依赖
<dependency>
<groupId>io.github.lnyo-cly</groupId>
<artifactId>ai4j-spring-boot-stater</artifactId>
<version>0.6.2</version>
</dependency>
3.配置yml文件

如果你是部署到本地就是
http://localhost:11434/
4.正常编写接口
controller类
import io.renren.modules.event.service.OllamaService; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author *** * @since 2025/2/18 * AI问答接口 */ @RestController @RequestMapping("event/ollama") @Api(tags = "ollama接口") public class OllamaController { @Autowired private OllamaService ollamaService; @GetMapping("/chat") public String getChatMessage(@RequestParam String question){ String chatMessage = ollamaService.getChatMessage(question); return chatMessage; } }
service类
/** * @author *** * @since 2025/2/19 */ public interface OllamaService { String getChatMessage(String question); }
Impl类
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletion; import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletionResponse; import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatMessage; import io.github.lnyocly.ai4j.service.IChatService; import io.github.lnyocly.ai4j.service.PlatformType; import io.github.lnyocly.ai4j.service.factor.AiService; import io.renren.modules.event.service.OllamaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author *** * @since 2025/2/19 */ @Service public class OllamaServiceImpl implements OllamaService { // 注入Ai服务 @Autowired private AiService aiService; @Override public String getChatMessage(String question) { // 获取OLLAMA的聊天服务 IChatService chatService = aiService.getChatService(PlatformType.OLLAMA); // 创建请求参数 ChatCompletion chatCompletion = ChatCompletion.builder() .model("deepseek-r1:32b") .message(ChatMessage.withUser(question)) .build(); System.out.println(chatCompletion); // 发送chat请求 ChatCompletionResponse chatCompletionResponse = null; try { chatCompletionResponse = chatService.chatCompletion(chatCompletion); } catch (Exception e) { throw new RuntimeException(e); } // 获取聊天内容和token消耗 String content = chatCompletionResponse.getChoices().get(0).getMessage().getContent(); long totalTokens = chatCompletionResponse.getUsage().getTotalTokens(); System.out.println("总token消耗: " + totalTokens); return content; } }
5.测试

...(扩展操作自行研究即可)

浙公网安备 33010602011771号