ChatGPT Java API
2.1.1
用于 ChatGPT、助手等的非官方、易于使用的 Java/Kotlin OpenAI API!
OpenAI#streamCompletion
进行流媒体支持OpenAI#streamChatCompletion
进行流媒体支持对于 Kotlin DSL ( build.gradle.kts
),将其添加到您的依赖项块中:
dependencies {
implementation( " com.cjcrafter:openai:2.1.0 " )
}
对于 Maven 项目,请将其添加到pom.xml
文件的<dependencies>
块中:
< dependency >
< groupId >com.cjcrafter</ groupId >
< artifactId >openai</ artifactId >
< version >2.1.0</ version >
</ dependency >
请参阅 gradle/ant/etc 的 Maven 存储库。
这是 Java 中 ChatGPT API 的简单工作示例:
import com . cjcrafter . openai . OpenAI ;
import com . cjcrafter . openai . chat . ChatMessage ;
import com . cjcrafter . openai . chat . ChatRequest ;
import com . cjcrafter . openai . chat . ChatResponse ;
import io . github . cdimascio . dotenv . Dotenv ;
import java . util . ArrayList ;
import java . util . List ;
import java . util . Scanner ;
/**
* In this Java example, we will be using the Chat API to create a simple chatbot.
*/
public class ChatCompletion {
public static void main ( String [] args ) {
// To use dotenv, you need to add the "io.github.cdimascio:dotenv-kotlin:version"
// dependency. Then you can add a .env file in your project directory.
String key = Dotenv . load (). get ( "OPENAI_TOKEN" );
OpenAI openai = OpenAI . builder ()
. apiKey ( key )
. build ();
List < ChatMessage > messages = new ArrayList <>();
messages . add ( ChatMessage . toSystemMessage ( "Help the user with their problem." ));
// Here you can change the model's settings, add tools, and more.
ChatRequest request = ChatRequest . builder ()
. model ( "gpt-3.5-turbo" )
. messages ( messages )
. build ();
Scanner scan = new Scanner ( System . in );
while ( true ) {
System . out . println ( "What are you having trouble with?" );
String input = scan . nextLine ();
messages . add ( ChatMessage . toUserMessage ( input ));
ChatResponse response = openai . createChatCompletion ( request );
System . out . println ( "Generating Response..." );
System . out . println ( response . get ( 0 ). getMessage (). getContent ());
// Make sure to add the response to the messages list!
messages . add ( response . get ( 0 ). getMessage ());
}
}
}
有关更多示例,请查看示例。
注意:OpenAI 建议为您的 API 令牌使用环境变量(了解更多)。
我们使用 SLF4J 进行日志记录。要启用日志记录,请将日志记录实现添加到您的项目中。如果您遇到 JSON 解析问题,我们会要求您启用日志记录并将日志发送给我们。
添加日志记录实现:
implementation( " ch.qos.logback:logback-classic: $version " )
将logback.xml
文件添加到您的资源文件夹中:
< configuration >
< appender name = " FILE " class = " ch.qos.logback.core.FileAppender " >
< file >debug.log</ file >
< append >false</ append >
< encoder >
< pattern >%date %level [%thread] %logger{10} %msg%n</ pattern >
</ encoder >
</ appender >
< logger name = " com.cjcrafter.openai " level = " DEBUG " /> <!-- Change to OFF to disable our logging -->
< root level = " DEBUG " >
< appender-ref ref = " FILE " />
</ root >
</ configuration >
如果我节省了您的时间,请考虑赞助我。
ChatGPT-Java-API 是一款根据 MIT 许可证授权的开源软件。这是一个非官方库,不隶属于 OpenAI 。