springboot3.x对接AI智谱清言

spring引入智谱清言ai包


 
     
         
             org.springframework.ai
             spring-ai-bom
             1.0.0-SNAPSHOT
             pom
             import
         
     
 

    
        
            spring-snapshots
            Spring Snapshots
            https://repo.spring.io/snapshot
            
                false
            
        
    

        
            org.springframework.ai
            spring-ai-starter-model-zhipuai
            
                
                    io.swagger.core.v3
                    swagger-annotations
                
            
        

这里如果使用了springdoc/swagger,需要exclude这个包,不然会出现包冲突,导致项目启动失败

spring新增智谱清言ai配置

  ai:
    zhipuai:
      api-key: xxxx # 你自己的智谱清言key
      base-url: https://open.bigmodel.cn/api/paas
      chat:
        options:
          model: glm-4-flash # 免费模型
		  # model: glm-4-plus #付费模型
          temperature: 0.5  # 响应随机性

定义智谱清言AI配置类

@Configuration
public class ZhipuAiConfig {
    @Bean
    public 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;
    }
    
    @Override
    public String sendMessage(String message) {
        return chatClient.prompt().user(message).call().content();
    }
}

以上就完成了AiService类的编写,controller类可以通过调用sendMessage方法和智谱清言AI接口进行对话。

你可能感兴趣的:(人工智能,ai,springboot)