GPTRemoteService.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package com.seeckg.knowledgegraph_backend.remote;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.springframework.http.MediaType;
  4. import org.springframework.stereotype.Service;
  5. import okhttp3.*;
  6. import java.io.IOException;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. @Service
  10. public class GPTRemoteService {
  11. public String getGPTAnswer(String question) throws IOException {
  12. String answer = "";
  13. OkHttpClient client = new OkHttpClient().newBuilder().build();
  14. MediaType mediaType = MediaType.parse("application/json");
  15. Map<String, String> input = new HashMap<String, String>();
  16. input.put("prompt", question);
  17. RequestBody body = RequestBody.create(mediaType, input.toString());
  18. Request request = new Request.Builder()
  19. .url("https://ai-talk.live/api/chat-process")
  20. .method("POST", body)
  21. .addHeader("Content-Type", "application/json")
  22. .build();
  23. Response response = client.newCall(request).execute();
  24. if (response.isSuccessful()) {
  25. String resp = response.body().string();
  26. JSONObject jsonObject = JSONObject.parseObject(resp);
  27. answer = jsonObject.getString("text");
  28. }
  29. else {
  30. throw new IOException("GPT error: " + response);
  31. }
  32. return answer;
  33. }
  34. }