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 。