0


多种方式简单访问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
}'
  • 注意: - 有可能遇到 ”connect timed out“ ,使用命令配置系统代理 //主机ip地址-端口号 export http_proxy=“http://proxy-XXXXX” export https_proxy=“https://proxy-XXXXX”

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'

需创建的类

  • Prompt类
importcom.fasterxml.jackson.annotation.JsonProperty;publicclassPrompt{publicString model;publicString prompt;// 序列化时把符合java命名规范的maxTokens转化为接口能够识别的max_tokens@JsonProperty(value ="max_tokens")publicInteger maxTokens;publicInteger temperature;publicPrompt(String model,String prompt,Integer maxTokens,Integer temperature){this.model = model;this.prompt = prompt;this.maxTokens = maxTokens;this.temperature = temperature;}publicPrompt(){}@OverridepublicStringtoString(){return"Prompt{"+"model='"+ model +'\''+", prompt='"+ prompt +'\''+", maxTokens="+ maxTokens +", temperature="+ temperature +'}';}}
  • Choice类
importcom.fasterxml.jackson.annotation.JsonIgnoreProperties;importcom.fasterxml.jackson.annotation.JsonProperty;@JsonIgnoreProperties(ignoreUnknown =true)publicclassChoice{publicString text;publicInteger index;@JsonProperty(value ="finish_reason")publicString finishReason;@OverridepublicStringtoString(){return"Choice{"+"text='"+ text +'\''+", index="+ index +", finishReason='"+ finishReason +'\''+'}';}}
  • PromptResponse类
importjava.util.List;publicclassPromptResponse{publicString id;publicString object;publicLong created;publicString model;publicList<Choice> choices;publicUsage usage;@OverridepublicStringtoString(){return"PromptResponse{"+"id='"+ id +'\''+", object='"+ object +'\''+", created="+ created +", model='"+ model +'\''+", choices="+ choices +", usage="+ usage +'}';}}
  • OkHttpGpt类
importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.google.gson.Gson;importokhttp3.*;importjava.io.IOException;importjava.net.InetSocketAddress;importjava.net.Proxy;importjava.util.concurrent.TimeUnit;publicclassOkHttpGpt{privatestaticfinalString API_ENDPOINT ="https://api.openai.com/v1/completions";privatestaticfinalString API_KEY ="YOUR_API_KEY";publicstaticvoidmain(String[] args)throwsIOException{// 设置系统代理,port自行设置Proxy proxy =newProxy(Proxy.Type.HTTP,newInetSocketAddress("127.0.0.1", port));OkHttpClient client =newOkHttpClient.Builder().connectTimeout(1,TimeUnit.SECONDS).readTimeout(5,TimeUnit.SECONDS).proxy(proxy).build();MediaType mediaType =MediaType.parse("application/json");Prompt prompt =newPrompt("text-davinci-003","地球直径",50,0);Gson gson =newGson();// 使用gson序列化// String s = gson.toJson(prompt);// 使用Jackson序列化ObjectMapper objectMapper =newObjectMapper();String s1 = objectMapper.writeValueAsString(prompt);Request request =newRequest.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("---");}}

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'

方法

    • GptRetrofit类和GptService接口
importokhttp3.OkHttpClient;importretrofit2.Call;importretrofit2.Response;importretrofit2.Retrofit;importretrofit2.converter.gson.GsonConverterFactory;importretrofit2.http.Body;importretrofit2.http.Headers;importretrofit2.http.POST;importjava.io.IOException;importjava.net.InetSocketAddress;importjava.net.Proxy;importjava.util.concurrent.TimeUnit;publicclassGptRetrofit{// 为方便演示,不做异常处理publicstaticvoidmain(String[] args)throwsIOException{Proxy proxy =newProxy(Proxy.Type.HTTP,newInetSocketAddress("127.0.0.1", port));finalOkHttpClient client =newOkHttpClient.Builder().connectTimeout(5,TimeUnit.SECONDS).readTimeout(5,TimeUnit.SECONDS).proxy(proxy).writeTimeout(5,TimeUnit.SECONDS).build();Retrofit retrofit =newRetrofit.Builder().baseUrl("https://api.openai.com").client(client).addConverterFactory(GsonConverterFactory.create()).build();GptService service = retrofit.create(GptService.class);Prompt prompt =newPrompt("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("-------");}}interfaceGptService{@Headers({"Content-Type: application/json","Authorization: Bearer YOUR_API_KEY"})@POST("/v1/completions")Call<PromptResponse>prompt(@BodyPrompt prompt);}intln("-------");}}interfaceGptService{@Headers({"Content-Type: application/json","Authorization: Bearer YOUR_API_KEY"})@POST("/v1/completions")Call<PromptResponse>prompt(@BodyPrompt prompt);}
标签: gpt-3 java postman

本文转载自: https://blog.csdn.net/weixin_48577882/article/details/129391716
版权归原作者 原来,你是。。。 所有, 如有侵权,请联系我们删除。

“多种方式简单访问gpt-3接口”的评论:

还没有评论