java-chatgpt

1.

https://www.jianshu.com/p/46dda2b38716

package com.demo.chatgpt.test;

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class ChatGptApiTest {
    //通过spring 的resttemplate调用chatgpt api
    private static final RestTemplate restTemplate = new RestTemplate();
    //openai的api key,可以写死或从配置文件读取,这里读取的环境变量
    private static final String apiKey = System.getenv("OPENAI_API_KEY");

    public static void main(String[] args) {
        final String question = "google和openai比,哪个公司更有潜力";
        final StringBuilder sb = new StringBuilder();
        while (true){
            //循环调用,将返回的内容附加到问题里,解决返回的答案被截断的问题
            AIResponse response = getAiResponse(question+"\n A:"+sb);
            if(response!= null ){
// 如果返回不为null,提取返回内容
                sb.append(CollectionUtil.getFirst(response.getChoices()).getText());
            }
            if(response == null || CollectionUtil.getFirst(response.getChoices()).finish()){
    //返回null,或者回答结束,退出循环
                break;
            }

        }

        log.info("result:{}",sb);


    }


    private static AIResponse getAiResponse(final String question){
        final Map<String,Object> data = Maps.newHashMap();
        data.put("model","text-davinci-003");
        data.put("prompt",question);
        data.put("temperature",0);
        data.put("max_tokens",50);

        log.info("apikey:{}",apiKey);
        if(StringUtils.isBlank(apiKey)){
            log.error("apikey is empty");
        }else {
            final URI uri = URI.create("https://api.openai.com/v1/completions");
            MultiValueMap<String,String> headers = new HttpHeaders();
            headers.add("Content-Type","application/json");
            headers.add("Authorization","Bearer "+apiKey);

            final RequestEntity<String> request = new RequestEntity<>(JsonUtils.toJson(data),headers,HttpMethod.POST, uri);
            final ResponseEntity<AIResponse> responseEntity = restTemplate.exchange(request, AIResponse.class);
            AIResponse responseEntityBody = responseEntity.getBody();
            log.info("{}",responseEntity);
            if(!Objects.isNull(responseEntityBody)){
                final AIResponseChoice first = CollectionUtil.getFirst(responseEntityBody.getChoices());
                if(!Objects.isNull(first)){
                    return responseEntityBody;
                }
            }else {
                log.info("{}",responseEntity);
            }
        }
        return null;
    }

    @Data
    public static class AIResponse{
        private List<AIResponseChoice> choices;
    }

    @Data
    public static class AIResponseChoice{
        private String text;
        @JsonProperty("finish_reason")
        private String finishReason;

        public boolean finish(){
            return !Objects.equals("length",finishReason);
        }

    }


}

2.

https://zhuanlan.zhihu.com/p/612460401

<dependency>
        <groupId>com.theokanning.openai-gpt3-java</groupId>
        <artifactId>client</artifactId>
	<version>0.11.0</version>
</dependency>
public void sendMsg() {
	// 消息列表
	List<ChatMessage> list = new ArrayList<>();

	// 给chatGPT定义一个身份,是一个助手
	ChatMessage chatMessage = new ChatMessage();
	chatMessage.setRole("system");
	chatMessage.setContent("You are a helpful assistant.");
	list.add(chatMessage);

	// 定义一个用户身份,content是用户写的内容
	ChatMessage userMessage = new ChatMessage();
	userMessage.setRole("user");
	userMessage.setContent("hello");
	list.add(userMessage);

	ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .messages(list)
                    .model("gpt-3.5-turbo")
                    .build();
	OpenAiService service = new OpenAiService("your token");

	// chatCompletion 对象就是chatGPT响应的数据了
	ChatCompletionResult chatCompletion = service.createChatCompletion(request);
}

3.

https://article.itxueyuan.com/4608la

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ChatGPTExample {
  
  private static final String API_ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions";
  private static final String ACCESS_TOKEN = "<your-access-token>";
  
  public static void main(String[] args) throws IOException {
    // Create a new HTTP client
    CloseableHttpClient httpClient = HttpClients.createDefault();
    
    // Set the API request parameters
    String prompt = "Hello, how are you today?";
    int maxTokens = 60;
    double temperature = 0.7;
    double topP = 1.0;
    double frequencyPenalty = 0.5;
    double presencePenalty = 0.0;
    
    // Create a new HTTP POST request
    HttpPost httpPost = new HttpPost(API_ENDPOINT);
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
    
    // Set the request body as a JSON string
    ObjectMapper objectMapper = new ObjectMapper();
    String requestBody = objectMapper.writeValueAsString(
        new ChatGPTRequest(prompt, maxTokens, temperature, topP, frequencyPenalty, presencePenalty));
    httpPost.setEntity(new StringEntity(requestBody));
    
    // Send the API request and parse the response
    CloseableHttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    EntityUtils.consume(entity);
    response.close();
    
    JsonNode responseJson = objectMapper.readTree(responseBody);
    String responseText = responseJson.get("choices").get(0).get("text").asText();
    
    // Print the response text to the console
    System.out.println("ChatGPT response: " + responseText);
    
    // Close the HTTP client
    httpClient.close();
  }
  
  static class ChatGPTRequest {
    public String prompt;
    public int max_tokens;
    public double temperature;
    public double top_p;
    public double frequency_penalty;
    public double presence_penalty;
    
    public ChatGPTRequest(String prompt, int maxTokens, double temperature, double topP,
        double frequencyPenalty, double presencePenalty) {
      this.prompt = prompt;
      this.max_tokens = maxTokens;
      this.temperature = temperature;
      this.top_p = topP;
      this.frequency_penalty = frequencyPenalty;
      this.presence_penalty = presencePenalty;
    }
  }
}

首先创建了一个HTTP客户端,然后设置了API的访问端点和访问密钥。接着,我们设置了对话的文本和一些生成对话的参数,并使用Jackson库将请求参数转换为JSON字符串。然后,我们创建了一个HTTP POST请求,并将JSON字符串设置为请求体。接着,我们使用HTTP客户端发送请求,并解析了响应。最后,我们使用Jackson库从响应JSON中提取生成的对话文本,并将其打印到控制台上。

4.

https://betheme.net/yidongkaifa/76935.html?action=onClick

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值