当前位置:   article > 正文

多种方式简单访问gpt-3接口

gpt-3接口

java多种方式简单访问gpt-3接口

使用的方式

curl命令

  • 官方文档找到示例,修改YOUR_API_KEY并复制到Linux虚拟机中
curl https://api.openai.com/v1/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -d '{
  "model": "text-davinci-003",
  "prompt": "Say this is a test",
  "max_tokens": 7,
  "temperature": 0
}'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 注意:
    • 有可能遇到 ”connect timed out“ ,使用命令配置系统代理
     //主机ip地址-端口号
      export http_proxy=“http://proxy-XXXXX”
      export https_proxy=“https://proxy-XXXXX”
    
    • 1
    • 2
    • 3

postman或其他接口工具

  • 参照上方代码把请求方法和路径填入
  • 把-h的内容填入到postman的headers里,注意修改YOUR_API_KEY
  • 把-d对内容填入body里的raw选项下,类型选json
  • 注意:
    • 可能会出现”connect timed out“,在postman里设置代理模式即可

okhttp

依赖包

//https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

implementation 'com.fasterxml.jackson.core:jackson-core:2.13.4'

//https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.4.2'

//https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

implementation 'com.squareup.okhttp3:okhttp:4.10.0'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

需创建的类

import com.fasterxml.jackson.annotation.JsonProperty;

public class Prompt {
    public String model;
    public String prompt;
    // 序列化时把符合java命名规范的maxTokens转化为接口能够识别的max_tokens
    @JsonProperty(value = "max_tokens")
    public Integer maxTokens;
    public Integer temperature;

    public Prompt(String model, String prompt, Integer maxTokens, Integer temperature) {
        this.model = model;
        this.prompt = prompt;
        this.maxTokens = maxTokens;
        this.temperature = temperature;
    }

    public Prompt() {
    }

    @Override
    public String toString() {
        return "Prompt{" +
                "model='" + model + '\'' +
                ", prompt='" + prompt + '\'' +
                ", maxTokens=" + maxTokens +
                ", temperature=" + temperature +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Choice {
    public String text;
    public Integer index;
    @JsonProperty(value = "finish_reason")
    public String finishReason;

    @Override
    public String toString() {
        return "Choice{" +
                "text='" + text + '\'' +
                ", index=" + index +
                ", finishReason='" + finishReason + '\'' +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
import java.util.List;

public class PromptResponse {
    public String id;
    public String object;
    public Long created;
    public String model;
    public List<Choice> choices;
    public Usage usage;

    @Override
    public String toString() {
        return "PromptResponse{" +
                "id='" + id + '\'' +
                ", object='" + object + '\'' +
                ", created=" + created +
                ", model='" + model + '\'' +
                ", choices=" + choices +
                ", usage=" + usage +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;


public class OkHttpGpt {
    private static final String API_ENDPOINT = "https://api.openai.com/v1/completions";
    private static final String API_KEY = "YOUR_API_KEY";

    public static void main(String[] args) throws IOException {
      // 设置系统代理,port自行设置
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port));

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .proxy(proxy)
                .build();


        MediaType mediaType = MediaType.parse("application/json");
        Prompt prompt = new Prompt("text-davinci-003", "地球直径", 50, 0);
        Gson gson = new Gson();
        // 使用gson序列化
        // String s = gson.toJson(prompt);
        // 使用Jackson序列化
        ObjectMapper objectMapper = new ObjectMapper();
        String s1 = objectMapper.writeValueAsString(prompt);

        Request request = new Request.Builder()
                .url(API_ENDPOINT)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .post(RequestBody.create(mediaType, s1))
                .build();

        Call call = client.newCall(request);
        call.timeout().timeout(10, TimeUnit.SECONDS);
        Response response = call.execute();
        String responseBody = response.body().string();
        System.out.println(responseBody);
        // 使用gson反序列化
//        PromptResponse promptResponse = gson.fromJson(responseBody, PromptResponse.class);
//        System.out.println("---");
//        System.out.println(promptResponse);
//        System.out.println("---");
        // 使用Jackson反序列化
        PromptResponse promptResponse1 = objectMapper.readValue(responseBody, PromptResponse.class);

        System.out.println("---");
        System.out.println(promptResponse1);
        System.out.println("---");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

retrofit

依赖

    // Retrofit库
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    // gson解析,可以自行替换
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.0.1'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

public class GptRetrofit {
  // 为方便演示,不做异常处理
    public static void main(String[] args) throws IOException {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port));

        final OkHttpClient client = new OkHttpClient.Builder().
                connectTimeout(5, TimeUnit.SECONDS).
                readTimeout(5, TimeUnit.SECONDS).
                proxy(proxy).
                writeTimeout(5, TimeUnit.SECONDS).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.openai.com")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GptService service = retrofit.create(GptService.class);
        Prompt prompt = new Prompt("text-davinci-003","地球直径",50,0);
        Call<PromptResponse> promptResponseCall = service.prompt(prompt);
        Response<PromptResponse> execute = promptResponseCall.execute();
        PromptResponse body = execute.body();
        System.out.println("-------");
        System.out.println(body);
        System.out.println("-------");
    }
}
interface GptService {
    @Headers({
            "Content-Type: application/json",
            "Authorization: Bearer YOUR_API_KEY"
    })
    @POST("/v1/completions")
    Call<PromptResponse> prompt(@Body Prompt prompt);

}
intln("-------");
    }
}
interface GptService {
    @Headers({
            "Content-Type: application/json",
            "Authorization: Bearer YOUR_API_KEY"
    })
    @POST("/v1/completions")
    Call<PromptResponse> prompt(@Body Prompt prompt);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号