켈 통지 :이 프로젝트는 더 이상 유지 관리되지 않으며 2024 년 6 월 6 일 현재 보관되었습니다.이 프로젝트를 기여하고 지원 한 모든 분들께 감사드립니다. 저장소는 현재 상태로 유지되지만 추가 업데이트 나 지원은 제공되지 않습니다. 필요에 따라 코드를 포크하고 수정하십시오.
켈 OpenAi는 모든 엔진 기반 API를 사용하지 않았습니다. 자세한 내용은 아래의 감가 상각 종료점을 참조하십시오.
OpenAI의 GPT API를 사용하기위한 Java 라이브러리. GPT-3, ChatGpt 및 GPT-4를 지원합니다.
다음 아티팩트를 포함합니다.
api
: GPT API의 요청/응답 Pojos.client
: GPT 엔드 포인트의 기본 개조 클라이언트, api
모듈 포함service
: 클라이언트를 생성하고 호출하는 기본 서비스 클래스. 이것은 시작하는 가장 쉬운 방법입니다.뿐만 아니라 서비스를 사용하는 예제 프로젝트.
implementation 'com.theokanning.openai-gpt3-java:<api|client|service>:<version>'
< dependency >
< groupId >com.theokanning.openai-gpt3-java</ groupId >
< artifactId >{api|client|service}</ artifactId >
< version >version</ version >
</ dependency >
자신의 클라이언트를 만들려면 api
모듈에서 Pojos를 가져 오십시오. 고객은 OpenAI API와 함께 작업하려면 Snake Case를 사용해야합니다.
Retrofit을 사용하는 경우 client
모듈을 가져와 Openaiapi를 사용할 수 있습니다.
인증 토큰을 헤더로 추가하고 (AuthenticationInterceptor 참조) 컨버터 팩토리를 뱀 케이스를 사용하도록 설정하고 널 필드가 포함되지 않도록해야합니다.
가장 빠른 솔루션을 찾고 있다면 service
모듈을 가져와 OpenAiservice를 사용하십시오.
켈 클라이언트 모듈의 OpenAiService가 더 이상 사용되지 않습니다. 서비스 모듈의 새 버전으로 전환하십시오.
OpenAiService service = new OpenAiService ( "your_token" );
CompletionRequest completionRequest = CompletionRequest . builder ()
. prompt ( "Somebody once told me the world is gonna roll me" )
. model ( "babbage-002" ")
. echo ( true )
. build ();
service . createCompletion ( completionRequest ). getChoices (). forEach ( System . out :: println );
OpenAiservice를 사용자 정의 해야하는 경우 자신만의 개조 클라이언트를 만들어 생성자에게 전달하십시오. 예를 들어, 요청 로깅을 추가하려면 다음을 수행하십시오 (로깅 그레이드 종속성을 추가 한 후) :
ObjectMapper mapper = defaultObjectMapper ();
OkHttpClient client = defaultClient ( token , timeout )
. newBuilder ()
. interceptor ( HttpLoggingInterceptor ())
. build ();
Retrofit retrofit = defaultRetrofit ( client , mapper );
OpenAiApi api = retrofit . create ( OpenAiApi . class );
OpenAiService service = new OpenAiService ( api );
프록시를 사용하려면 아래와 같이 OKHTTP 클라이언트를 수정하십시오.
ObjectMapper mapper = defaultObjectMapper ();
Proxy proxy = new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( host , port ));
OkHttpClient client = defaultClient ( token , timeout )
. newBuilder ()
. proxy ( proxy )
. build ();
Retrofit retrofit = defaultRetrofit ( client , mapper );
OpenAiApi api = retrofit . create ( OpenAiApi . class );
OpenAiService service = new OpenAiService ( api );
ChatFunction 클래스를 사용하여 기능을 만들고 실행자를 쉽게 정의 할 수 있으며 사용 가능한 매개 변수를 정의하는 데 도움이되는 사용자 정의 클래스와 함께 쉽게 정의 할 수 있습니다. FunctionExecutor라는 집행자의 도움으로 기능을 쉽게 처리 할 수 있습니다.
먼저 기능 매개 변수를 선언합니다.
public class Weather {
@ JsonPropertyDescription ( "City and state, for example: León, Guanajuato" )
public String location ;
@ JsonPropertyDescription ( "The temperature unit, can be 'celsius' or 'fahrenheit'" )
@ JsonProperty ( required = true )
public WeatherUnit unit ;
}
public enum WeatherUnit {
CELSIUS , FAHRENHEIT ;
}
public static class WeatherResponse {
public String location ;
public WeatherUnit unit ;
public int temperature ;
public String description ;
// constructor
}
다음으로, 우리는 기능 자체를 선언하고 그것을 집행자와 연결합니다.이 예에서는 일부 API의 응답을 속일 것입니다.
ChatFunction . builder ()
. name ( "get_weather" )
. description ( "Get the current weather of a location" )
. executor ( Weather . class , w -> new WeatherResponse ( w . location , w . unit , new Random (). nextInt ( 50 ), "sunny" ))
. build ()
그런 다음 '서비스'모듈에서 functionExecutor 객체를 사용하여 대화 준비가 된 객체로의 실행 및 변환을 지원합니다.
List < ChatFunction > functionList = // list with functions
FunctionExecutor functionExecutor = new FunctionExecutor ( functionList );
List < ChatMessage > messages = new ArrayList <>();
ChatMessage userMessage = new ChatMessage ( ChatMessageRole . USER . value (), "Tell me the weather in Barcelona." );
messages . add ( userMessage );
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
. builder ()
. model ( "gpt-3.5-turbo-0613" )
. messages ( messages )
. functions ( functionExecutor . getFunctions ())
. functionCall ( new ChatCompletionRequestFunctionCall ( "auto" ))
. maxTokens ( 256 )
. build ();
ChatMessage responseMessage = service . createChatCompletion ( chatCompletionRequest ). getChoices (). get ( 0 ). getMessage ();
ChatFunctionCall functionCall = responseMessage . getFunctionCall (); // might be null, but in this case it is certainly a call to our 'get_weather' function.
ChatMessage functionResponseMessage = functionExecutor . executeAndConvertToMessageHandlingExceptions ( functionCall );
messages . add ( response );
참고 :
FunctionExecutor
클래스는 '서비스'모듈의 일부입니다.
자신만의 기능 집행자를 만들 수도 있습니다. ChatFunctionCall.getArguments()
의 반환 개체 ()는 단순성을위한 JSONNODE이며이를 도와 줄 수 있어야합니다.
보다 심층적 인 모습을 보려면 : openaiapifunctionsexample.java에서 함수를 사용하는 대화 예제를 참조하십시오. 또는 함수 및 스트림을 사용하여 예를 들어 : OpenaiaPifunctionswithStreamexample.java
스트리밍 응답 직후 프로세스를 종료하려면 OpenAiService.shutdownExecutor()
로 전화하십시오.
이것은 스트리밍하지 않는 전화에 필요하지 않습니다.
프로젝트가 필요한 모든 예제는 OpenAI API 토큰입니다.
export OPENAI_TOKEN= " sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "
이 프로젝트의 모든 기능을 사용하여 시도 할 수 있습니다.
./gradlew runExampleOne
기능을 사용하는 새로운 기능을 시도 할 수도 있습니다.
./gradlew runExampleTwo
또는 '스트림'모드가 활성화 된 기능 :
./gradlew runExampleThree
예! GPT-4는 ChatCompletion API를 사용하며 여기에서 최신 모델 옵션을 볼 수 있습니다.
GPT-4는 현재 제한된 베타 (4/1/23 기준)에 있으므로 사용하기 전에 액세스 할 수 있는지 확인하십시오.
전적으로! 더러운 작업을 걱정하지 않고 자신의 기능을 사용하는 것은 매우 쉽습니다. 위에서 언급했듯이 OpenaiaPifunctionsexample.java 또는 OpenAiApiFunctionswithStreamexample.java 프로젝트를 참조하십시오.
해당 국가에서 OpenAi를 사용할 수 있는지 확인하십시오.
많은 프로젝트가 OpenAiService를 사용하고 있으며, 최선을 다하기 위해 매우 간단하게 유지했습니다.
나만의 OpenAIAPI 인스턴스를 만들어 헤더, 타임 아웃, 기본 URL 등을 사용자 정의 할 수 있습니다.
Retry Logic 및 Async 호출과 같은 기능을 원한다면 OpenAiApi
인스턴스를 만들고 OpenAiService
사용하는 대신 직접 호출해야합니다.
OpenAI는 모델 기반 엔드 포인트에 유리한 평가 된 엔진 기반 엔드 포인트를 가지고 있습니다. 예를 들어, v1/engines/{engine_id}/completions
사용하는 대신 v1/completions
으로 전환하고 CompletionRequest
에서 모델을 지정하십시오. 이 코드에는 모든 감가 상각 된 엔드 포인트에 대한 업그레이드 지침이 포함되어 있습니다.
OpenAi가 종료 될 때 까지이 라이브러리에서 기존 엔드 포인트를 제거하지 않습니다.
MIT 라이센스에 따라 게시 됨