springboot3.x对接AI智谱清言
spring引入智谱清言ai包
<!--版本管理--><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>1.0.0-SNAPSHOT</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
<!-- Spring AI BOM 声明了特定版本的 Spring AI依赖项的推荐版本 --><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository></repositories>
<!-- 智谱清言AI --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-zhipuai</artifactId><exclusions><exclusion><groupId>io.swagger.core.v3</groupId><artifactId>swagger-annotations</artifactId></exclusion></exclusions></dependency>
这里如果使用了springdoc/swagger,需要exclude这个包,不然会出现包冲突,导致项目启动失败
spring新增智谱清言ai配置
ai:zhipuai:api-key: xxxx # 你自己的智谱清言keybase-url: https://open.bigmodel.cn/api/paaschat:options:model: glm-4-flash # 免费模型# model: glm-4-plus #付费模型temperature: 0.5 # 响应随机性
定义智谱清言AI配置类
@Configuration
public class ZhipuAiConfig {@Beanpublic ChatClient chatClient(ChatModel chatModel) {return ChatClient.builder(chatModel).build();}
}
AiService类
@Service
public class AiServiceImpl implements AiService{private final ChatClient chatClient;public AiCheckServiceImpl(ChatClient chatClient) {this.chatClient = chatClient;}@Overridepublic String sendMessage(String message) {return chatClient.prompt().user(message).call().content();}
}
以上就完成了AiService类的编写,controller类可以通过调用sendMessage方法和智谱清言AI接口进行对话。