使用JAVA控制台程序访问文心一言API

本文中使用的模型为erine模型,其它模型的地址请根据官方文档改写。

在开始前您需要在pom文件中导入如下依赖(不唯一):

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

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20230618</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

定义全局变量, 此处的AK与SK是申请下来的密钥:

private static final String AK="";

private static final String SK="";
public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(60000, TimeUnit.SECONDS).readTimeout(60000,TimeUnit.SECONDS).build();

 接下来根据文档中的例子获取access_token:

static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + AK
                + "&client_secret=" + SK);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        assert response.body() != null;
        return new JSONObject(response.body().string()).getString("access_token");
    }

根据文档中要求的结构,构造返回给服务器的对象:

public class Message {
    private List<Map<String,String>> messages;

    public List<Map<String, String>> getMessages() {
        return messages;
    }

    public void setInfo(List<Map<String, String>> messages) {
        this.messages = messages;
    }

    @Override
    public String toString() {
        return "Message{" +
                "message=" + messages +
                '}';
    }
}

接下来是控制台主程序

public static void main(String[] args) throws IOException {
        String accessToken = getAccessToken();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Message message = new Message();
        List<Map<String,String>> mess = new ArrayList<>();
        String str="";
        System.out.println("成功建立链接!输入end后即可退出本次对话");
        do{

            System.out.print("用户:");
            str = br.readLine();
       if (Objects.equals(str, "end")) break; Map<String,String> a1 = new HashMap<>(); a1.put("role","user"); a1.put("content",str); mess.add(a1); message.setInfo(mess); String content = com.alibaba.fastjson.JSONObject.toJSONString(message); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, content); Request request = new Request.Builder() .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + accessToken) .method("POST", body) .addHeader("Content-Type", "application/json") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); assert response.body() != null; String result = new JSONObject(response.body().string()).getString("result"); System.out.print("回答:"); System.out.println(result); Map<String,String> a2 = new HashMap<>(); a2.put("role","assistant"); a2.put("content",result); mess.add(a2); } while(!str.equals("end")); System.out.println("您已退出本次对话"); System.exit(0); }

这只是一个非常简单的控制台程序,能实现够与文心一言进行语言对话。您可以在此基础上通过对response的解析实现对异常的处理,或更换其它模型实现图片的生成功能。

posted @ 2023-08-31 16:55  咸鱼划水  阅读(507)  评论(0编辑  收藏  举报