3 Star 35 Fork 17

lzhpo / chatgpt-spring-boot-starter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Style check

概览

  1. 支持设置多个 API Key,并且支持对其设置权重以及是否启用,支持自动禁用失效的 API Key 以及自动轮转
  2. 支持设置请求代理
  3. 支持自定义请求 API(如果对 OpenAi 的 API 做了中转/代理)
  4. 支持 OpenAi 所有可以使用 API Key 访问的 API
  5. 支持流式响应,即所谓的"打字机"模式
  6. 请求参数自动校验
  7. 支持 token 计算
  8. 支持 function calling

支持的功能

✅ 模型查询(Model)
✅ 流式、非流式对话聊天(Stream Chat/completion)
✅ 根据提示生成文本(Edit)
✅ 自然语言转换为向量表示
✅ 音频、视频语音转文本(Create transcription)
✅ 文本翻译(Create translation)
✅ 文件的查询、上传、删除(File - List/Upload/Delete/Retrieve)
✅ 预训练模型的微调、查询、放弃、过程(事件)(Fine-tunes - Create/List/Retrieve/Cancel/Events)
✅ 内容审核(Moderation)
✅ 用户余额、使用量查询(Billing/Usage)
✅ 用户信息查询(User)
✅ 根据提示创建、编辑图像、根据图像生成多版本图像(Image - Create/Create edit/Create variation)

项目地址

导入依赖

<dependency>
    <groupId>com.lzhpo</groupId>
    <artifactId>chatgpt-spring-boot-starter</artifactId>
    <version>${version}</version>
</dependency>

配置示例

1. 支持配置多个 API Key(权重、是否启用)

可以对当前 api key 设置权重,以及是否需要启用此 api key,提供了两种方式配置。

1.1 方式1-常规yaml配置方式

openai:
  keys:
    - key: "sk-xxx1"
      weight: 1.0
      enabled: true
    - key: "sk-xxx2"
      weight: 2.0
      enabled: false
    - key: "sk-xxx3"
      weight: 3.0
      enabled: false

支持自动禁用失效的 API Key 以及自动轮转,参考:InvalidedKeyEventNoAvailableKeyEventOpenAiEventListener

1.2 方式2-自定义获取 API Key 逻辑

如果你的 API Key 是存在数据库或者其它地方的,那么可以选择使用这种方式配置。

实现OpenAiKeyProvider接口即可,例如:

@Component
public class XxxOpenAiKeyProvider implements OpenAiKeyProvider {

    @Override
    public List<OpenAiKey> get() {
        List<OpenAiKey> openAiKeys = new ArrayList<>();
        openAiKeys.add(OpenAiKey.builder().key("sk-xxx1").weight(1.0).enabled(true).build());
        openAiKeys.add(OpenAiKey.builder().key("sk-xxx2").weight(2.0).enabled(false).build());
        openAiKeys.add(OpenAiKey.builder().key("sk-xxx2").weight(3.0).enabled(true).build());
        return openAiKeys;
    }
}

注意:每次请求都会调用此方法,有需要的话可以在此加一个缓存。

2. 支持配置代理

openai:
  proxy:
    host: "127.0.0.1"
    port: 7890
    type: http
    header-name: "Proxy-Authorization"
    username: admin
    password: 123456

3. 支持配置超时时间

openai:
  connect-timeout: 1m
  read-timeout: 1m
  write-timeout: 1m

4. 支持自定义请求API

如果没有配置代理,也没有定制完整请求地址的需求,那么无需配置openai.domain以及openai.urls,会自动使用默认的。

4.1 方式1 - 只配置了代理

如果只是配置了国内中转代理,那么只需要配置openai.domain为代理地址即可,默认值为https://api.openai.com

openai:
  domain: "https://api.openai.com"

4.2 方式2 - 定制完整的请求地址

如果有定制完整请求地址的需求,可以按照如下配置,优先级比openai.domain更高,但需要的是完整的请求地址

openai:
  urls:
    moderations: "https://api.openai.com/v1/moderations"
    completions: "https://api.openai.com/v1/completions"
    edits: "https://api.openai.com/v1/edits"
    chat-completions: "https://api.openai.com/v1/chat/completions"
    list-models: "https://api.openai.com/v1/models"
    retrieve-model: "https://api.openai.com/v1/models/{model}"
    embeddings: "https://api.openai.com/v1/embeddings"
    list-files: "https://api.openai.com/v1/files"
    upload-file: "https://api.openai.com/v1/files"
    delete-file: "https://api.openai.com/v1/files/{file_id}"
    retrieve-file: "https://api.openai.com/v1/files/{file_id}"
    retrieve-file-content: "https://api.openai.com/v1/files/{file_id}/content"
    create_fine_tune: "https://api.openai.com/v1/fine-tunes"
    list_fine_tune: "https://api.openai.com/v1/fine-tunes"
    retrieve_fine_tune: "https://api.openai.com/v1/fine-tunes/{fine_tune_id}"
    cancel_fine_tune: "https://api.openai.com/v1/fine-tunes/{fine_tune_id}/cancel"
    list_fine_tune_events: "https://api.openai.com/v1/fine-tunes/{fine_tune_id}/events"
    delete_fine_tune_events: "https://api.openai.com/v1/models/{model}"
    create-transcription: "https://api.openai.com/v1/audio/transcriptions"
    create-translation: "https://api.openai.com/v1/audio/translations"
    create_image: "https://api.openai.com/v1/images/generations"
    create_image_edit: "https://api.openai.com/v1/images/edits"
    create_image_variation: "https://api.openai.com/v1/images/variations"
    billing-credit-grants: "https://api.openai.com/dashboard/billing/credit_grants"
    users: "https://api.openai.com/v1/organizations/{organizationId}/users"
    billing-subscription: "https://api.openai.com/v1/dashboard/billing/subscription"
    billing-usage: "https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"

5. 支持token计算

示例1:

Long tokens = TokenUtils.tokens(model, content);

示例2:CompletionRequest

CompletionRequest request = new CompletionRequest();
// request.setXXX 略...
Long tokens = TokenUtils.tokens(request.getModel(), request.getPrompt());

示例3:ChatCompletionRequest

ChatCompletionRequest request = new ChatCompletionRequest();
// request.setXXX 略...
Long tokens = TokenUtils.tokens(request.getModel(), request.getMessages());

OpenAi返回的token计算结果可在response返回体中获取:

  • prompt_tokens:OpenAi计算的输入消耗的token
  • completion_tokens:OpenAi计算的输出消耗的token
  • total_tokensprompt_tokens + completion_tokens

具体可参考测试用例OpenAiCountTokensTest以及TokenUtils

6. 支持 function calling

关于 function calling 的介绍:https://platform.openai.com/docs/guides/gpt/function-calling

参考示例见测试目录:com.lzhpo.chatgpt.OpenAiClientTest#functions

7. 关于异常处理

  1. 常规、SSE以及WebSocket请求失败均会抛出OpenAiException异常,可自定义全局异常,取出OpenAi的响应结果转换为OpenAiError(如果转换结果OpenAiError不为空),继而自行处理。
  2. 自定义流式处理的EventSourceListener,推荐继承AbstractEventSourceListener,如果没有特殊需求,直接重写onEvent方法即可,如果重写了onFailure方法,抛出何种异常取决于重写的onFailure方法。
  3. 提供了失效的Api-Key事件、当前无可用的Api-Key事件,可自行监听处理,例如:
    @Slf4j
    @Component
    public class OpenAiEventListener {
    
       @EventListener
       public void processInvalidedKey(InvalidedKeyEvent event) {
           String invalidedApiKey = event.getInvalidedApiKey();
           String errorResponse = event.getErrorResponse();
           log.error("Processing invalidedApiKey={} event, errorResponse: {}", invalidedApiKey, errorResponse);
       }
    
       @EventListener
       public void processNoAvailableKey(NoAvailableKeyEvent event) {
           List<String> invalidedKeys = event.getInvalidedKeys();
           log.error("Processing noAvailableKey event, invalidedKeys={}", invalidedKeys);
       }
    }
  4. 也可以实现OKHttp的Interceptor接口,并声明为Bean,也可在里面自行处理异常,参考:OpenAiErrorInterceptor

代码示例

1. 流式输出(“打字机”)

1.1 SSE方式示例

这里快速了解一下SSE(Server-Sent Events)

SSE和WebSocket都是用于实现服务器和浏览器之间实时通信的技术。 WebSocket是全双工通信协议,适用于双向通信的实时场景,而SSE是单向通信协议,适用于服务器向客户端推送消息的实时场景。

简单网页效果示例(“打字机”效果):

后端代码简单示例:

@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class ChatController {

    private final OpenAiClient openAiClient;

    @GetMapping("/chat/sse")
    public SseEmitter sseStreamChat(@RequestParam String message) {
        SseEmitter sseEmitter = new SseEmitter();
        ChatCompletionRequest request = ChatCompletionRequest.create(message);
        openAiClient.streamChatCompletions(request, new SseEventSourceListener(sseEmitter));
        return sseEmitter;
    }
}

SseEventSourceListener是基于okhttp3.sse.EventSourceListener实现的,可以接收text/event-stream类型的流式数据。

前端代码简单示例:

// message为需要发送的消息
const eventSource = new EventSource(`http://127.0.0.1:6060/chat/sse?message=${message}`);
// 收到消息处理
eventSource.onmessage = function(event) {
    // 略...
}

由于SSE协议只支持GET方法,不支持POST方法。
如果要支持POST方法可以参考:https://github.com/Azure/fetch-event-source

详细代码见仓库目录下:

  • templates/chat.html
  • templates/sse-stream-chat.html
  • com.lzhpo.chatgpt.OpenAiTestController

1.2 WebSocket方式示例

效果和SSE方式一样,即“打字机”效果。

声明WebSocket端点:

@Slf4j
@Component
@ServerEndpoint("/chat/websocket")
public class OpenAiWebSocketTest {

    @OnOpen
    public void onOpen(Session session) {
        log.info("sessionId={} joined.", session.getId());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("Received sessionId={} message={}", session.getId(), message);
        ChatCompletionRequest request = ChatCompletionRequest.create(message);
        WebSocketEventSourceListener listener = new WebSocketEventSourceListener(session);
        SpringUtil.getBean(OpenAiClient.class).streamChatCompletions(request, listener);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("Closed sessionId={} connection.", session.getId());
    }

    @OnError
    public void onError(Session session, Throwable e) {
        log.error("sessionId={} error: {}", session.getId(), e.getMessage(), e);
    }
}

开启WebSocket端点:

@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
}

前端代码主要逻辑如下:

const websocket = new WebSocket("ws://127.0.0.1:6060/chat/websocket");
// 发送消息(message为需要发送的消息)
websocket.send(message);
// 收到消息
websocket.onmessage = function(event) {
    // 略...
}

详细代码见仓库目录下的templates/websocket-stream-chat.html

2. 自定义请求拦截器

实现okhttp3.Interceptor接口,并将其声明为bean即可。

例如:

@Slf4j
public class OpenAiLoggingInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        log.info("Request url: {} {}", request.method(), request.url());
        log.info("Request header: {}", request.headers());

        Response response = chain.proceed(request);
        log.info("Response code: {}", response.code());
        log.info("Response body: {}", response.body().string());
        return response;
    }
}

3. 全部API测试示例

见:com.lzhpo.chatgpt.OpenAiClientTest

问题锦集

1. okhttp 报错 NoSuchMethodError

参考 issue:https://gitee.com/lzhpo/chatgpt-spring-boot-starter/issues/I7KHQG

鸣谢

感谢Jetbrains提供的License!

JetBrains Logo (Main) logo.

微信公众号

会打篮球的程序猿
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

支持OpenAi所有可用的接口,包括但不限于流式输出和Token计算等,可配置多个API-Key、权重、代理、自定义API等诸多功能... 展开 收起
Java 等 3 种语言
Apache-2.0
取消

发行版 (12)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/lzhpo/chatgpt-spring-boot-starter.git
git@gitee.com:lzhpo/chatgpt-spring-boot-starter.git
lzhpo
chatgpt-spring-boot-starter
chatgpt-spring-boot-starter
master

搜索帮助