GPTController.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.izouma.nineth.web;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.github.kevinsawicki.http.HttpRequest;
  5. import com.izouma.nineth.exception.BusinessException;
  6. import com.izouma.nineth.service.SysConfigService;
  7. import lombok.AllArgsConstructor;
  8. import lombok.NoArgsConstructor;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. @RestController
  15. @RequestMapping("/gpt3")
  16. @AllArgsConstructor
  17. @NoArgsConstructor
  18. public class GPTController {
  19. private SysConfigService sysConfigService;
  20. @RequestMapping("/text")
  21. public String text(@RequestParam String prompt) {
  22. String token = sysConfigService.getString("chatGPT_token");
  23. Map<String, Object> params = new HashMap<>();
  24. params.put("model", "text-davinci-003");
  25. params.put("prompt", prompt);
  26. params.put("max_tokens", 2000);
  27. params.put("temperature", 1);
  28. HttpRequest request = HttpRequest.post("https://api.openai.com/v1/completions")
  29. .header("Authorization", "Bearer " + token)
  30. .contentType("application/json")
  31. .send(JSON.toJSONString(params));
  32. int code = request.code();
  33. String body = request.body();
  34. JSONObject res = JSON.parseObject(body);
  35. if (code != 200) {
  36. throw new BusinessException(res.getJSONObject("error").getString("message"));
  37. }
  38. return res.getJSONArray("choices").getJSONObject(0).getString("text").trim();
  39. }
  40. }