一、文章前言
此文主要實現基于Springboot+微信小程序調用文心一言大模型實現AI聊天對話功能,使用Java作為后端語言進行支持,界面友好,開發簡單。



二、開發流程及工具準備
2.1、登錄百度智能云平臺,獲取 API Key 和 Secret Key兩個憑證
2.2、注冊微信公眾平臺賬號。
2.3、下載安裝IntelliJ IDEA(后端語言開發工具),Mysql數據庫,微信Web開發者工具。
三、開發步驟
1.創建maven project
先創建一個名為SpringBootDemo的項目,選擇【New Project】
然后在彈出的下圖窗口中,選擇左側菜單的【New Project】(注:和2022之前的idea版本不同,這里左側沒有【Maven】選項,不要選【Maven Archetype】!!!),輸入Name(項目名):SpringBootDemo,language選擇【java】,build system選擇【maven】,然后選擇jdk,我這里選的是jdk18.
然后點擊【Create】
2.在project下創建module
點擊右鍵選擇【new】—【Module…】
左側選擇【Spring initializr】,通過idea中集成的Spring initializr工具進行spring boot項目的快速創建。窗口右側:name可根據自己喜好設置,group和artifact和上面一樣的規則,其他選項保持默認值即可,【next】
Developer Tools模塊勾選【Spring Boot DevTools】,web模塊勾選【Spring Web】
此時,一個Springboot項目已經搭建完成,可開發后續功能
3.編寫一個消息實體類、Mapper、service(三層架構)
@Data
public class Chat {@TableId(type = IdType.AUTO)private Long id;private Long userId;private Long targetUserId;private LocalDateTime createTime;private String userName;private String targetUserName;private String content;}
由于我們使用mybatis-plus,所以簡單的增刪改查不用自己寫,框架自帶了,只需要實現或者繼承他的Mapper、Service
4.編寫調用ai服務類
//獲取AccessKey
public static String GetAccessToken()
{String url = "https://aip.baidubce.com/oauth/2.0/token";String params="grant_type=client_credentials&client_id=xxxx&client_secret=xxxxx";// 發送 POST 請求String response = HttpUtil.post(url, params);JSONObject json=JSONObject.parseObject(response);return json.getString("access_token");
}
5.創建控制器Controller
先創建Controller Package
創建一個Controller
輸入類名,選在【Class】
因為要編寫Rest風格的Api,要在Controller上標注@RestController注解
6.創建具體的Api接口
@RestController
public class DemoController {@RequestMapping("chat-gpt")public Map chat(String sender){String token= GetAccessToken();List<MessageDTO> messageDTOS=new ArrayList<>();messageDTOS.add(new MessageDTO("user",sender));Map<String, Object> map=new HashMap<>();map.put("user_id","");map.put("messages",messageDTOS);map.put("temperature",0.95);map.put("top_p",0.8);map.put("penalty_score",1);map.put("disable_search",false);map.put("enable_citation",false);map.put("stream",false);String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token="+token;String response = HttpUtil.createPost(url).header("Content-Type", "application/json").body(JSONObject.toJSONString(map)).execute().body();ReturnMap returnMap = new ReturnMap();returnMap.setData(JSONObject.parse(response));return returnMap.getreturnMap();}}
7.小程序代碼
3.20、在pages文件夾下面創建一個文件夾并新建對應的page文件,并實現聊天對話框樣式。
<view class="cu-chat" id="j_page"><view class="cu-item 'self'" wx:for="{{chatData}}"><view class="main"><view class="content shadow bg-green"><text>{{item.content}}</text></view></view><view class="cu-avatar radius" style="background-image:url(../../../images/cat.jpg)"></view><view class="date">{{item.createTime}}</view></view>
</view><view class="cu-bar foot input {{InputBottom!=0?'cur':''}}" style="bottom:{{InputBottom}}px"><view class="action"><text class="cuIcon-sound text-grey"></text></view><input class="solid-bottom" value="{{content}}" bindinput="formMsg" bindfocus="InputFocus" bindblur="InputBlur" adjust-position="{{false}}" focus="{{false}}" maxlength="300" cursor-spacing="10"></input><view class="action"><text class="cuIcon-emojifill text-grey"></text></view><button class="cu-btn bg-green shadow" bindtap="sendMsg">發送</button>
</view>
.cu-chat {display: flex;flex-direction: column;
}.cu-chat .cu-item {display: flex;padding: 30rpx 30rpx 70rpx;position: relative;
}.cu-chat .cu-item>.cu-avatar {width: 80rpx;height: 80rpx;
}.cu-chat .cu-item>.main {max-width: calc(100% - 260rpx);margin: 0 40rpx;display: flex;align-items: center;
}.cu-chat .cu-item>image {height: 320rpx;
}.cu-chat .cu-item>.main .content {padding: 20rpx;border-radius: 6rpx;display: inline-flex;max-width: 100%;align-items: center;font-size: 30rpx;position: relative;min-height: 80rpx;line-height: 40rpx;text-align: left;
}.cu-chat .cu-item>.main .content:not([class*="bg-"]) {background-color: var(--white);color: var(--black);
}.cu-chat .cu-item .date {position: absolute;font-size: 24rpx;color: var(--grey);width: calc(100% - 320rpx);bottom: 20rpx;left: 160rpx;
}.cu-chat .cu-item .action {padding: 0 30rpx;display: flex;align-items: center;
}.cu-chat .cu-item>.main .content::after {content: "";top: 27rpx;transform: rotate(45deg);position: absolute;z-index: 100;display: inline-block;overflow: hidden;width: 24rpx;height: 24rpx;left: -12rpx;right: initial;background-color: inherit;
}.cu-chat .cu-item.self>.main .content::after {left: auto;right: -12rpx;
}
3.22、準備兩張頭像,在WXML中根據對應的用戶名判斷聊天記錄是否是自己發出,并賦對應的class樣式,后續這個步驟可以直接在接口返回的數據中進行判斷,請求查詢列表的接口將用戶token作為參數傳輸過去即可。


<view class="cu-chat" id="j_page"><view class="cu-item {{item.userId=='2'?'self':''}}" wx:for="{{chatData}}"><view class="cu-avatar radius" style="background-image:url(../../../images/cat.jpg)" wx:if="{{item.userId=='1'}}"></view><view class="main"><view class="content shadow {{item.userId=='1'?'bg-green':''}}"><text>{{item.content}}</text></view></view><view class="cu-avatar radius" style="background-image:url(../../../images/dog.jpg)" wx:if="{{item.userId=='2'}}"></view><view class="date">{{item.createTime}}</view></view>
</view>
3.23、這里需要注意的是,我們需要在每次發送消息后將頁面內容定位在底部,一直保持一個閱讀最新消息的狀態。
wx.pageScrollTo({scrollTop: 9999
})