Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
themeEmacs
titleGPTControllerjsGPTController.java
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Mono;

import java.io.*;

@RestController
public class GPTController {
    private static final String GPT_API_URL = "https://api.openai.com/v1/chat/completions";
    private static final String GPT_API_KEY = "API key";

    @PostMapping("/requestGPT")
    public SseEmitter requestGPT(@RequestBody String json) throws IOException {
        SseEmitter emitter = new SseEmitter((long)(5*60*1000));
        WebClient client = WebClient.create(GPT_API_URL);
        client.post()
                .header("Content-Type", "application/json")
                .header("Authorization", String.format("Bearer %s", GPT_API_KEY))
                .body(BodyInserters.fromValue(json))
                .exchangeToFlux(response -> {
                    if(response.statusCode().equals(HttpStatus.OK)){
                        return response.bodyToFlux(String.class);
                    } else {
                        return response.createException().flatMapMany(Mono::error);
                    }
                })
                .doOnNext(line -> {
                    try {
                        emitter.send(SseEmitter.event().data(line));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                })
                .doOnError(emitter::completeWithError)
                .doOnComplete(emitter::complete)
                .subscribe();
        return emitter;
    }
}

...