如何在 Spring Boot中使用 OpenAI ChatGPT API

2024-04-16 13:02:07 浏览数 (3)

有一些库可与 ChatGPT 集成,但本文介绍如何在没有任何外部依赖项的情况下使用 ChatGPT API。

执行

WebClient用于调用 ChatGPT API,这就是为什么spring-boot-starter-webflux将依赖项添加到pom.

代码语言:javascript复制
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

将您的 API 密钥放入application.yml如下所示的位置。AuthorizationAPI 密钥将作为请求中的 HTTP 标头发送。API 密钥可以从https://platform.openai.com/account/api-keys创建。

代码语言:javascript复制
chatgpt:
  api-key: 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

为了简单起见,控制器端点接收请求正文中的问题或提示并直接发送到 ChatGPT。您可以做更强大的事情来提出提示。

请注意,您可以更改并使用构造函数中的modeltemperature

代码语言:javascript复制
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.annotation.PostExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

interface GptClient {
    @PostExchange("/v1/chat/completions")
    ChatResponse chat(@RequestBody ChatRequest request);
}

@SpringBootApplication
public class MainApplication {

    @Value("${chatgpt.api-key}")
    private String apiKey;

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

    @Bean
    GptClient client(WebClient.Builder builder) {
        var httpClient = HttpClient.newConnection()
                .responseTimeout(Duration.ofSeconds(60))
                .keepAlive(false);

        var wc = builder.baseUrl("https://api.openai.com")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer "   apiKey)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();

        var wca = WebClientAdapter.forClient(wc);
        return HttpServiceProxyFactory.builder()
                .blockTimeout(Duration.ofSeconds(60))
                .clientAdapter(wca)
                .build()
                .createClient(GptClient.class);
    }
}

class ChatRequest {
    private String model;
    private List<Message> messages;
    private double temperature;

    public ChatRequest() {

    }

    public ChatRequest(String prompt) {
        this.model = "gpt-3.5-turbo";
        this.messages = List.of(new Message("user", prompt));
        this.temperature = 0.0;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public List<Message> getMessages() {
        return messages;
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    public double getTemperature() {
        return temperature;
    }

    public void setTemperature(double temperature) {
        this.temperature = temperature;
    }
}

record Message(String role, String content) {
}

record Choice(int index, Message message) {
}

record ChatResponse(List<Choice> choices) {
}

@Controller
@ResponseBody
@RequestMapping("/api")
class ChatController {

    private final GptClient gpt;

    public ChatController(GptClient gpt) {
        this.gpt = gpt;
    }

    @PostMapping("/chat")
    public String chat(@RequestBody String prompt) {
        var response = gpt.chat(new ChatRequest(prompt));
        System.out.println(response);

        return response.choices().stream()
                .map(c -> c.message().content())
                .collect(Collectors.joining("n"));
    }
}

0 人点赞