MCPcopy Index your code
hub / github.com/Grt1228/chatgpt-java

github.com/Grt1228/chatgpt-java @v1.1.5

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.1.5 ↗ · + Follow
577 symbols 1,940 edges 149 files 342 documented · 59% 2 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

it’s an “unofficial" or "community-maintained” library. This is an unofficial community-maintained library. Bug reports are welcome and let's learn from each other.

Original publication must be credited if reprinted!

Open source license: LICENSE

💬 Contact me, all ChatGPT-related learning, communication and consultation are free.

Let's discuss issues related to chatgpt-java, SDK problem consultation, project and product development communication If the group is invalid, please follow the official account to restore: chatgpt-java
QR code QR code

📖 Project Introduction

ChatGPT Java Client

The Java SDK for OpenAI's official API allows for quick integration into projects. It supports all of OpenAI's official interfaces, as well as token calculations. Reference documentation: Tokens_README.md.

TikToken Chat Completions Images Speech To Text Balance Inquiry
Token Calculation GPT-3.5, 4.0 Dialogue Model GPT-3.0 Dialogue Image Model Speech-to-Text, Speech Translation Balance Inquiry
Embeddings Files Moderations Fine-tune Models
Embeddings Custom Training Models Text Review, Sensitive Word Identification Fine-tune Model Retrieval

Supports streaming output: Streaming output implementation | Mini Program | Android | iOS | H5 ---|---|---|---|--- SSE Reference:OpenAISSEEventSourceListener | Not Supported | Supported| Supported | Supported WebSocket Reference:OpenAIWebSocketEventSourceListener | Supported| Supported | Supported | Supported

🚩 Features

  • support gpt plugin ,eg: PluginTest
  • Supports dynamic handling of keys in case of exceptions (invalid, expired, blocked). See the reference implementation DynamicKeyOpenAiAuthInterceptor.
  • Supports alerting in case of key exceptions (custom development needed for platforms like DingTalk, Feishu, email, WeChat Work). See the reference implementation DynamicKeyOpenAiAuthInterceptor.
  • Supports multiple ways of token calculation.
  • Supports customizing the OkHttpClient.
  • Supports customizing multiple Apikeys.
  • Supports customizing the key acquisition strategy.
  • Supports balance inquiry.
  • Supports personal account information inquiry.
  • Supports GPT3, GPT3.5, GPT4.0, GPT3.5—0614, GPT4.0—0614...
  • Supports all OpenAI APIs.

📑 Update Log

  • [x] 1.1.5 Bug Fix
  • [x] 1.1.3 Upgrade to support Assistant、Run、Thread、Message Api. eg: OpenAiClientTest
  • [x] 1.1.2-beta0 Upgrade to support chat completion with picture GPT-4V、return JSON model、Tool Call、Dall-e-3、Fine Tune Job、TTS.
  • [x] 1.1.1-beta0 function call update to GPT plugin model, so easy use the plugin api. eg: PluginTest
  • [x] 1.0.15 moderations api update,code fix,bug fix
  • [x] 1.0.14 Upgrade to support the latest version gpt-3.5—0614、gpt-4.0—0614 models, support function-calling full test e.g.:OpenAiClientFunctionTest
  • [x] 1.0.13 Added support for custom handling of key exceptions (invalid, expired, blocked) with the implementation reference DynamicKeyOpenAiAuthInterceptor. Also added support for alerting on key exceptions (DingTalk, Feishu, email, WeChat Enterprise, etc.), which requires custom development.
  • [x] 1.0.12 Optimized token calculation, modified delete model interface, and updated speech interface to support the latest official parameters.
  • [x] 1.0.11 Added new balance query interface with reference to OpenAiClientTest and OpenAiStreamClientTest. Fixed slow token calculation issue.
  • [x] 1.0.10 Added support for token calculation with reference to TikTokensTest. For more detailed information, please refer to the document: Tokens_README.md
  • [x] 1.0.9 Added support for custom key usage strategies with reference to OpenAiClientTest and OpenAiStreamClientTest. Deprecated ChatGPTClient and optimized Moderation interface.
  • [x] 1.0.8 Modified the custom implementation of OpenAiClient and OpenAiStreamClient, and changed the timeout setting, proxy setting, and custom interceptor setting to be implemented through custom OkHttpClient. This makes it more reasonable to hand over the OkHttpClient to the user for custom control, and more parameters can be customized. Also added support for multiple API key configurations.
  • [x] 1.0.7 Fixed deserialization error bug: https://github.com/Grt1228/chatgpt-java/issues/79, and image SDK enumeration value bug: https://github.com/Grt1228/chatgpt-java/issues/76. Thanks to @CCc3120 and @seven-cm for pointing them out.
  • [x] 1.0.6 Added support for balance inquiry with reference to OpenAiClientTest and OpenAiStreamClientTest creditGrants method. Also added support for the latest GPT-4 model, reference: ChatCompletion.ModelThe creditGrants method supports the latest GPT-4 model. Refer to the ChatCompletion.Model to build the message body and pass it into the model. Thanks to the group members for providing the balance interface address and @PlexPt for providing the model parameters.
  • [x] 1.0.5 Supports custom Api Host and can be built using Builder. Refer to the code in the Quick Start section below.
  • [x] 1.0.4 Changes to the Api return value in the latest ChatGPT Stream mode.
  • [x] 1.0.3 Supports the latest GPT-3.5-Turbo and Whisper-1 models, supports speech-to-text and voice translation. OpenAiClient and OpenAiStreamClient support Builder construction and proxy support.
  • [x] 1.0.2 Supports Stream output, refer to: OpenAiStreamClient
  • [x] 1.0.1 Supports custom timeout and custom OkHttpClient interceptor, refer to: OpenAiClient constructor
  • [x] 1.0.0 Supports all official OpenAI interfaces.

🚀 Quick Start

This project supports both default output and streaming output. For a complete SDK test case, see:

SDK Test Cases | TikToken Test Cases | Full Function Call Test Cases ---|---|---| OpenAiClientTest and OpenAiStreamClientTest | Token calculation reference: TikTokensTest | OpenAiClientFunctionTest

Method 1

1. Import pom dependency

<dependency>
    <groupId>com.unfbx</groupId>
    <artifactId>chatgpt-java</artifactId>
    <version>1.0.14</version>
</dependency>

2. Streaming client usage example:

More SDK examples can be found at: OpenAiStreamClientTest

Default OkHttpClient

public class Test {
    public static void main(String[] args) {
        OpenAiStreamClient client = OpenAiStreamClient.builder()
                .apiKey(Arrays.asList("sk-********","sk-********"))
                // Custom key acquisition strategy: default KeyRandomStrategy
                //.keyStrategy(new KeyRandomStrategy())
                .keyStrategy(new FirstKeyStrategy())
                // If you have a proxy, pass the proxy address, otherwise you can skip it
//                .apiHost("https://自己代理的服务器地址/")
                .build();
        // Chat model: gpt-3.5
        ConsoleEventSourceListener eventSourceListener = new ConsoleEventSourceListener();
        Message message = Message.builder().role(Message.Role.USER).content("你好啊我的伙伴!").build();
        ChatCompletion chatCompletion = ChatCompletion.builder().messages(Arrays.asList(message)).build();
        client.streamChatCompletion(chatCompletion, eventSourceListener);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Customize the usage of OkHttpClient client example:

public class Test {
    public static void main(String[] args) {
        // If accessing the service from China, a proxy needs to be configured. No proxy is needed for accessing the service from overseas servers.
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        // !!! Do not enable BODY level logging in production or test environment !!!
        // !!! It is recommended to set the logging level to one of these three levels in production or test environment: NONE, BASIC, HEADERS !!!
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .proxy(proxy) // custom proxy
                .addInterceptor(httpLoggingInterceptor) // custom logger
                .connectTimeout(30, TimeUnit.SECONDS) // custom connection timeout
                .writeTimeout(30, TimeUnit.SECONDS) // custom write timeout
                .readTimeout(30, TimeUnit.SECONDS) // custom read timeout
                .build();
        OpenAiStreamClient client = OpenAiStreamClient.builder()
                .apiKey(Arrays.asList("sk-********","sk-********"))
                // custom key acquisition strategy: default is KeyRandomStrategy
                //.keyStrategy(new KeyRandomStrategy())
                .keyStrategy(new FirstKeyStrategy())
                .okHttpClient(okHttpClient) // custom OkHttpClient
                // if a proxy is used, pass the proxy address, if not, do not pass
//                .apiHost("https://your.proxy.server.address/")
                .build();
    }
}

Output log (text is continuously output): ``` 23:03:59.158 [省略无效信息] INFO com.unfbx.chatgpt.sse.ConsoleEventSourceListener - OpenAI建立sse连接... 23:03:59.160 [省略无效信息] INFO com.unfbx.chatgpt.sse.Conso

Extension points exported contracts — how you extend this code

KeyStrategyFunction (Interface)
描述:key 的获取策略 jdk默认实现 @see Function @author https:www.unfbx.com @since 2023-04-03 [2 implementers]
src/main/java/com/unfbx/chatgpt/function/KeyStrategyFunction.java
IError (Interface)
描述: @author https:www.unfbx.com 2023-02-11 [1 implementers]
src/main/java/com/unfbx/chatgpt/exception/IError.java
OpenAiApi (Interface)
描述: open ai官方api接口 @author https:www.unfbx.com 2023-02-15
src/main/java/com/unfbx/chatgpt/OpenAiApi.java

Core symbols most depended-on inside this repo

build
called by 146
src/main/java/com/unfbx/chatgpt/OpenAiClient.java
builder
called by 105
src/main/java/com/unfbx/chatgpt/OpenAiClient.java
role
called by 32
src/main/java/com/unfbx/chatgpt/entity/chat/Message.java
model
called by 30
src/main/java/com/unfbx/chatgpt/OpenAiApi.java
builder
called by 29
src/main/java/com/unfbx/chatgpt/entity/chat/Message.java
messages
called by 24
src/main/java/com/unfbx/chatgpt/OpenAiApi.java
code
called by 21
src/main/java/com/unfbx/chatgpt/exception/IError.java
name
called by 21
src/main/java/com/unfbx/chatgpt/entity/chat/Message.java

Shape

Method 386
Class 148
Enum 40
Interface 3

Languages

Java100%

Modules by API surface

src/main/java/com/unfbx/chatgpt/OpenAiClient.java78 symbols
src/main/java/com/unfbx/chatgpt/OpenAiApi.java64 symbols
src/test/java/com/unfbx/chatgpt/OpenAiClientTest.java46 symbols
src/test/java/com/unfbx/chatgpt/v1_1_3/OpenAiClientTest.java33 symbols
src/test/java/com/unfbx/chatgpt/v1_1_2/OpenAiClientTest.java23 symbols
src/main/java/com/unfbx/chatgpt/OpenAiStreamClient.java18 symbols
src/main/java/com/unfbx/chatgpt/entity/fineTune/FineTune.java13 symbols
src/main/java/com/unfbx/chatgpt/entity/chat/MessagePicture.java12 symbols
src/main/java/com/unfbx/chatgpt/entity/chat/Message.java12 symbols
src/main/java/com/unfbx/chatgpt/sse/PluginListener.java8 symbols
src/main/java/com/unfbx/chatgpt/plugin/PluginAbstract.java8 symbols
src/main/java/com/unfbx/chatgpt/entity/edits/Edit.java8 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add chatgpt-java \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact