Java通过post请求调用openai接口

java版

模型请求demo
package test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import util.HttpUtil;


public class AiTest {
    /**
     * 聊天端点
     */
    private static String chatEndpoint = "http://xxx.xxx.xxx.xxx:7006/v1/chat/completions";
    /**
     * api密匙
     */
    private static String apiKey = "xxxx";


    public static void main(String[] args) throws Exception {

        //生成body
        JSONObject param = new JSONObject();
        param.put("model", "qwen-1.5-32b");
        param.put("temperature", "0.1");

        //messages就是通常发送给ai的会话信息
        JSONArray messages = new JSONArray();

        JSONObject message1 = new JSONObject();
        message1.put("role", "system");
        message1.put("content", "请帮我判断下面的查询sql存在下列问题:1.单表的时间查询在join之后。如果存在,请帮我优化为结果不变但效率更高的SQL");


        JSONObject message2 = new JSONObject();
        message2.put("role", "user");
        message2.put("content", "select a.user_type,b.user_name from a left join b on a.id=b.user_id where a.time>'2024-03-02'");

        messages.add(message1);
        messages.add(message2);

        param.put("messages", messages);

        //生成header
        JSONArray headers = new JSONArray();
        JSONObject header1 = new JSONObject();
        header1.put("key", "Authorization");
        header1.put("value", apiKey);
        headers.add(header1);

        //发送请求
        String result = HttpUtil.postWithJson(chatEndpoint, param.toString(), headers);

        System.out.println(result);

    }
}
 http工具类
package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

public class HttpUtil {
    public static String postWithJson(String url, String param, JSONArray header) throws ClientProtocolException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (!Strings.isNullOrEmpty(param)) {
            StringEntity entity = new StringEntity(param, Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        if (header != null) {
            header.forEach(r -> {
                JSONObject tm = (JSONObject) r;
                httpPost.setHeader(tm.getString("key"), tm.getString("value"));
            });
        }
        CloseableHttpResponse response = client.execute(httpPost);
        return getResult(response);
    }

    public static String doGet(String url, JSONArray param, JSONArray header) throws IOException, URISyntaxException {
        HttpClient client = HttpClientBuilder.create().build();
        URIBuilder builder = new URIBuilder(url);
        if (param != null) {
            param.forEach(r -> {
                JSONObject tm = JSON.parseObject(JSON.toJSONString(r));
                builder.addParameter(tm.getString("name"), tm.getString("value"));
            });
        }
        HttpGet httpGet = new HttpGet(builder.build());
        if (header != null) {
            header.forEach(r -> {
                JSONObject tm = JSON.parseObject(JSON.toJSONString(r));
                httpGet.setHeader(tm.getString("key"), tm.getString("value"));
            });
        }
        HttpResponse response = client.execute(httpGet);
        return getResult(response);
    }

    private static String getResult(HttpResponse response) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));
        StringBuffer sb = new StringBuffer();
        String line;
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        return sb.toString();
    }
}
返回
{
  "id": "cmpl-a9a3b9c5d14e48ee8cd60c4d2484d41b",
  "object": "chat.completion",
  "created": 1725951521,
  "model": "qwen-1.5-32b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "根据你的SQL查询,它看起来已经很优化了。这个查询首先根据`a.id = b.user_id`对表a和表b进行左连接,然后在连接后的结果中筛选出`a.time > '2024-03-02'`的记录。单表的时间查询(`a.time > '2024-03-02'`)是在join操作之前进行的,这意味着MySQL会先过滤掉时间不符合条件的行,然后再进行连接操作,这样可以减少连接的数据量,提高效率。\n\n如果你的表a和表b有大量数据,并且`a.time`和`b.user_id`都有索引,这个查询已经相当高效了。不过,为了确保最佳性能,你可以确保以下两点:\n\n1. 确保`a.time`字段有索引,因为这是你的查询条件。\n2. 确保`b.user_id`字段有索引,因为这是连接条件。\n\n如果这两个字段都已经有索引,那么这个查询已经很优化了。如果你还有其他表或者查询条件,可能需要根据具体情况进一步优化。如果没有其他信息,这个SQL查询已经是比较高效的。"
      },
      "logprobs": null,
      "finish_reason": "stop",
      "stop_reason": null
    }
  ],
  "usage": {
    "prompt_tokens": 79,
    "total_tokens": 328,
    "completion_tokens": 249
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值