前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何在 Spring Boot中使用 OpenAI ChatGPT API

如何在 Spring Boot中使用 OpenAI ChatGPT API

作者头像
lyb-geek
发布2024-04-16 13:02:07
880
发布2024-04-16 13:02:07
举报
文章被收录于专栏:Linyb极客之路Linyb极客之路

有一些库可与 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"));
    }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-04-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Linyb极客之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 执行
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档