SpringBoot实现简单AI问答(百度千帆)

第一步:注册并登录百度智能云,创建应用并获取自己的APIKey与SecretKey,参考网址:

点击去百度智能云

第二步:引入千帆的pom依赖

xml 复制代码
		<dependency>
            <groupId>com.baidubce</groupId>
            <artifactId>qianfan</artifactId>
            <version>0.0.9</version>
        </dependency>

第三步:创建前端需要的controller

java 复制代码
import com.baidubce.qianfan.core.auth.Auth;
import com.lx.vue.common.resp.ResultData;
import com.lx.vue.common.resp.ReturnCodeEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.builder.ChatBuilder;
import com.baidubce.qianfan.model.chat.ChatResponse;

@RestController
public class QianFanController {

    private static final String APIKey = "你的APIKey";
    private static final String SecretKey = "你的SecretKey";

    private static Qianfan qianfan = new Qianfan(Auth.TYPE_OAUTH,APIKey, SecretKey);


    @PostMapping("/ai/sendMsg")
    public ResultData sendMsg(@RequestBody String problem) {
        String result = null;
        try {
            result = chat(problem);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData(ReturnCodeEnum.RC500.getCode(),"服务暂不可用",null);
        }
        return new ResultData(ReturnCodeEnum.RC200.getCode(),ReturnCodeEnum.RC200.getMessage(),result);
    }

    private static String chat(String problem) {
        ChatBuilder bulder = qianfan.chatCompletion()
                .model("ERNIE-Speed-8K");//你要使用的大模型款式,最好和我一样,其他的很有可能是收费的
            bulder.addMessage("user",problem);//你的问题  
        ChatResponse response = bulder.execute();
        return response.getResult();
    }
}

第四步:前端进行调用,并动态将自己的问题与AI的回答填入Vue页面

相关推荐
醉殇姒若梦遗年1 小时前
怎么用idea打jar包
java·intellij-idea·jar
林九生1 小时前
【Docker】Docker环境下快速部署Ollama与Open-WebUI:详细指南
java·docker·eureka
Aric_Jones2 小时前
lua入门语法,包含安装,注释,变量,循环等
java·开发语言·git·elasticsearch·junit·lua
Akiiiira2 小时前
【日撸 Java 三百行】Day 12(顺序表(二))
java·开发语言
Chase_Mos6 小时前
Spring 必会之微服务篇(1)
java·spring·微服务
小林学习编程8 小时前
SpringBoot校园失物招领信息平台
java·spring boot·后端
撸码到无法自拔8 小时前
docker常见命令
java·spring cloud·docker·容器·eureka
愿你天黑有灯下雨有伞8 小时前
Spring Boot整合Kafka实战指南:从环境搭建到消息处理全解析
spring boot·kafka·linq
heart000_18 小时前
IDEA 插件推荐:提升编程效率
java·ide·intellij-idea
Clf丶忆笙9 小时前
SpringBoot异步处理@Async深度解析:从基础到高阶实战
spring boot