当前位置:AIGC资讯 > AIGC > 正文

JAVA项目接入百度文心一言文本对话功能

依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.0.0</version>
        </dependency>

       

1.获取参数

从百度云获取固定参数

        String client_id = "usl...............";
        String client_secret = "T5xrE5k...............";

2.完整代码
 

package com.center.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.common.constants.RedisConstant;
import com.common.core.HttpRequestServer;
import com.common.redis.RedisOperation;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: some desc
 * @author: ccxt
 * @paramete: int
 * @date: 2023/12/9 10:48
 */
@Component
public class ChatGptWenUtil {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    private static  ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<>();


    /**
     * @param uid 用户id
     * @param redisOperation redis工具类
     * 用户 获取自己的token标识,因token数量有限,所以存放token时间较长
     */
    public static void getToken(Long uid,RedisOperation redisOperation) throws IOException {
        String client_id = "usl8CQ....................";
        String client_secret = "T5xrE.......................";
        String grant_type = "client_credentials";
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + client_id + "&client_secret=" + client_secret + "&grant_type=" + grant_type)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if (response.body()==null){
            throw new RuntimeException("accessToken 获取失败");
        }
        String string = response.body().string();
        JSONObject jsonObject = JSON.parseObject(string);
        String accessToken = (String) jsonObject.get("access_token");
        //将token放入redis中 设置27 天过期时间,原token一个月过期时间,token数量有限
        String key = RedisConstant.CACHE_SIGN + RedisConstant.USER_WEN_XIN_YI_YAN_TOKEN;
        redisOperation.hset(key,uid.toString(),accessToken, 27 * 24 * 3600);
    }

    /**
     * @param uid  用户 id
     * @param redisOperation redis工具类
     *从redis中获取用户的token,放入临时缓存中
     */
    private static void getTokenByMap(Long uid,RedisOperation redisOperation) {
        String key = RedisConstant.CACHE_SIGN + RedisConstant.USER_WEN_XIN_YI_YAN_TOKEN;
        Object o = redisOperation.hget(key,uid.toString());
        if (o !=null){
            map.put(uid, o.toString());
        }
    }

    /**
     * @param msg 对话消息
     * @param uid 用户 id
     * @param redisOperation redis工具类
     * @return {@code JSONObject }
     * redis中有改用户信息,从redis中获取该用户token,放入临时缓存中
     */
    public static JSONObject ChatGptDialogueCall(HashMap<String, String> msg, Long uid,RedisOperation redisOperation) throws IOException {
        ArrayList<HashMap> messages = new ArrayList<>();
        messages.add(msg);
        HashMap<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", messages);
        String outputStr = JSON.toJSONString(requestBody);
        String token = null;
        // 从缓存中获取token
        token = map.get(uid);
        if (StringUtils.isEmpty(token)) {
            // 从redis中获取token放入临时缓存中
            getTokenByMap(uid,redisOperation);
            token = map.get(uid);
            if (StringUtils.isEmpty(token)){
                // 调用百度云接口获取token放入redis中
                getToken(uid,redisOperation);
                getTokenByMap(uid,redisOperation);
                token = map.get(uid);
            }
        }
        JSONObject info = new JSONObject();
        String path = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + token;
        JSONObject object = HttpRequestServer.wenChatGpt(path, "POST", outputStr, "application/json");
        if (object.containsKey("error_code")) {
            info.put("error_code", object.getString("error_code"));
            info.put("error_msg", object.getString("error_msg"));
            return info;
        }
        String result = object.getString("result");
        info.put("uid", uid);
        info.put("result", result);
        return info;
    }

    /**
     * @param uid 用户 id
     * 用户 退出时 清除存放token临时缓存的方法
     */
    public static void deleteMapToken(Long uid){
        map.remove(uid);
    }

}

3.调用代码
 

        try {
            HashMap<String, String> map = new HashMap<>();
            // 固定参数
            map.put("role", "user");
            map.put("content", "对话内容");
            jsonObject = ChatGptWenUtil.ChatGptDialogueCall(map, uid, redisOperation);
        } catch (Exception e) {
            e.printStackTrace();
        }

更新时间 2024-04-10