|
6 | 6 | import java.io.OutputStreamWriter; |
7 | 7 | import java.net.HttpURLConnection; |
8 | 8 | import java.net.URL; |
9 | | -import org.springframework.beans.factory.annotation.Autowired; |
10 | | -import org.springframework.core.env.Environment; |
| 9 | +import org.springframework.beans.factory.annotation.Value; |
11 | 10 | import org.springframework.security.access.annotation.Secured; |
12 | 11 | import org.springframework.web.bind.annotation.PostMapping; |
13 | 12 | import org.springframework.web.bind.annotation.RequestBody; |
|
16 | 15 | import org.springframework.web.bind.annotation.RestController; |
17 | 16 |
|
18 | 17 | @RestController |
19 | | -@RequestMapping("/api") |
20 | | -public class ChatGptcontroller { |
| 18 | +@RequestMapping("/api/chat-gpt") |
| 19 | +public class ChatGptController { |
21 | 20 |
|
22 | | - @Autowired |
23 | | - Environment appProperties; |
| 21 | + @Value("${openai.api.key:}") |
| 22 | + private String openAiApiKey; |
| 23 | + |
| 24 | + @Value("${openai.chat.api.url:https://api.openai.com/v1/chat/completions}") |
| 25 | + private String openAiChatApiUrl; |
24 | 26 |
|
25 | 27 | @ResponseBody |
26 | 28 | @Secured("ROLE_USER") |
27 | | - @PostMapping("/chat-gpt") |
| 29 | + @PostMapping |
28 | 30 | protected String sendChatMessage(@RequestBody String body) { |
29 | | - String openaiApiKey = appProperties.getProperty("OPENAI_API_KEY"); |
30 | | - if (openaiApiKey == null || openaiApiKey.isEmpty()) { |
| 31 | + if (openAiApiKey == null || openAiApiKey.isEmpty()) { |
31 | 32 | throw new RuntimeException("OPENAI_API_KEY is not set"); |
32 | 33 | } |
33 | 34 | try { |
34 | | - URL url = new URL("https://api.openai.com/v1/chat/completions"); |
| 35 | + URL url = new URL(openAiChatApiUrl); |
35 | 36 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
36 | 37 | connection.setRequestMethod("POST"); |
37 | | - connection.setRequestProperty("Authorization", "Bearer " + openaiApiKey); |
| 38 | + connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey); |
38 | 39 | connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); |
39 | 40 | connection.setRequestProperty("Accept-Charset", "UTF-8"); |
40 | 41 | connection.setDoOutput(true); |
41 | 42 | OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); |
42 | 43 | writer.write(body); |
43 | 44 | writer.flush(); |
44 | 45 | writer.close(); |
45 | | - BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"ISO-8859-1")); |
| 46 | + BufferedReader br = new BufferedReader( |
| 47 | + new InputStreamReader(connection.getInputStream(), "UTF-8")); |
46 | 48 | String line; |
47 | 49 | StringBuffer response = new StringBuffer(); |
48 | 50 | while ((line = br.readLine()) != null) { |
|
0 commit comments