# OpenAI-Java
Java libraries for using OpenAI's GPT apis. Supports GPT-3, ChatGPT, and GPT-4.
Includes the following artifacts:
- `api` : request/response POJOs for the GPT APIs.
- `client` : a basic retrofit client for the GPT endpoints, includes the `api` module
- `service` : A basic service class that creates and calls the client. This is the easiest way to get started.
as well as an example project using the service.
## Supported APIs
- [Models](https://platform.openai.com/docs/api-reference/models)
- [Completions](https://platform.openai.com/docs/api-reference/completions)
- [Chat Completions](https://platform.openai.com/docs/api-reference/chat/create)
- [Edits](https://platform.openai.com/docs/api-reference/edits)
- [Embeddings](https://platform.openai.com/docs/api-reference/embeddings)
- [Audio](https://platform.openai.com/docs/api-reference/audio)
- [Files](https://platform.openai.com/docs/api-reference/files)
- [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning)
- [Images](https://platform.openai.com/docs/api-reference/images)
- [Moderations](https://platform.openai.com/docs/api-reference/moderations)
- [Assistants](https://platform.openai.com/docs/api-reference/assistants)
#### Deprecated by OpenAI
- [Engines](https://platform.openai.com/docs/api-reference/engines)
- [Legacy Fine-Tunes](https://platform.openai.com/docs/guides/legacy-fine-tuning)
## Importing
### Gradle
`implementation 'com.theokanning.openai-gpt3-java:<api|client|service>:<version>'`
### Maven
```xml
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>{api|client|service}</artifactId>
<version>version</version>
</dependency>
```
## Usage
### Data classes only
If you want to make your own client, just import the POJOs from the `api` module.
Your client will need to use snake case to work with the OpenAI API.
### Retrofit client
If you're using retrofit, you can import the `client` module and use the [OpenAiApi](client/src/main/java/com/theokanning/openai/OpenAiApi.java).
You'll have to add your auth token as a header (see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java))
and set your converter factory to use snake case and only include non-null fields.
### OpenAiService
If you're looking for the fastest solution, import the `service` module and use [OpenAiService](service/src/main/java/com/theokanning/openai/service/OpenAiService.java).
> ⚠️The OpenAiService in the client module is deprecated, please switch to the new version in the service module.
```java
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);
```
### Customizing OpenAiService
If you need to customize OpenAiService, create your own Retrofit client and pass it in to the constructor.
For example, do the following to add request logging (after adding the logging gradle dependency):
```java
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);
```
### Adding a Proxy
To use a proxy, modify the OkHttp client as shown below:
```java
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);
```
### Functions
You can create your functions and define their executors easily using the ChatFunction class, along with any of your custom classes that will serve to define their available parameters. You can also process the functions with ease, with the help of an executor called FunctionExecutor.
First we declare our function parameters:
```java
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
}
```
Next, we declare the function itself and associate it with an executor, in this example we will fake a response from some API:
```java
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()
```
Then, we employ the FunctionExecutor object from the 'service' module to assist with execution and transformation into an object that is ready for the conversation:
```java
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);
```
> **Note:** The `FunctionExecutor` class is part of the 'service' module.
You can also create your own function executor. The return object of `ChatFunctionCall.getArguments()` is a JsonNode for simplicity and should be able to help you with that.
For a more in-depth look, refer to a conversational example that employs functions in: [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java).
Or for an example using functions and stream: [OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java)
### Streaming thread shutdown
If you want to shut down your process immediately after streaming responses, call `OpenAiService.shutdownExecutor()`.
This is not necessary for non-streaming calls.
## Running the example project
All the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your OpenAI api token
```bash
export OPENAI_TOKEN="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
```
You can try all the capabilities of this project using:
```bash
./gradlew runExampleOne
```
And you can also try the new capability of using functions:
```bash
./gradlew runExampleTwo
```
Or functions with 'stream' mode enabled:
```bash
./gradlew runExampleThree
```
## FAQ
### Does this support GPT-4?
Yes! GPT-4 uses the ChatCompletion Api, and you can see the latest model options [here](https://platform.openai.com/docs/models/gpt-4).
GPT-4 is currently in a limited
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
openai-使用Java调用OpenAIAPI-适用于GPT4-优质实用项目.zip (191个子文件)
gradlew.bat 3KB
build.gradle 705B
build.gradle 524B
build.gradle 503B
build.gradle 428B
build.gradle 221B
settings.gradle 185B
gradlew 8KB
assistants-data.html 13B
gradle-wrapper.jar 60KB
OpenAiService.java 26KB
ChatCompletionTest.java 14KB
OpenAiApi.java 14KB
TikTokensUtil.java 9KB
AssistantFunctionTest.java 7KB
OpenAiApiFunctionsExample.java 5KB
CompletionRequest.java 5KB
FineTuneRequest.java 4KB
MessageTest.java 4KB
ChatCompletionRequest.java 4KB
OpenAiApiDynamicFunctionExample.java 4KB
OpenAiApiFunctionsWithStreamExample.java 4KB
AssistantTest.java 4KB
FunctionExecutor.java 4KB
AudioTest.java 3KB
ImageTest.java 3KB
ResponseBodyCallbackTest.java 3KB
ResponseBodyCallback.java 3KB
OpenAiServiceTest.java 3KB
JsonTest.java 3KB
FineTuningTest.java 3KB
ChatMessageAccumulator.java 2KB
RunTest.java 2KB
OpenAiApiExample.java 2KB
FineTuneTest.java 2KB
FineTuningJob.java 2KB
ThreadTest.java 2KB
FileTest.java 2KB
Message.java 2KB
ChatFunctionCallArgumentsSerializerAndDeserializer.java 2KB
CreateImageRequest.java 2KB
FineTuneResult.java 2KB
CompletionTest.java 2KB
ChatFunction.java 2KB
ChatMessage.java 2KB
ChatCompletionRequestSerializerAndDeserializer.java 2KB
ChatFunctionDynamic.java 2KB
EditRequest.java 2KB
ListSearchParameters.java 1KB
Subscription.java 1KB
Run.java 1KB
CreateTranscriptionRequest.java 1KB
ChatFunctionParametersSerializer.java 1KB
CreateImageEditRequest.java 1KB
MessageRequest.java 1KB
Assistant.java 1KB
Permission.java 1KB
RunStep.java 1KB
CreateTranslationRequest.java 1KB
Moderation.java 1KB
CreateImageVariationRequest.java 1KB
File.java 1KB
EmbeddingRequest.java 1KB
Thread.java 1KB
LogProbResult.java 1017B
Annotation.java 969B
FineTuningJobRequest.java 969B
EmbeddingTest.java 957B
Model.java 954B
AssistantRequest.java 937B
ThreadRequest.java 936B
CreateSpeechRequest.java 932B
ModifyAssistantRequest.java 930B
EditTest.java 866B
MessageFile.java 854B
CompletionResult.java 845B
OpenAiError.java 827B
FineTuningEvent.java 819B
ModerationTest.java 813B
HyperParameters.java 803B
Hyperparameters.java 794B
OpenAiHttpException.java 791B
TikTokensExample.java 782B
CreateThreadAndRunRequest.java 772B
AuthenticationInterceptor.java 770B
CreditGrantsResponse.java 766B
TranscriptionResult.java 763B
TranslationResult.java 761B
OpenAiResponse.java 751B
FileCitation.java 751B
ModelTest.java 751B
ChatCompletionResult.java 747B
CompletionChunk.java 745B
MessageContent.java 720B
ChatFunctionParameters.java 708B
ModifyMessageRequest.java 703B
CompletionChoice.java 699B
ModerationCategories.java 690B
AuthenticationInterceptor.java 689B
TranscriptionSegment.java 686B
共 191 条
- 1
- 2
资源评论
极智视界
- 粉丝: 2w+
- 资源: 1575
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功