Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ChatGPT Java SDK。支持 GPT-4o、 GPT-5 API。开箱即用。An unofficial Java SDK for seamless integration with ChatGPT's GPT-5 and GPT-4 APIs. Ready-to-use, simple setup, and efficient for building AI-powered applications.

License

NotificationsYou must be signed in to change notification settings

PlexPt/chatgpt-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

stableMaven Central

English Doc.

OpenAI ChatGPT SDK

功能特性

功能特性
GPT 3.5支持
GPT 4.0支持
GPT 4o支持
GPT 4o-mini支持
函数调用支持
流式对话支持
上下文支持
计算Token支持
多KEY轮询支持
代理支持
反向代理支持

使用指南

参考Demohttps://github.com/PlexPt/chatgpt-online-springboot

最新版本Maven Central

maven

<dependency>    <groupId>com.github.plexpt</groupId>    <artifactId>chatgpt</artifactId>    <version>6.0.0</version></dependency>

gradle

implementation group: 'com.github.plexpt', name: 'chatgpt', version: '6.0.0'

最简使用

//国内需要代理Proxyproxy =Proxys.http("127.0.0.1",1081);//socks5 代理// Proxy proxy = Proxys.socks5("127.0.0.1", 1080);ChatGPTchatGPT =ChatGPT.builder()                .apiKey("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")                .proxy(proxy)                .apiHost("https://api.openai.com/")//反向代理地址                .build()                .init();Stringres =chatGPT.chat("写一段七言绝句诗,题目是:火锅!");System.out.println(res);

也可以使用这个类进行测试ConsoleChatGPT

进阶使用

//国内需要代理 国外不需要Proxyproxy =Proxys.http("127.0.0.1",1080);ChatGPTchatGPT =ChatGPT.builder()                .apiKey("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")                .proxy(proxy)                .timeout(900)                .apiHost("https://api.openai.com/")//反向代理地址                .build()                .init();Messagesystem =Message.ofSystem("你现在是一个诗人,专门写七言绝句");Messagemessage =Message.of("写一段七言绝句诗,题目是:火锅!");ChatCompletionchatCompletion =ChatCompletion.builder()                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())                .messages(Arrays.asList(system,message))                .maxTokens(3000)                .temperature(0.9)                .build();ChatCompletionResponseresponse =chatGPT.chatCompletion(chatCompletion);System.out.println(response.toPlainString());

计算token数

Messagesystem =Message.ofSystem("你现在是一个诗人,专门写七言绝句");Messagemessage =Message.of("写一段七言绝句诗,题目是:火锅!");ChatCompletionchatCompletion1 =ChatCompletion.builder()        .model(ChatCompletion.Model.GPT_3_5_TURBO)        .messages(Arrays.asList(system,message))        .maxTokens(3000)        .temperature(0.9)        .build();ChatCompletionchatCompletion2 =ChatCompletion.builder()        .model(ChatCompletion.Model.GPT4)        .messages(Arrays.asList(system,message))        .maxTokens(3000)        .temperature(0.9)        .build();log.info("{} tokens: {}",chatCompletion1.getModel(),chatCompletion1.countTokens());log.info("{} tokens: {}",chatCompletion2.getModel(),chatCompletion2.countTokens());

函数调用(Function Call)

//国内需要代理 国外不需要Proxyproxy =Proxys.http("127.0.0.1",1080);chatGPT =ChatGPT.builder()                  .apiKey("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")                  .timeout(900)                  .proxy(proxy)                  .apiHost("https://api.openai.com/")//代理地址                  .build()                  .init();List<ChatFunction>functions =newArrayList<>();ChatFunctionfunction =newChatFunction();function.setName("getCurrentWeather");function.setDescription("获取给定位置的当前天气");function.setParameters(ChatFunction.ChatParameter.builder()        .type("object")        .required(Arrays.asList("location"))        .properties(JSON.parseObject("{\n" +"\"location\": {\n" +"\"type\":\"string\",\n" +"\"description\":\"The city and state, e.g. San Francisco, " +"CA\"\n" +"          },\n" +"\"unit\": {\n" +"\"type\":\"string\",\n" +"\"enum\": [\"celsius\",\"fahrenheit\"]\n" +"          }\n" +"        }"))        .build());functions.add(function);Messagemessage =Message.of("上海的天气怎么样?");ChatCompletionchatCompletion =ChatCompletion.builder()        .model(ChatCompletion.Model.GPT_3_5_TURBO_0613.getName())        .messages(Arrays.asList(message))        .functions(functions)        .maxTokens(8000)        .temperature(0.9)        .build();ChatCompletionResponseresponse =chatGPT.chatCompletion(chatCompletion);ChatChoicechoice =response.getChoices().get(0);Messageres =choice.getMessage();System.out.println(res);if ("function_call".equals(choice.getFinishReason())) {FunctionCallResultfunctionCall =res.getFunctionCall();StringfunctionCallName =functionCall.getName();if ("getCurrentWeather".equals(functionCallName)) {Stringarguments =functionCall.getArguments();JSONObjectjsonObject =JSON.parseObject(arguments);Stringlocation =jsonObject.getString("location");Stringunit =jsonObject.getString("unit");Stringweather =getCurrentWeather(location,unit);callWithWeather(weather,res,functions);        }        }privatevoidcallWithWeather(Stringweather,Messageres,List<ChatFunction>functions) {Messagemessage =Message.of("上海的天气怎么样?");Messagefunction1 =Message.ofFunction(weather);function1.setName("getCurrentWeather");ChatCompletionchatCompletion =ChatCompletion.builder()        .model(ChatCompletion.Model.GPT_3_5_TURBO_0613.getName())        .messages(Arrays.asList(message,res,function1))        .functions(functions)        .maxTokens(8000)        .temperature(0.9)        .build();ChatCompletionResponseresponse =chatGPT.chatCompletion(chatCompletion);ChatChoicechoice =response.getChoices().get(0);Messageres2 =choice.getMessage();//上海目前天气晴朗,气温为 22 摄氏度。System.out.println(res2.getContent());        }publicStringgetCurrentWeather(Stringlocation,Stringunit) {return"{\"temperature\": 22,\"unit\":\"celsius\",\"description\":\"晴朗\" }";        }

流式使用

//国内需要代理 国外不需要Proxyproxy =Proxys.http("127.0.0.1",1080);ChatGPTStreamchatGPTStream =ChatGPTStream.builder()                .timeout(600)                .apiKey("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")                .proxy(proxy)                .apiHost("https://api.openai.com/")                .build()                .init();ConsoleStreamListenerlistener =newConsoleStreamListener();Messagemessage =Message.of("写一段七言绝句诗,题目是:火锅!");ChatCompletionchatCompletion =ChatCompletion.builder()                .messages(Arrays.asList(message))                .build();chatGPTStream.streamChatCompletion(chatCompletion,listener);

流式配合Spring SseEmitter使用

参考SseStreamListener

你可能在找这个,参考Demohttps://github.com/PlexPt/chatgpt-online-springboot

@GetMapping("/chat/sse")@CrossOriginpublicSseEmittersseEmitter(Stringprompt) {//国内需要代理 国外不需要Proxyproxy =Proxys.http("127.0.0.1",1080);ChatGPTStreamchatGPTStream =ChatGPTStream.builder()                .timeout(600)                .apiKey("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")                .proxy(proxy)                .apiHost("https://api.openai.com/")                .build()                .init();SseEmittersseEmitter =newSseEmitter(-1L);SseStreamListenerlistener =newSseStreamListener(sseEmitter);Messagemessage =Message.of(prompt);listener.setOnComplate(msg -> {//回答完成,可以做一些事情        });chatGPTStream.streamChatCompletion(Arrays.asList(message),listener);returnsseEmitter;    }

多KEY自动轮询

只需替换chatGPT构造部分

chatGPT = ChatGPT.builder()        .apiKeyList(               // 从数据库或其他地方取出多个KEY                Arrays.asList("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",                        "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",                        "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",                        "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",                        ))        .timeout(900)        .proxy(proxy)        .apiHost("https://api.openai.com/") //代理地址        .build()        .init();

上下文

参考ChatContextHolder.java

另外请看看我的另一个项目ChatGPT中文使用指南

公众号

云服务器

点击👇🏻传送链接,购买云服务器:

项目合作洽谈请点击 联系微信https://work.weixin.qq.com/kfid/kfc6913bb4906e0e597

QQ群:645132635

Star History

Star History Chart


🙏 Special Thanks

JetBrains Logo

Thanks toJetBrains for providing free open-source development license for this project


About

ChatGPT Java SDK。支持 GPT-4o、 GPT-5 API。开箱即用。An unofficial Java SDK for seamless integration with ChatGPT's GPT-5 and GPT-4 APIs. Ready-to-use, simple setup, and efficient for building AI-powered applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors10

Languages


[8]ページ先頭

©2009-2025 Movatter.jp