package com.izouma.nineth.web; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.kevinsawicki.http.HttpRequest; import com.izouma.nineth.exception.BusinessException; import com.izouma.nineth.service.SysConfigService; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/gpt3") @AllArgsConstructor @NoArgsConstructor public class GPTController { private SysConfigService sysConfigService; @RequestMapping("/text") public String text(@RequestParam String prompt) { String token = sysConfigService.getString("chatGPT_token"); Map params = new HashMap<>(); params.put("model", "text-davinci-003"); params.put("prompt", prompt); params.put("max_tokens", 2000); params.put("temperature", 1); HttpRequest request = HttpRequest.post("https://api.openai.com/v1/completions") .header("Authorization", "Bearer " + token) .contentType("application/json") .send(JSON.toJSONString(params)); int code = request.code(); String body = request.body(); JSONObject res = JSON.parseObject(body); if (code != 200) { throw new BusinessException(res.getJSONObject("error").getString("message")); } return res.getJSONArray("choices").getJSONObject(0).getString("text").trim(); } }