Compare commits

...

29 Commits
0.8.1 ... main

Author SHA1 Message Date
488f40b789 Change JDK version from 11 to 17 2023-03-28 10:07:37 -04:00
5e644ceffd 修改许可证信息 2023-03-13 11:30:37 -04:00
8619ecc46e 修改编译使用的 JDK 为 JDK 17 2023-03-13 11:27:35 -04:00
666c38e7b1 修改自述文件来提供允许 OpenAI 的方法 2023-03-10 12:34:30 -05:00
30dfac5f0a 更新项目提交 Bug 的链接 2023-03-10 11:05:26 -05:00
ce616c7816 更新 POM 文件 2023-03-10 10:59:18 -05:00
a991582b80 更新自述文件,并且将 Key 配置到环境文件中 2023-03-10 09:07:44 -05:00
7d3b7c7eb1 更新联系方式使用 SharkFly 公众号来进行 OpenAI 的测试 2023-03-07 08:38:15 -05:00
4fd7096e65 更新 Apache 使用的版本 2023-01-13 19:36:18 -05:00
5967337229 Update the test folder and sub-task 2023-01-07 08:41:19 -05:00
09aa7fdeb6 Update README file 2023-01-06 18:40:06 -05:00
8babebac7a Update README file to include more info to project. 2023-01-06 18:36:55 -05:00
c796112903 Clean up the file we don't need it 2023-01-06 18:22:01 -05:00
f23170b45c update the maven repo 2023-01-06 16:17:12 -05:00
9b907d0d9a update to new name 2023-01-06 14:41:47 -05:00
65a30def30 Update Readme file 2023-01-06 14:40:52 -05:00
85961e264c Update Readme file 2023-01-06 13:32:10 -05:00
633b877145 update the git file 2023-01-06 13:27:55 -05:00
3bf8d33cd7 Re-name the all package and start build base on those new package name 2023-01-06 13:24:09 -05:00
062798c73a Delete all lombok from project and build as JDK version 11 2023-01-06 13:20:51 -05:00
f63a2438dc Add client module to package 2023-01-06 12:47:41 -05:00
0dda9fc1f4 Delete all code use for lombok 2023-01-06 12:46:06 -05:00
YuCheng Hu
0fc2159293 New code for maven 2023-01-06 12:36:47 -05:00
YuCheng Hu
add90c312a Test to use maven 2023-01-06 12:11:02 -05:00
Theo Kanning
e68a098b87
Add image generation, editing, and variations (#63)
https://beta.openai.com/docs/api-reference/images
2023-01-03 16:33:52 -06:00
Theo Kanning
3f8f02f104
Upgrade github actions plugins (#64)
This should fix some deprecation warnings
2023-01-03 16:33:24 -06:00
Theo Kanning
b9ff2dc177
Add test for CompletionRequest n parameter (#61) 2023-01-02 17:17:55 -06:00
Theo Kanning
68e75010fd
Gradle 8.0 deprecation fix (#60)
Switched to the new method of setting the main class.
2023-01-02 15:40:27 -06:00
Theo Kanning
5b3955d81a
Delete deprecated Answer, Classification, and Search APIs (#59)
OpenAI deprecated these months ago, and they have now stopped working.
2023-01-02 15:36:33 -06:00
115 changed files with 4437 additions and 2054 deletions

6
.gitattributes vendored
View File

@ -1,6 +0,0 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

View File

@ -1,31 +0,0 @@
name: Publish
on:
push:
tags:
- '[0-9]+.[0-9]+.[0-9]+'
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Test
run: ./gradlew test
env:
OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }}
- name: Publish
run: ./gradlew build publish
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_KEY }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_KEY_PASSWORD }}

View File

@ -1,24 +0,0 @@
name: Test
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Test
run: ./gradlew test --stacktrace
env:
OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }}

264
.gitignore vendored
View File

@ -1,33 +1,235 @@
# Compiled class file ### Gradle ###
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
!gradle/wrapper/gradle-wrapper.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# IntelliJ Files #
.idea/
*.iml
# Ignore Gradle project-specific cache directory
.gradle .gradle
build/
# Ignore Gradle build output directory # Ignore Gradle GUI config
build gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Intellij+iml ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+iml Patch ###
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.flattened-pom.xml
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint

10
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Zeppelin ignored files
/ZeppelinRemoteNotebooks/

15
.idea/compiler.xml generated Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="openai-j-api" />
<module name="openai-j-example" />
<module name="openai-j-client" />
</profile>
</annotationProcessing>
</component>
</project>

23
.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/api/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/api/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/api/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/client/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/client/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/client/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/example/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/example/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/example/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-api/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-api/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-api/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-client/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-client/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/openai-j-client/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/filter/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

55
.idea/jarRepositories.xml generated Normal file
View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="ossez-repo-snapshots" />
<option name="name" value="OSSEZ Private Snapshots" />
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossrh-releases" />
<option name="name" value="ossrh Releases" />
<option name="url" value="https://oss.sonatype.org/service/local/staging/deploy/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.ossez.com/repository/maven-public/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossez-repo" />
<option name="name" value="Ossez-Repo-Snapshot" />
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossez-repo-releases" />
<option name="name" value="OSSEZ Private Releases" />
<option name="url" value="https://repo.ossez.com/repository/maven-releases/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossrh-snapshots" />
<option name="name" value="OSSEZ Private Snapshots" />
<option name="url" value="https://oss.sonatype.org/content/repositories/snapshots" />
</remote-repository>
<remote-repository>
<option name="id" value="ossrh-releases" />
<option name="name" value="ossrh Releases" />
<option name="url" value="https://repo.ossez.com/repository/maven-releases/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossrh" />
<option name="name" value="ossrh" />
<option name="url" value="https://oss.sonatype.org/content/repositories/snapshots" />
</remote-repository>
</component>
</project>

6
.idea/jpa-buddy.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JpaBuddyIdeaProjectConfig">
<option name="renamerInitialized" value="true" />
</component>
</project>

12
.idea/php.xml generated Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>

7
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) [year] [fullname] Copyright (c) 2023 OSSEZ
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

144
README.md
View File

@ -1,45 +1,92 @@
![Maven Central](https://img.shields.io/maven-central/v/com.theokanning.openai-gpt3-java/client?color=blue) # OpenAI-J
> ⚠The [Answers](https://help.openai.com/en/articles/6233728-answers-transition-guide), <p align="center">
>[Classifications](https://help.openai.com/en/articles/6272941-classifications-transition-guide), <a href="https://github.com/honeymoose">
>and [Searches](https://help.openai.com/en/articles/6272952-search-transition-guide) APIs are deprecated, <img height=85 src="https://avatars1.githubusercontent.com/u/45009982?s=200&v=4">
>and will stop working on December 3rd, 2022. </a>
<br>This project builds by JDK 17 and OpenJ9 for JVM.
</p>
> ⚠OpenAI has deprecated all Engine-based APIs. See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below for more info. * [社区和讨论 (community)](https://www.ossez.com/tag/chat-gpt)
# OpenAI-Java
Java libraries for using OpenAI's GPT-3 api. Java libraries for using OpenAI's GPT-3 api.
We forked this API from: https://github.com/TheoKanning/openai-java/.
The major reason we rebuild this API was OpenAI-JAVA include lombok, we think it is better build this in plain java
code.
# 联系方式
请使用下面的联系方式和我们联系。
* [社区和讨论](https://www.ossez.com/tag/chat-gpt)
| 联系方式名称 | 联系方式 |
|------------------|---------------------------------------|
| 电子邮件Email | [yhu@ossez.com](mailto:yhu@ossez.com) |
| QQ 或微信WeChat | 103899765 |
| QQ 交流群 | 15186112 |
| 社区论坛 Community | https://www.ossez.com/tag/chat-gpt |
# 公众平台
我们建议您通过社区论坛来和我们进行沟通,请关注我们公众平台上的账号
## 微信公众号
![](https://cdn.ossez.com/img/sharkfly/sharkfly-qr-wechat-search-w400.png)
关注公众号以后,可以通过向这个公众号发送消息来测试 ChatGPT 的微信消息集成功能。
<img src="https://cdn.ossez.com/discourse-uploads/original/2X/5/5f1cf67c4349029be682a30268df06d77202d510.png" width="600">
有关更多 ChatGPT 的讨论,请访问我们的 [ChatGPT 社区](https://www.ossez.com/tag/chat-gpt)。
## 头条号
我们也在头条号上创建了我们的公众号,请扫描下面的 QR 关注我们的头条号。
![](https://cdn.ossez.com/img/cwikius/cwikus-qr-toutiao.png)
## 知乎
请关注我们的知乎https://www.zhihu.com/people/huyuchengus
# Deprecated OpenAI API Endpoint
* [Answers](https://help.openai.com/en/articles/6233728-answers-transition-guide),
* [Classifications](https://help.openai.com/en/articles/6272941-classifications-transition-guide),
* [Searches](https://help.openai.com/en/articles/6272952-search-transition-guide)
APIs are deprecated, and will stop working on December 3rd, 2022.
OpenAI has deprecated all Engine-based APIs.
See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below for more info.
# How To Use
Includes the following artifacts: Includes the following artifacts:
- `api` : request/response POJOs for the GPT-3 engine, completion, and search APIs. - `api` : request/response POJOs for the GPT-3 engine, completion, and search APIs.
- `client` : a basic retrofit client for the GPT-3 endpoints, includes the `api` module - `client` : a basic retrofit client for the GPT-3 endpoints, includes the `api` module
as well as an example project using the client. as well as an example project using the client.
## Supported APIs
- [Models](https://beta.openai.com/docs/api-reference/models)
- [Completions](https://beta.openai.com/docs/api-reference/completions)
- [Edits](https://beta.openai.com/docs/api-reference/edits)
- [Embeddings](https://beta.openai.com/docs/api-reference/embeddings)
- [Files](https://beta.openai.com/docs/api-reference/files)
- [Fine-tunes](https://beta.openai.com/docs/api-reference/fine-tunes)
- [Moderations](https://beta.openai.com/docs/api-reference/moderations)
#### Deprecated by OpenAI
- [Searches](https://beta.openai.com/docs/api-reference/searches)
- [Classifications](https://beta.openai.com/docs/api-reference/classifications)
- [Answers](https://beta.openai.com/docs/api-reference/answers)
- [Engines](https://beta.openai.com/docs/api-reference/engines)
## Usage ## Usage
### Importing into a gradle project ### Importing into a gradle project
`implementation 'com.theokanning.openai-gpt3-java:api:<version>'` `implementation 'com.theokanning.openai-gpt3-java:api:<version>'`
or or
`implementation 'com.theokanning.openai-gpt3-java:client:<version>'` `implementation 'com.theokanning.openai-gpt3-java:client:<version>'`
### Using OpenAiService ### Using OpenAiService
If you're looking for the fastest solution, import the `client` and use [OpenAiService](client/src/main/java/com/theokanning/openai/OpenAiService.java).
If you're looking for the fastest solution, import the `client` and
use [OpenAiService](client/src/main/java/com/theokanning/openai/OpenAiService.java).
``` ```
OpenAiService service = new OpenAiService("your_token"); OpenAiService service = new OpenAiService("your_token");
CompletionRequest completionRequest = CompletionRequest.builder() CompletionRequest completionRequest = CompletionRequest.builder()
@ -51,27 +98,56 @@ service.createCompletion(completionRequest).getChoices().forEach(System.out::pri
``` ```
### Using OpenAiApi Retrofit client ### Using OpenAiApi 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)) 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. and set your converter factory to use snake case and only include non-null fields.
### Using data classes only ### Using data classes only
If you want to make your own client, just import the POJOs from the `api` module. 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. Your client will need to use snake case to work with the OpenAI API.
## Running the example project ## Running the example project
All the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your OpenAI api token
``` There is an [example](https://github.com/honeymoose/OpenAI-J/blob/main/example/src/main/java/com/ossez/openai/example/OpenAiApiExample.java) project
export OPENAI_TOKEN="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" with a OpenAiApiExample file contain main function to run.
./gradlew example:run
``` Also, you can run all tests by JUnit too.
[OpenAI-J 如何进行测试](https://www.ossez.com/t/openai-j/14338)
## Deprecated Endpoints ## Deprecated Endpoints
OpenAI has deprecated engine-based endpoints in favor of model-based endpoints.
For example, instead of using `v1/engines/{engine_id}/completions`, switch to `v1/completions` and specify the model in the `CompletionRequest`. OpenAI has deprecated engine-based endpoints in favor of model-based endpoints.
For example, instead of using `v1/engines/{engine_id}/completions`, switch to `v1/completions` and specify the model in
the `CompletionRequest`.
The code includes upgrade instructions for all deprecated endpoints. The code includes upgrade instructions for all deprecated endpoints.
I won't remove the old endpoints from this library until OpenAI shuts them down. I won't remove the old endpoints from this library until OpenAI shuts them down.
## License # FAQ (常见问题)
Published under the MIT License
## Supported APIs
- [Models](https://beta.openai.com/docs/api-reference/models)
- [Completions](https://beta.openai.com/docs/api-reference/completions)
- [Edits](https://beta.openai.com/docs/api-reference/edits)
- [Embeddings](https://beta.openai.com/docs/api-reference/embeddings)
- [Files](https://beta.openai.com/docs/api-reference/files)
- [Fine-tunes](https://beta.openai.com/docs/api-reference/fine-tunes)
- [Moderations](https://beta.openai.com/docs/api-reference/moderations)
## Deprecated by OpenAI
- [Searches](https://beta.openai.com/docs/api-reference/searches)
- [Classifications](https://beta.openai.com/docs/api-reference/classifications)
- [Answers](https://beta.openai.com/docs/api-reference/answers)
- [Engines](https://beta.openai.com/docs/api-reference/engines)
# License许可证
[OpenAI-J is licensed under the MIT License](https://github.com/honeymoose/openai-j/blob/main/LICENSE)

View File

@ -1,13 +0,0 @@
apply plugin: 'java-library'
apply plugin: "com.vanniktech.maven.publish"
dependencies {
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
compileOnly 'org.projectlombok:lombok:1.18.24'
annotationProcessor 'org.projectlombok:lombok:1.18.24'
}
compileJava {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}

View File

@ -1,3 +0,0 @@
POM_ARTIFACT_ID=api
POM_NAME=api
POM_DESCRIPTION=Basic java objects for the OpenAI GPT-3 API

77
api/pom.xml Normal file
View File

@ -0,0 +1,77 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j-api</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<name>OpenAI J Api</name>
<description>The module that constitutes the main USRealEstate data process system</description>
<licenses>
<license>
<name>The MIT license</name>
<url>https://opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>YuCheng Hu</name>
<id>honeymoose</id>
<email>huyuchengus@gmail.com</email>
<timezone>-5</timezone>
<organization>Open Source</organization>
<roles>
<role>Sr. Java Developer</role>
</roles>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/honeymoose/OpenAI-J.git</connection>
<developerConnection>scm:git:ssh://git@github.com/honeymoose/OpenAI-J.git</developerConnection>
<url>https://github.com/honeymoose/OpenAI-J</url>
<tag>HEAD</tag>
</scm>
<issueManagement>
<system>JIRA</system>
<url>http://bug.ossez.com/projects/USVisaTrack</url>
</issueManagement>
<dependencies>
<dependency>
<!-- for JRE requirement check annotation -->
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-annotations</artifactId>
<version>1.9</version>
<scope>provided</scope>
<optional>true</optional><!-- no need to have this at runtime -->
</dependency>
</dependencies>
<build>
<defaultGoal>package</defaultGoal>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>${basedir}/src/filter/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
</profiles>
</project>

View File

@ -0,0 +1,48 @@
package com.ossez.openai;
/**
* A response when deleting an object
*/
public class DeleteResult {
/**
* The id of the object.
*/
String id;
/**
* The type of object deleted, for example "file" or "model"
*/
String object;
/**
* True if successfully deleted
*/
boolean deleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}

View File

@ -0,0 +1,33 @@
package com.ossez.openai;
import java.util.List;
public class OpenAiResponse<T> {
/**
* A list containing the actual results
*/
public List<T> data;
/**
* The type of object returned, should be "list"
*/
public String object;
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
}

View File

@ -0,0 +1,47 @@
package com.ossez.openai;
/**
* The OpenAI resources used by a request
*/
public class Usage {
/**
* The number of prompt tokens used.
*/
long promptTokens;
/**
* The number of completion tokens used.
*/
long completionTokens;
/**
* The number of total tokens used
*/
long totalTokens;
public long getPromptTokens() {
return promptTokens;
}
public void setPromptTokens(long promptTokens) {
this.promptTokens = promptTokens;
}
public long getCompletionTokens() {
return completionTokens;
}
public void setCompletionTokens(long completionTokens) {
this.completionTokens = completionTokens;
}
public long getTotalTokens() {
return totalTokens;
}
public void setTotalTokens(long totalTokens) {
this.totalTokens = totalTokens;
}
}

View File

@ -0,0 +1,63 @@
package com.ossez.openai.completion;
/**
* A completion generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/completions/create
*/
public class CompletionChoice {
/**
* The generated text. Will include the prompt if {@link CompletionRequest#echo } is true
*/
String text;
/**
* This index of this completion in the returned list.
*/
Integer index;
/**
* The log probabilities of the chosen tokens and the top {@link CompletionRequest#logprobs} tokens
*/
LogProbResult logprobs;
/**
* The reason why GPT-3 stopped generating, for example "length".
*/
String finish_reason;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public LogProbResult getLogprobs() {
return logprobs;
}
public void setLogprobs(LogProbResult logprobs) {
this.logprobs = logprobs;
}
public String getFinish_reason() {
return finish_reason;
}
public void setFinish_reason(String finish_reason) {
this.finish_reason = finish_reason;
}
}

View File

@ -1,9 +1,4 @@
package com.theokanning.openai.completion; package com.ossez.openai.completion;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -14,11 +9,25 @@ import java.util.Map;
* *
* https://beta.openai.com/docs/api-reference/completions/create * https://beta.openai.com/docs/api-reference/completions/create
*/ */
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CompletionRequest { public class CompletionRequest {
public CompletionRequest(String model, String prompt, Integer maxTokens, Double temperature, Double topP, Integer n, Boolean stream, Integer logprobs, Boolean echo, List<String> stop, Double presencePenalty, Double frequencyPenalty, Integer bestOf, Map<String, Integer> logitBias, String user) {
this.model = model;
this.prompt = prompt;
this.maxTokens = maxTokens;
this.temperature = temperature;
this.topP = topP;
this.n = n;
this.stream = stream;
this.logprobs = logprobs;
this.echo = echo;
this.stop = stop;
this.presencePenalty = presencePenalty;
this.frequencyPenalty = frequencyPenalty;
this.bestOf = bestOf;
this.logitBias = logitBias;
this.user = user;
}
/** /**
* The name of the model to use. * The name of the model to use.
@ -124,4 +133,124 @@ public class CompletionRequest {
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/ */
String user; String user;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public Integer getMaxTokens() {
return maxTokens;
}
public void setMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
}
public Double getTemperature() {
return temperature;
}
public void setTemperature(Double temperature) {
this.temperature = temperature;
}
public Double getTopP() {
return topP;
}
public void setTopP(Double topP) {
this.topP = topP;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public Boolean getStream() {
return stream;
}
public void setStream(Boolean stream) {
this.stream = stream;
}
public Integer getLogprobs() {
return logprobs;
}
public void setLogprobs(Integer logprobs) {
this.logprobs = logprobs;
}
public Boolean getEcho() {
return echo;
}
public void setEcho(Boolean echo) {
this.echo = echo;
}
public List<String> getStop() {
return stop;
}
public void setStop(List<String> stop) {
this.stop = stop;
}
public Double getPresencePenalty() {
return presencePenalty;
}
public void setPresencePenalty(Double presencePenalty) {
this.presencePenalty = presencePenalty;
}
public Double getFrequencyPenalty() {
return frequencyPenalty;
}
public void setFrequencyPenalty(Double frequencyPenalty) {
this.frequencyPenalty = frequencyPenalty;
}
public Integer getBestOf() {
return bestOf;
}
public void setBestOf(Integer bestOf) {
this.bestOf = bestOf;
}
public Map<String, Integer> getLogitBias() {
return logitBias;
}
public void setLogitBias(Map<String, Integer> logitBias) {
this.logitBias = logitBias;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
} }

View File

@ -0,0 +1,101 @@
package com.ossez.openai.completion;
import java.util.List;
import java.util.Map;
public class CompletionRequestBuilder {
private String model;
private String prompt;
private Integer maxTokens;
private Double temperature;
private Double topP;
private Integer n;
private Boolean stream;
private Integer logprobs;
private Boolean echo;
private List<String> stop;
private Double presencePenalty;
private Double frequencyPenalty;
private Integer bestOf;
private Map<String, Integer> logitBias;
private String user;
public CompletionRequestBuilder setModel(String model) {
this.model = model;
return this;
}
public CompletionRequestBuilder setPrompt(String prompt) {
this.prompt = prompt;
return this;
}
public CompletionRequestBuilder setMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
return this;
}
public CompletionRequestBuilder setTemperature(Double temperature) {
this.temperature = temperature;
return this;
}
public CompletionRequestBuilder setTopP(Double topP) {
this.topP = topP;
return this;
}
public CompletionRequestBuilder setN(Integer n) {
this.n = n;
return this;
}
public CompletionRequestBuilder setStream(Boolean stream) {
this.stream = stream;
return this;
}
public CompletionRequestBuilder setLogprobs(Integer logprobs) {
this.logprobs = logprobs;
return this;
}
public CompletionRequestBuilder setEcho(Boolean echo) {
this.echo = echo;
return this;
}
public CompletionRequestBuilder setStop(List<String> stop) {
this.stop = stop;
return this;
}
public CompletionRequestBuilder setPresencePenalty(Double presencePenalty) {
this.presencePenalty = presencePenalty;
return this;
}
public CompletionRequestBuilder setFrequencyPenalty(Double frequencyPenalty) {
this.frequencyPenalty = frequencyPenalty;
return this;
}
public CompletionRequestBuilder setBestOf(Integer bestOf) {
this.bestOf = bestOf;
return this;
}
public CompletionRequestBuilder setLogitBias(Map<String, Integer> logitBias) {
this.logitBias = logitBias;
return this;
}
public CompletionRequestBuilder setUser(String user) {
this.user = user;
return this;
}
public CompletionRequest createCompletionRequest() {
return new CompletionRequest(model, prompt, maxTokens, temperature, topP, n, stream, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, logitBias, user);
}
}

View File

@ -0,0 +1,92 @@
package com.ossez.openai.completion;
import com.ossez.openai.Usage;
import java.util.List;
/**
* An object containing a response from the completion api
*
* https://beta.openai.com/docs/api-reference/completions/create
*/
public class CompletionResult {
/**
* A unique id assigned to this completion.
*/
String id;
/**
* The type of object returned, should be "text_completion"
*/
String object;
/**
* The creation time in epoch seconds.
*/
long created;
/**
* The GPT-3 model used.
*/
String model;
/**
* A list of generated completions.
*/
List<CompletionChoice> choices;
/**
* The API usage for this request
*/
Usage usage;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public List<CompletionChoice> getChoices() {
return choices;
}
public void setChoices(List<CompletionChoice> choices) {
this.choices = choices;
}
public Usage getUsage() {
return usage;
}
public void setUsage(Usage usage) {
this.usage = usage;
}
}

View File

@ -0,0 +1,63 @@
package com.ossez.openai.completion;
import java.util.List;
import java.util.Map;
public class LogProbResult {
/**
* The tokens chosen by the completion api
*/
List<String> tokens;
/**
* The log probability of each token in {@link tokens}
*/
List<Double> tokenLogprobs;
/**
* A map for each index in the completion result.
* The map contains the top {@link CompletionRequest#logprobs} tokens and their probabilities
*/
List<Map<String, Double>> topLogprobs;
/**
* The character offset from the start of the returned text for each of the chosen tokens.
*/
List<Integer> textOffset;
public List<String> getTokens() {
return tokens;
}
public void setTokens(List<String> tokens) {
this.tokens = tokens;
}
public List<Double> getTokenLogprobs() {
return tokenLogprobs;
}
public void setTokenLogprobs(List<Double> tokenLogprobs) {
this.tokenLogprobs = tokenLogprobs;
}
public List<Map<String, Double>> getTopLogprobs() {
return topLogprobs;
}
public void setTopLogprobs(List<Map<String, Double>> topLogprobs) {
this.topLogprobs = topLogprobs;
}
public List<Integer> getTextOffset() {
return textOffset;
}
public void setTextOffset(List<Integer> textOffset) {
this.textOffset = textOffset;
}
}

View File

@ -0,0 +1,37 @@
package com.ossez.openai.edit;
/**
* An edit generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
public class EditChoice {
/**
* The edited text.
*/
String text;
/**
* This index of this completion in the returned list.
*/
Integer index;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
}

View File

@ -1,18 +1,23 @@
package com.theokanning.openai.edit; package com.ossez.openai.edit;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*; import org.checkerframework.checker.nullness.qual.NonNull;
/** /**
* Given a prompt and an instruction, OpenAi will return an edited version of the prompt * Given a prompt and an instruction, OpenAi will return an edited version of the prompt
* *
* https://beta.openai.com/docs/api-reference/edits/create * https://beta.openai.com/docs/api-reference/edits/create
*/ */
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class EditRequest { public class EditRequest {
public EditRequest(String model, String input, @NonNull String instruction, Integer n, Double temperature, Double topP) {
this.model = model;
this.input = input;
this.instruction = instruction;
this.n = n;
this.temperature = temperature;
this.topP = topP;
}
/** /**
* The name of the model to use. * The name of the model to use.
@ -54,4 +59,52 @@ public class EditRequest {
*/ */
@JsonProperty("top_p") @JsonProperty("top_p")
Double topP; Double topP;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getInstruction() {
return instruction;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public Double getTemperature() {
return temperature;
}
public void setTemperature(Double temperature) {
this.temperature = temperature;
}
public Double getTopP() {
return topP;
}
public void setTopP(Double topP) {
this.topP = topP;
}
} }

View File

@ -0,0 +1,46 @@
package com.ossez.openai.edit;
import org.checkerframework.checker.nullness.qual.NonNull;
public class EditRequestBuilder {
private String model;
private String input;
private @NonNull String instruction;
private Integer n;
private Double temperature;
private Double topP;
public EditRequestBuilder setModel(String model) {
this.model = model;
return this;
}
public EditRequestBuilder setInput(String input) {
this.input = input;
return this;
}
public EditRequestBuilder setInstruction(@NonNull String instruction) {
this.instruction = instruction;
return this;
}
public EditRequestBuilder setN(Integer n) {
this.n = n;
return this;
}
public EditRequestBuilder setTemperature(Double temperature) {
this.temperature = temperature;
return this;
}
public EditRequestBuilder setTopP(Double topP) {
this.topP = topP;
return this;
}
public EditRequest createEditRequest() {
return new EditRequest(model, input, instruction, n, temperature, topP);
}
}

View File

@ -0,0 +1,67 @@
package com.ossez.openai.edit;
import com.ossez.openai.Usage;
import java.util.List;
/**
* A list of edits generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
public class EditResult {
/**
* The type of object returned, should be "edit"
*/
public String object;
/**
* The creation time in epoch milliseconds.
*/
public long created;
/**
* A list of generated edits.
*/
public List<EditChoice> choices;
/**
* The API usage for this request
*/
public Usage usage;
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public List<EditChoice> getChoices() {
return choices;
}
public void setChoices(List<EditChoice> choices) {
this.choices = choices;
}
public Usage getUsage() {
return usage;
}
public void setUsage(Usage usage) {
this.usage = usage;
}
}

View File

@ -0,0 +1,55 @@
package com.ossez.openai.edit;
import com.ossez.openai.Usage;
/**
* An object containing the API usage for an edit request
*
* Deprecated, use {@link Usage} instead
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
@Deprecated
public class EditUsage {
/**
* The number of prompt tokens consumed.
*/
String promptTokens;
/**
* The number of completion tokens consumed.
*/
String completionTokens;
/**
* The number of total tokens consumed.
*/
String totalTokens;
public String getPromptTokens() {
return promptTokens;
}
public void setPromptTokens(String promptTokens) {
this.promptTokens = promptTokens;
}
public String getCompletionTokens() {
return completionTokens;
}
public void setCompletionTokens(String completionTokens) {
this.completionTokens = completionTokens;
}
public String getTotalTokens() {
return totalTokens;
}
public void setTotalTokens(String totalTokens) {
this.totalTokens = totalTokens;
}
}

View File

@ -0,0 +1,53 @@
package com.ossez.openai.embedding;
import java.util.List;
/**
* Represents an embedding returned by the embedding api
*
* https://beta.openai.com/docs/api-reference/classifications/create
*/
public class Embedding {
/**
* The type of object returned, should be "embedding"
*/
String object;
/**
* The embedding vector
*/
List<Double> embedding;
/**
* The position of this embedding in the list
*/
Integer index;
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public List<Double> getEmbedding() {
return embedding;
}
public void setEmbedding(List<Double> embedding) {
this.embedding = embedding;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
}

View File

@ -1,19 +1,18 @@
package com.theokanning.openai.embedding; package com.ossez.openai.embedding;
import lombok.*;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List; import java.util.List;
/**
* Creates an embedding vector representing the input text.
*
* https://beta.openai.com/docs/api-reference/embeddings/create
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class EmbeddingRequest { public class EmbeddingRequest {
public EmbeddingRequest(String model, @NonNull List<String> input, String user) {
this.model = model;
this.input = input;
this.user = user;
}
/** /**
* The name of the model to use. * The name of the model to use.
@ -36,4 +35,28 @@ public class EmbeddingRequest {
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/ */
String user; String user;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public List<String> getInput() {
return input;
}
public void setInput(List<String> input) {
this.input = input;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
} }

View File

@ -0,0 +1,30 @@
package com.ossez.openai.embedding;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
public class EmbeddingRequestBuilder {
private String model;
private @NonNull List<String> input;
private String user;
public EmbeddingRequestBuilder setModel(String model) {
this.model = model;
return this;
}
public EmbeddingRequestBuilder setInput(@NonNull List<String> input) {
this.input = input;
return this;
}
public EmbeddingRequestBuilder setUser(String user) {
this.user = user;
return this;
}
public EmbeddingRequest createEmbeddingRequest() {
return new EmbeddingRequest(model, input, user);
}
}

View File

@ -0,0 +1,66 @@
package com.ossez.openai.embedding;
import com.ossez.openai.Usage;
import java.util.List;
/**
* An object containing a response from the answer api
*
* https://beta.openai.com/docs/api-reference/embeddings/create
*/
public class EmbeddingResult {
/**
* The GPT-3 model used for generating embeddings
*/
String model;
/**
* The type of object returned, should be "list"
*/
String object;
/**
* A list of the calculated embeddings
*/
List<Embedding> data;
/**
* The API usage for this request
*/
Usage usage;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public List<Embedding> getData() {
return data;
}
public void setData(List<Embedding> data) {
this.data = data;
}
public Usage getUsage() {
return usage;
}
public void setUsage(Usage usage) {
this.usage = usage;
}
}

View File

@ -1,6 +1,5 @@
package com.theokanning.openai.engine; package com.ossez.openai.engine;
import lombok.Data;
/** /**
* GPT-3 engine details * GPT-3 engine details
@ -8,7 +7,8 @@ import lombok.Data;
* https://beta.openai.com/docs/api-reference/retrieve-engine * https://beta.openai.com/docs/api-reference/retrieve-engine
*/ */
@Deprecated @Deprecated
@Data
public class Engine { public class Engine {
/** /**
* An identifier for this engine, used to specify an engine for completions or searching. * An identifier for this engine, used to specify an engine for completions or searching.
@ -29,4 +29,36 @@ public class Engine {
* Whether the engine is ready to process requests or not * Whether the engine is ready to process requests or not
*/ */
public boolean ready; public boolean ready;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public boolean isReady() {
return ready;
}
public void setReady(boolean ready) {
this.ready = ready;
}
} }

View File

@ -0,0 +1,90 @@
package com.ossez.openai.file;
/**
* A file uploaded to OpenAi
*
* https://beta.openai.com/docs/api-reference/files
*/
public class File {
/**
* The unique id of this file.
*/
String id;
/**
* The type of object returned, should be "file".
*/
String object;
/**
* File size in bytes.
*/
Long bytes;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* The name of the file.
*/
String filename;
/**
* Description of the file's purpose.
*/
String purpose;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public Long getBytes() {
return bytes;
}
public void setBytes(Long bytes) {
this.bytes = bytes;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
}

View File

@ -0,0 +1,62 @@
package com.ossez.openai.finetune;
/**
* An object representing an event in the lifecycle of a fine-tuning job
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
public class FineTuneEvent {
/**
* The type of object returned, should be "fine-tune-event".
*/
String object;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* The log level of this message.
*/
String level;
/**
* The event message.
*/
String message;
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -1,7 +1,7 @@
package com.theokanning.openai.finetune; package com.ossez.openai.finetune;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*; import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List; import java.util.List;
@ -11,10 +11,7 @@ import java.util.List;
* *
* https://beta.openai.com/docs/api-reference/fine-tunes/create * https://beta.openai.com/docs/api-reference/fine-tunes/create
*/ */
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class FineTuneRequest { public class FineTuneRequest {
/** /**
@ -108,4 +105,100 @@ public class FineTuneRequest {
* A string of up to 40 characters that will be added to your fine-tuned model name. * A string of up to 40 characters that will be added to your fine-tuned model name.
*/ */
String suffix; String suffix;
public String getTrainingFile() {
return trainingFile;
}
public void setTrainingFile(String trainingFile) {
this.trainingFile = trainingFile;
}
public String getValidationFile() {
return validationFile;
}
public void setValidationFile(String validationFile) {
this.validationFile = validationFile;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Integer getnEpochs() {
return nEpochs;
}
public void setnEpochs(Integer nEpochs) {
this.nEpochs = nEpochs;
}
public Integer getBatchSize() {
return batchSize;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
public Double getLearningRateMultiplier() {
return learningRateMultiplier;
}
public void setLearningRateMultiplier(Double learningRateMultiplier) {
this.learningRateMultiplier = learningRateMultiplier;
}
public Double getPromptLossWeight() {
return promptLossWeight;
}
public void setPromptLossWeight(Double promptLossWeight) {
this.promptLossWeight = promptLossWeight;
}
public Boolean getComputeClassificationMetrics() {
return computeClassificationMetrics;
}
public void setComputeClassificationMetrics(Boolean computeClassificationMetrics) {
this.computeClassificationMetrics = computeClassificationMetrics;
}
public Integer getClassificationNClasses() {
return classificationNClasses;
}
public void setClassificationNClasses(Integer classificationNClasses) {
this.classificationNClasses = classificationNClasses;
}
public String getClassificationPositiveClass() {
return classificationPositiveClass;
}
public void setClassificationPositiveClass(String classificationPositiveClass) {
this.classificationPositiveClass = classificationPositiveClass;
}
public List<Double> getClassificationBetas() {
return classificationBetas;
}
public void setClassificationBetas(List<Double> classificationBetas) {
this.classificationBetas = classificationBetas;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
} }

View File

@ -0,0 +1,184 @@
package com.ossez.openai.finetune;
import com.ossez.openai.file.File;
import java.util.List;
/**
* An object describing a fine-tuned model. Returned by multiple fine-tune requests.
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
public class FineTuneResult {
/**
* The ID of the fine-tuning job.
*/
String id;
/**
* The type of object returned, should be "fine-tune".
*/
String object;
/**
* The name of the base model.
*/
String model;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* List of events in this job's lifecycle. Null when getting a list of fine-tune jobs.
*/
List<FineTuneEvent> events;
/**
* The ID of the fine-tuned model, null if tuning job is not finished.
* This is the id used to call the model.
*/
String fineTunedModel;
/**
* The specified hyper-parameters for the tuning job.
*/
HyperParameters hyperparams;
/**
* The ID of the organization this model belongs to.
*/
String organizationId;
/**
* Result files for this fine-tune job.
*/
List<File> resultFiles;
/**
* The status os the fine-tune job. "pending", "succeeded", or "cancelled"
*/
String status;
/**
* Training files for this fine-tune job.
*/
List<File> trainingFiles;
/**
* The last update time in epoch seconds.
*/
Long updatedAt;
/**
* Validation files for this fine-tune job.
*/
List<File> validationFiles;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public List<FineTuneEvent> getEvents() {
return events;
}
public void setEvents(List<FineTuneEvent> events) {
this.events = events;
}
public String getFineTunedModel() {
return fineTunedModel;
}
public void setFineTunedModel(String fineTunedModel) {
this.fineTunedModel = fineTunedModel;
}
public HyperParameters getHyperparams() {
return hyperparams;
}
public void setHyperparams(HyperParameters hyperparams) {
this.hyperparams = hyperparams;
}
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
public List<File> getResultFiles() {
return resultFiles;
}
public void setResultFiles(List<File> resultFiles) {
this.resultFiles = resultFiles;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<File> getTrainingFiles() {
return trainingFiles;
}
public void setTrainingFiles(List<File> trainingFiles) {
this.trainingFiles = trainingFiles;
}
public Long getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
public List<File> getValidationFiles() {
return validationFiles;
}
public void setValidationFiles(List<File> validationFiles) {
this.validationFiles = validationFiles;
}
}

View File

@ -0,0 +1,64 @@
package com.ossez.openai.finetune;
/**
* Fine-tuning job hyperparameters
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
public class HyperParameters {
/**
* The batch size to use for training.
*/
String batchSize;
/**
* The learning rate multiplier to use for training.
*/
Double learningRateMultiplier;
/**
* The number of epochs to train the model for.
*/
Integer nEpochs;
/**
* The weight to use for loss on the prompt tokens.
*/
Double promptLossWeight;
public String getBatchSize() {
return batchSize;
}
public void setBatchSize(String batchSize) {
this.batchSize = batchSize;
}
public Double getLearningRateMultiplier() {
return learningRateMultiplier;
}
public void setLearningRateMultiplier(Double learningRateMultiplier) {
this.learningRateMultiplier = learningRateMultiplier;
}
public Integer getnEpochs() {
return nEpochs;
}
public void setnEpochs(Integer nEpochs) {
this.nEpochs = nEpochs;
}
public Double getPromptLossWeight() {
return promptLossWeight;
}
public void setPromptLossWeight(Double promptLossWeight) {
this.promptLossWeight = promptLossWeight;
}
}

View File

@ -0,0 +1,80 @@
package com.ossez.openai.image;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A request for OpenAi to edit an image based on a prompt
* All fields except prompt are optional
*
* https://beta.openai.com/docs/api-reference/images/create-edit
*/
public class CreateImageEditRequest {
/**
* A text description of the desired image(s). The maximum length in 1000 characters.
*/
@NonNull
String prompt;
/**
* The number of images to generate. Must be between 1 and 10. Defaults to 1.
*/
Integer n;
/**
* The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024".
*/
String size;
/**
* The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url.
*/
String responseFormat;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

View File

@ -0,0 +1,79 @@
package com.ossez.openai.image;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A request for OpenAi to create an image based on a prompt
* All fields except prompt are optional
*
* https://beta.openai.com/docs/api-reference/images/create
*/
public class CreateImageRequest {
/**
* A text description of the desired image(s). The maximum length in 1000 characters.
*/
@NonNull
String prompt;
/**
* The number of images to generate. Must be between 1 and 10. Defaults to 1.
*/
Integer n;
/**
* The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024".
*/
String size;
/**
* The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url.
*/
String responseFormat;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

View File

@ -0,0 +1,63 @@
package com.ossez.openai.image;
/**
* A request for OpenAi to create a variation of an image
* All fields are optional
*
* https://beta.openai.com/docs/api-reference/images/create-variation
*/
public class CreateImageVariationRequest {
/**
* The number of images to generate. Must be between 1 and 10. Defaults to 1.
*/
Integer n;
/**
* The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024".
*/
String size;
/**
* The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url.
*/
String responseFormat;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

View File

@ -0,0 +1,39 @@
package com.ossez.openai.image;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* An object containing either a URL or a base 64 encoded image.
*
* https://beta.openai.com/docs/api-reference/images
*/
public class Image {
/**
* The URL where the image can be accessed.
*/
String url;
/**
* Base64 encoded image string.
*/
@JsonProperty("b64_json")
String b64Json;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getB64Json() {
return b64Json;
}
public void setB64Json(String b64Json) {
this.b64Json = b64Json;
}
}

View File

@ -0,0 +1,39 @@
package com.ossez.openai.image;
import java.util.List;
/**
* An object with a list of image results.
*
* https://beta.openai.com/docs/api-reference/images
*/
public class ImageResult {
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* List of image results.
*/
List<Image> data;
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public List<Image> getData() {
return data;
}
public void setData(List<Image> data) {
this.data = data;
}
}

View File

@ -0,0 +1,89 @@
package com.ossez.openai.model;
import java.util.List;
/**
* GPT-3 model details
*
* https://beta.openai.com/docs/api-reference/models
*/
public class Model {
/**
* An identifier for this model, used to specify the model when making completions, etc
*/
public String id;
/**
* The type of object returned, should be "model"
*/
public String object;
/**
* The owner of the GPT-3 model, typically "openai"
*/
public String ownedBy;
/**
* List of permissions for this model
*/
public List<Permission> permission;
/**
* The root model that this and its parent (if applicable) are based on
*/
public String root;
/**
* The parent model that this is based on
*/
public String parent;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getOwnedBy() {
return ownedBy;
}
public void setOwnedBy(String ownedBy) {
this.ownedBy = ownedBy;
}
public List<Permission> getPermission() {
return permission;
}
public void setPermission(List<Permission> permission) {
this.permission = permission;
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
}

View File

@ -0,0 +1,140 @@
package com.ossez.openai.model;
/**
* GPT-3 model permissions
* I couldn't find documentation for the specific permissions, and I've elected to leave them undocumented rather than
* write something incorrect.
*
* https://beta.openai.com/docs/api-reference/models
*/
public class Permission {
/**
* An identifier for this model permission
*/
public String id;
/**
* The type of object returned, should be "model_permission"
*/
public String object;
/**
* The creation time in epoch seconds.
*/
public long created;
public boolean allowCreateEngine;
public boolean allowSampling;
public boolean allowLogProbs;
public boolean allowSearchIndices;
public boolean allowView;
public boolean allowFineTuning;
public String organization;
public String group;
public boolean isBlocking;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public boolean isAllowCreateEngine() {
return allowCreateEngine;
}
public void setAllowCreateEngine(boolean allowCreateEngine) {
this.allowCreateEngine = allowCreateEngine;
}
public boolean isAllowSampling() {
return allowSampling;
}
public void setAllowSampling(boolean allowSampling) {
this.allowSampling = allowSampling;
}
public boolean isAllowLogProbs() {
return allowLogProbs;
}
public void setAllowLogProbs(boolean allowLogProbs) {
this.allowLogProbs = allowLogProbs;
}
public boolean isAllowSearchIndices() {
return allowSearchIndices;
}
public void setAllowSearchIndices(boolean allowSearchIndices) {
this.allowSearchIndices = allowSearchIndices;
}
public boolean isAllowView() {
return allowView;
}
public void setAllowView(boolean allowView) {
this.allowView = allowView;
}
public boolean isAllowFineTuning() {
return allowFineTuning;
}
public void setAllowFineTuning(boolean allowFineTuning) {
this.allowFineTuning = allowFineTuning;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public boolean isBlocking() {
return isBlocking;
}
public void setBlocking(boolean blocking) {
isBlocking = blocking;
}
}

View File

@ -1,13 +1,11 @@
package com.theokanning.openai.moderation; package com.ossez.openai.moderation;
import lombok.Data;
/** /**
* An object containing the moderation data for a single input string * An object containing the moderation data for a single input string
* *
* https://beta.openai.com/docs/api-reference/moderations/create * https://beta.openai.com/docs/api-reference/moderations/create
*/ */
@Data
public class Moderation { public class Moderation {
/** /**
* Set to true if the model classifies the content as violating OpenAI's content policy, false otherwise * Set to true if the model classifies the content as violating OpenAI's content policy, false otherwise
@ -27,4 +25,28 @@ public class Moderation {
* The scores should not be interpreted as probabilities. * The scores should not be interpreted as probabilities.
*/ */
public ModerationCategoryScores categoryScores; public ModerationCategoryScores categoryScores;
public boolean isFlagged() {
return flagged;
}
public void setFlagged(boolean flagged) {
this.flagged = flagged;
}
public ModerationCategories getCategories() {
return categories;
}
public void setCategories(ModerationCategories categories) {
this.categories = categories;
}
public ModerationCategoryScores getCategoryScores() {
return categoryScores;
}
public void setCategoryScores(ModerationCategoryScores categoryScores) {
this.categoryScores = categoryScores;
}
} }

View File

@ -0,0 +1,86 @@
package com.ossez.openai.moderation;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* An object containing the flags for each moderation category
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
public class ModerationCategories {
public boolean hate;
@JsonProperty("hate/threatening")
public boolean hateThreatening;
@JsonProperty("self-harm")
public boolean selfHarm;
public boolean sexual;
@JsonProperty("sexual/minors")
public boolean sexualMinors;
public boolean violence;
@JsonProperty("violence/graphic")
public boolean violenceGraphic;
public boolean isHate() {
return hate;
}
public void setHate(boolean hate) {
this.hate = hate;
}
public boolean isHateThreatening() {
return hateThreatening;
}
public void setHateThreatening(boolean hateThreatening) {
this.hateThreatening = hateThreatening;
}
public boolean isSelfHarm() {
return selfHarm;
}
public void setSelfHarm(boolean selfHarm) {
this.selfHarm = selfHarm;
}
public boolean isSexual() {
return sexual;
}
public void setSexual(boolean sexual) {
this.sexual = sexual;
}
public boolean isSexualMinors() {
return sexualMinors;
}
public void setSexualMinors(boolean sexualMinors) {
this.sexualMinors = sexualMinors;
}
public boolean isViolence() {
return violence;
}
public void setViolence(boolean violence) {
this.violence = violence;
}
public boolean isViolenceGraphic() {
return violenceGraphic;
}
public void setViolenceGraphic(boolean violenceGraphic) {
this.violenceGraphic = violenceGraphic;
}
}

View File

@ -0,0 +1,86 @@
package com.ossez.openai.moderation;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* An object containing the scores for each moderation category
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
public class ModerationCategoryScores {
public double hate;
@JsonProperty("hate/threatening")
public double hateThreatening;
@JsonProperty("self-harm")
public double selfHarm;
public double sexual;
@JsonProperty("sexual/minors")
public double sexualMinors;
public double violence;
@JsonProperty("violence/graphic")
public double violenceGraphic;
public double getHate() {
return hate;
}
public void setHate(double hate) {
this.hate = hate;
}
public double getHateThreatening() {
return hateThreatening;
}
public void setHateThreatening(double hateThreatening) {
this.hateThreatening = hateThreatening;
}
public double getSelfHarm() {
return selfHarm;
}
public void setSelfHarm(double selfHarm) {
this.selfHarm = selfHarm;
}
public double getSexual() {
return sexual;
}
public void setSexual(double sexual) {
this.sexual = sexual;
}
public double getSexualMinors() {
return sexualMinors;
}
public void setSexualMinors(double sexualMinors) {
this.sexualMinors = sexualMinors;
}
public double getViolence() {
return violence;
}
public void setViolence(double violence) {
this.violence = violence;
}
public double getViolenceGraphic() {
return violenceGraphic;
}
public void setViolenceGraphic(double violenceGraphic) {
this.violenceGraphic = violenceGraphic;
}
}

View File

@ -1,18 +1,14 @@
package com.theokanning.openai.moderation; package com.ossez.openai.moderation;
import lombok.*;
import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull;
/** /**
* A request for OpenAi to detect if text violates OpenAi's content policy. * A request for OpenAi to detect if text violates OpenAi's content policy.
* *
* https://beta.openai.com/docs/api-reference/moderations/create * https://beta.openai.com/docs/api-reference/moderations/create
*/ */
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ModerationRequest { public class ModerationRequest {
/** /**
@ -25,4 +21,20 @@ public class ModerationRequest {
* The name of the model to use, defaults to text-moderation-stable. * The name of the model to use, defaults to text-moderation-stable.
*/ */
String model; String model;
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
} }

View File

@ -0,0 +1,50 @@
package com.ossez.openai.moderation;
import java.util.List;
/**
* An object containing a response from the moderation api
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
public class ModerationResult {
/**
* A unique id assigned to this moderation.
*/
public String id;
/**
* The GPT-3 model used.
*/
public String model;
/**
* A list of moderation scores.
*/
public List<Moderation> results;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public List<Moderation> getResults() {
return results;
}
public void setResults(List<Moderation> results) {
this.results = results;
}
}

View File

@ -1,24 +0,0 @@
package com.theokanning.openai;
import lombok.Data;
/**
* A response when deleting an object
*/
@Data
public class DeleteResult {
/**
* The id of the object.
*/
String id;
/**
* The type of object deleted, for example "file" or "model"
*/
String object;
/**
* True if successfully deleted
*/
boolean deleted;
}

View File

@ -1,21 +0,0 @@
package com.theokanning.openai;
import lombok.Data;
import java.util.List;
/**
* A wrapper class to fit the OpenAI engine and search endpoints
*/
@Data
public class OpenAiResponse<T> {
/**
* A list containing the actual results
*/
public List<T> data;
/**
* The type of object returned, should be "list"
*/
public String object;
}

View File

@ -1,24 +0,0 @@
package com.theokanning.openai;
import lombok.Data;
/**
* The OpenAI resources used by a request
*/
@Data
public class Usage {
/**
* The number of prompt tokens used.
*/
long promptTokens;
/**
* The number of completion tokens used.
*/
long completionTokens;
/**
* The number of total tokens used
*/
long totalTokens;
}

View File

@ -1,141 +0,0 @@
package com.theokanning.openai.answer;
import lombok.*;
import java.util.List;
import java.util.Map;
/**
* Given a question, a set of documents, and some examples, the API generates an answer to the question based
* on the information in the set of documents. This is useful for question-answering applications on sources of truth,
* like company documentation or a knowledge base.
*
* Documentation taken from
* https://beta.openai.com/docs/api-reference/answers/create
*/
@Deprecated
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class AnswerRequest {
/**
* ID of the engine to use for completion.
*/
@NonNull
String model;
/**
* Question to get answered.
*/
@NonNull
String question;
/**
* List of (question, answer) pairs that will help steer the model towards the tone and answer format you'd like.
* We recommend adding 2 to 3 examples.
*/
@NonNull
List<List<String>> examples;
/**
* A text snippet containing the contextual information used to generate the answers for the examples you provide.
*/
@NonNull
String examplesContext;
/**
* List of documents from which the answer for the input question should be derived.
* If this is an empty list, the question will be answered based on the question-answer examples.
*
* You should specify either documents or a file, but not both.
*/
List<String> documents;
/**
* The ID of an uploaded file that contains documents to search over.
* See upload file for how to upload a file of the desired format and purpose.
*
* You should specify either documents or file, but not both.
*/
String file;
/**
* ID of the engine to use for Search. You can select one of ada, babbage, curie, or davinci.
*/
String searchModel;
/**
* The maximum number of documents to be ranked by Search when using file.
* Setting it to a higher value leads to improved accuracy but with increased latency and cost.
*/
Integer maxRerank;
/**
* What sampling temperature to use. Higher values means the model will take more risks.
* Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.
*
* We generally recommend using this or {@link top_p} but not both.
*/
Double temperature;
/**
* Include the log probabilities on the logprobs most likely tokens, as well the chosen tokens.
* For example, if logprobs is 10, the API will return a list of the 10 most likely tokens.
* The API will always return the logprob of the sampled token,
* so there may be up to logprobs+1 elements in the response.
*/
Integer logprobs;
/**
* The maximum number of tokens allowed for the generated answer.
*/
Integer maxTokens;
/**
* Up to 4 sequences where the API will stop generating further tokens.
* The returned text will not contain the stop sequence.
*/
List<String> stop;
/**
* How many answers to generate for each question.
*/
Integer n;
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a json object that maps tokens (specified by their token ID in the GPT tokenizer) to an
* associated bias value from -100 to 100.
*/
Map<String, Double> logitBias;
/**
* A special boolean flag for showing metadata.
* If set to true, each document entry in the returned JSON will contain a "metadata" field.
*
* This flag only takes effect when file is set.
*/
Boolean returnMetadata;
/**
* If set to true, the returned JSON will include a "prompt" field containing the final prompt that was
* used to request a completion. This is mainly useful for debugging purposes.
*/
Boolean returnPrompt;
/**
* If an object name is in the list, we provide the full information of the object;
* otherwise, we only provide the object ID.
*
* Currently we support completion and file objects for expansion.
*/
List<String> expand;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
}

View File

@ -1,44 +0,0 @@
package com.theokanning.openai.answer;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the answer api
*
* https://beta.openai.com/docs/api-reference/answers/create
*/
@Deprecated
@Data
public class AnswerResult {
/**
* A list of generated answers to the provided question/
*/
List<String> answers;
/**
* A unique id assigned to this completion
*/
String completion;
/**
* The GPT-3 model used for completion
*/
String model;
/**
* The type of object returned, should be "answer"
*/
String object;
/**
* The GPT-3 model used for search
*/
String searchModel;
/**
* A list of the most relevant documents for the question.
*/
List<Document> selectedDocuments;
}

View File

@ -1,22 +0,0 @@
package com.theokanning.openai.answer;
import lombok.Data;
/**
* Represents an example returned by the classification api
*
* https://beta.openai.com/docs/api-reference/classifications/create
*/
@Deprecated
@Data
public class Document {
/**
* The position of this example in the example list
*/
Integer document;
/**
* The text of the example
*/
String text;
}

View File

@ -1,121 +0,0 @@
package com.theokanning.openai.classification;
import lombok.*;
import java.util.List;
import java.util.Map;
/**
* A request for OpenAi to classify text based on provided examples
* All fields are nullable.
*
* Documentation taken from
* https://beta.openai.com/docs/api-reference/classifications/create
*/
@Deprecated
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ClassificationRequest {
/**
* ID of the engine to use for completion
*/
@NonNull
String model;
/**
* Query to be classified
*/
@NonNull
String query;
/**
* A list of examples with labels, in the following format:
*
* [["The movie is so interesting.", "Positive"], ["It is quite boring.", "Negative"], ...]
*
* All the label strings will be normalized to be capitalized.
*
* You should specify either examples or file, but not both.
*/
List<List<String>> examples;
/**
* The ID of the uploaded file that contains training examples.
* See upload file for how to upload a file of the desired format and purpose.
*
* You should specify either examples or file, but not both.
*/
String file;
/**
* The set of categories being classified.
* If not specified, candidate labels will be automatically collected from the examples you provide.
* All the label strings will be normalized to be capitalized.
*/
List<String> labels;
/**
* ID of the engine to use for Search. You can select one of ada, babbage, curie, or davinci.
*/
String searchModel;
/**
* What sampling temperature to use. Higher values means the model will take more risks.
* Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.
*
* We generally recommend using this or {@link top_p} but not both.
*/
Double temperature;
/**
* Include the log probabilities on the logprobs most likely tokens, as well the chosen tokens.
* For example, if logprobs is 10, the API will return a list of the 10 most likely tokens.
* The API will always return the logprob of the sampled token,
* so there may be up to logprobs+1 elements in the response.
*/
Integer logprobs;
/**
* The maximum number of examples to be ranked by Search when using file.
* Setting it to a higher value leads to improved accuracy but with increased latency and cost.
*/
Integer maxExamples;
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a json object that maps tokens (specified by their token ID in the GPT tokenizer) to an
* associated bias value from -100 to 100.
*/
Map<String, Double> logitBias;
/**
* If set to true, the returned JSON will include a "prompt" field containing the final prompt that was
* used to request a completion. This is mainly useful for debugging purposes.
*/
Boolean returnPrompt;
/**
* A special boolean flag for showing metadata.
* If set to true, each document entry in the returned JSON will contain a "metadata" field.
*
* This flag only takes effect when file is set.
*/
Boolean returnMetadata;
/**
* If an object name is in the list, we provide the full information of the object;
* otherwise, we only provide the object ID.
*
* Currently we support completion and file objects for expansion.
*/
List<String> expand;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
}

View File

@ -1,45 +0,0 @@
package com.theokanning.openai.classification;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the classification api
* <
* https://beta.openai.com/docs/api-reference/classifications/create
*/
@Deprecated
@Data
public class ClassificationResult {
/**
* A unique id assigned to this completion
*/
String completion;
/**
* The predicted label for the query text.
*/
String label;
/**
* The GPT-3 model used for completion
*/
String model;
/**
* The type of object returned, should be "classification"
*/
String object;
/**
* The GPT-3 model used for search
*/
String searchModel;
/**
* A list of the most relevant examples for the query text.
*/
List<Example> selectedExamples;
}

View File

@ -1,27 +0,0 @@
package com.theokanning.openai.classification;
import lombok.Data;
/**
* Represents an example returned by the classification api
*
* https://beta.openai.com/docs/api-reference/classifications/create
*/
@Deprecated
@Data
public class Example {
/**
* The position of this example in the example list
*/
Integer document;
/**
* The label of the example
*/
String label;
/**
* The text of the example
*/
String text;
}

View File

@ -1,31 +0,0 @@
package com.theokanning.openai.completion;
import lombok.Data;
/**
* A completion generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/completions/create
*/
@Data
public class CompletionChoice {
/**
* The generated text. Will include the prompt if {@link CompletionRequest#echo } is true
*/
String text;
/**
* This index of this completion in the returned list.
*/
Integer index;
/**
* The log probabilities of the chosen tokens and the top {@link CompletionRequest#logprobs} tokens
*/
LogProbResult logprobs;
/**
* The reason why GPT-3 stopped generating, for example "length".
*/
String finish_reason;
}

View File

@ -1,44 +0,0 @@
package com.theokanning.openai.completion;
import com.theokanning.openai.Usage;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the completion api
*
* https://beta.openai.com/docs/api-reference/completions/create
*/
@Data
public class CompletionResult {
/**
* A unique id assigned to this completion.
*/
String id;
/**
* The type of object returned, should be "text_completion"
*/
String object;
/**
* The creation time in epoch seconds.
*/
long created;
/**
* The GPT-3 model used.
*/
String model;
/**
* A list of generated completions.
*/
List<CompletionChoice> choices;
/**
* The API usage for this request
*/
Usage usage;
}

View File

@ -1,37 +0,0 @@
package com.theokanning.openai.completion;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* Log probabilities of different token options
* Returned if {@link CompletionRequest#logprobs} is greater than zero
*
* https://beta.openai.com/docs/api-reference/create-completion
*/
@Data
public class LogProbResult {
/**
* The tokens chosen by the completion api
*/
List<String> tokens;
/**
* The log probability of each token in {@link tokens}
*/
List<Double> tokenLogprobs;
/**
* A map for each index in the completion result.
* The map contains the top {@link CompletionRequest#logprobs} tokens and their probabilities
*/
List<Map<String, Double>> topLogprobs;
/**
* The character offset from the start of the returned text for each of the chosen tokens.
*/
List<Integer> textOffset;
}

View File

@ -1,22 +0,0 @@
package com.theokanning.openai.edit;
import lombok.Data;
/**
* An edit generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
@Data
public class EditChoice {
/**
* The edited text.
*/
String text;
/**
* This index of this completion in the returned list.
*/
Integer index;
}

View File

@ -1,35 +0,0 @@
package com.theokanning.openai.edit;
import com.theokanning.openai.Usage;
import lombok.Data;
import java.util.List;
/**
* A list of edits generated by GPT-3
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
@Data
public class EditResult {
/**
* The type of object returned, should be "edit"
*/
public String object;
/**
* The creation time in epoch milliseconds.
*/
public long created;
/**
* A list of generated edits.
*/
public List<EditChoice> choices;
/**
* The API usage for this request
*/
public Usage usage;
}

View File

@ -1,30 +0,0 @@
package com.theokanning.openai.edit;
import lombok.Data;
/**
* An object containing the API usage for an edit request
*
* Deprecated, use {@link com.theokanning.openai.Usage} instead
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
@Data
@Deprecated
public class EditUsage {
/**
* The number of prompt tokens consumed.
*/
String promptTokens;
/**
* The number of completion tokens consumed.
*/
String completionTokens;
/**
* The number of total tokens consumed.
*/
String totalTokens;
}

View File

@ -1,29 +0,0 @@
package com.theokanning.openai.embedding;
import lombok.Data;
import java.util.List;
/**
* Represents an embedding returned by the embedding api
*
* https://beta.openai.com/docs/api-reference/classifications/create
*/
@Data
public class Embedding {
/**
* The type of object returned, should be "embedding"
*/
String object;
/**
* The embedding vector
*/
List<Double> embedding;
/**
* The position of this embedding in the list
*/
Integer index;
}

View File

@ -1,35 +0,0 @@
package com.theokanning.openai.embedding;
import com.theokanning.openai.Usage;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the answer api
*
* https://beta.openai.com/docs/api-reference/embeddings/create
*/
@Data
public class EmbeddingResult {
/**
* The GPT-3 model used for generating embeddings
*/
String model;
/**
* The type of object returned, should be "list"
*/
String object;
/**
* A list of the calculated embeddings
*/
List<Embedding> data;
/**
* The API usage for this request
*/
Usage usage;
}

View File

@ -1,42 +0,0 @@
package com.theokanning.openai.file;
import lombok.Data;
/**
* A file uploaded to OpenAi
*
* https://beta.openai.com/docs/api-reference/files
*/
@Data
public class File {
/**
* The unique id of this file.
*/
String id;
/**
* The type of object returned, should be "file".
*/
String object;
/**
* File size in bytes.
*/
Long bytes;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* The name of the file.
*/
String filename;
/**
* Description of the file's purpose.
*/
String purpose;
}

View File

@ -1,31 +0,0 @@
package com.theokanning.openai.finetune;
import lombok.Data;
/**
* An object representing an event in the lifecycle of a fine-tuning job
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
@Data
public class FineTuneEvent {
/**
* The type of object returned, should be "fine-tune-event".
*/
String object;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* The log level of this message.
*/
String level;
/**
* The event message.
*/
String message;
}

View File

@ -1,80 +0,0 @@
package com.theokanning.openai.finetune;
import com.theokanning.openai.file.File;
import lombok.Data;
import java.util.List;
/**
* An object describing an fine-tuned model. Returned by multiple fine-tune requests.
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
@Data
public class FineTuneResult {
/**
* The ID of the fine-tuning job.
*/
String id;
/**
* The type of object returned, should be "fine-tune".
*/
String object;
/**
* The name of the base model.
*/
String model;
/**
* The creation time in epoch seconds.
*/
Long createdAt;
/**
* List of events in this job's lifecycle. Null when getting a list of fine-tune jobs.
*/
List<FineTuneEvent> events;
/**
* The ID of the fine-tuned model, null if tuning job is not finished.
* This is the id used to call the model.
*/
String fineTunedModel;
/**
* The specified hyper-parameters for the tuning job.
*/
HyperParameters hyperparams;
/**
* The ID of the organization this model belongs to.
*/
String organizationId;
/**
* Result files for this fine-tune job.
*/
List<File> resultFiles;
/**
* The status os the fine-tune job. "pending", "succeeded", or "cancelled"
*/
String status;
/**
* Training files for this fine-tune job.
*/
List<File> trainingFiles;
/**
* The last update time in epoch seconds.
*/
Long updatedAt;
/**
* Validation files for this fine-tune job.
*/
List<File> validationFiles;
}

View File

@ -1,32 +0,0 @@
package com.theokanning.openai.finetune;
import lombok.Data;
/**
* Fine-tuning job hyperparameters
*
* https://beta.openai.com/docs/api-reference/fine-tunes
*/
@Data
public class HyperParameters {
/**
* The batch size to use for training.
*/
String batchSize;
/**
* The learning rate multiplier to use for training.
*/
Double learningRateMultiplier;
/**
* The number of epochs to train the model for.
*/
Integer nEpochs;
/**
* The weight to use for loss on the prompt tokens.
*/
Double promptLossWeight;
}

View File

@ -1,43 +0,0 @@
package com.theokanning.openai.model;
import lombok.Data;
import java.util.List;
/**
* GPT-3 model details
*
* https://beta.openai.com/docs/api-reference/models
*/
@Data
public class Model {
/**
* An identifier for this model, used to specify the model when making completions, etc
*/
public String id;
/**
* The type of object returned, should be "model"
*/
public String object;
/**
* The owner of the GPT-3 model, typically "openai"
*/
public String ownedBy;
/**
* List of permissions for this model
*/
public List<Permission> permission;
/**
* The root model that this and its parent (if applicable) are based on
*/
public String root;
/**
* The parent model that this is based on
*/
public String parent;
}

View File

@ -1,47 +0,0 @@
package com.theokanning.openai.model;
import lombok.Data;
/**
* GPT-3 model permissions
* I couldn't find documentation for the specific permissions, and I've elected to leave them undocumented rather than
* write something incorrect.
*
* https://beta.openai.com/docs/api-reference/models
*/
@Data
public class Permission {
/**
* An identifier for this model permission
*/
public String id;
/**
* The type of object returned, should be "model_permission"
*/
public String object;
/**
* The creation time in epoch seconds.
*/
public long created;
public boolean allowCreateEngine;
public boolean allowSampling;
public boolean allowLogProbs;
public boolean allowSearchIndices;
public boolean allowView;
public boolean allowFineTuning;
public String organization;
public String group;
public boolean isBlocking;
}

View File

@ -1,34 +0,0 @@
package com.theokanning.openai.moderation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.theokanning.openai.completion.CompletionChoice;
import lombok.Data;
import java.util.List;
/**
* An object containing the flags for each moderation category
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
@Data
public class ModerationCategories {
public boolean hate;
@JsonProperty("hate/threatening")
public boolean hateThreatening;
@JsonProperty("self-harm")
public boolean selfHarm;
public boolean sexual;
@JsonProperty("sexual/minors")
public boolean sexualMinors;
public boolean violence;
@JsonProperty("violence/graphic")
public boolean violenceGraphic;
}

View File

@ -1,31 +0,0 @@
package com.theokanning.openai.moderation;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* An object containing the scores for each moderation category
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
@Data
public class ModerationCategoryScores {
public double hate;
@JsonProperty("hate/threatening")
public double hateThreatening;
@JsonProperty("self-harm")
public double selfHarm;
public double sexual;
@JsonProperty("sexual/minors")
public double sexualMinors;
public double violence;
@JsonProperty("violence/graphic")
public double violenceGraphic;
}

View File

@ -1,28 +0,0 @@
package com.theokanning.openai.moderation;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the moderation api
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
@Data
public class ModerationResult {
/**
* A unique id assigned to this moderation.
*/
public String id;
/**
* The GPT-3 model used.
*/
public String model;
/**
* A list of moderation scores.
*/
public List<Moderation> results;
}

View File

@ -1,33 +0,0 @@
package com.theokanning.openai.search;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* A request to the document search api.
* GPT-3 will perform a semantic search over the documents and score them based on how related they are to the query.
* Higher scores indicate a stronger relation.
*
* https://beta.openai.com/docs/api-reference/searches
*/
@Deprecated
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class SearchRequest {
/**
* Documents to search over
*/
List<String> documents;
/**
* Search query
*/
String query;
}

View File

@ -1,28 +0,0 @@
package com.theokanning.openai.search;
import lombok.Data;
/**
* A search result for a single document.
*
* https://beta.openai.com/docs/api-reference/searches
*/
@Deprecated
@Data
public class SearchResult {
/**
* The position of this document in the request list
*/
Integer document;
/**
* The type of object returned, should be "search_result"
*/
String object;
/**
* A number measuring the document's correlation with the query.
* A higher score means a stronger relationship.
*/
Double score;
}

View File

@ -1,21 +0,0 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.19.0'
}
}
allprojects {
repositories {
mavenCentral()
}
plugins.withId("com.vanniktech.maven.publish") {
mavenPublish {
sonatypeHost = "S01"
}
}
}

View File

@ -1,21 +0,0 @@
apply plugin: 'java-library'
apply plugin: "com.vanniktech.maven.publish"
dependencies {
api project(":api")
api 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.9.0'
testImplementation(platform('org.junit:junit-bom:5.8.2'))
testImplementation('org.junit.jupiter:junit-jupiter')
}
compileJava {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
test {
useJUnitPlatform()
}

View File

@ -1,3 +0,0 @@
POM_ARTIFACT_ID=client
POM_NAME=client
POM_DESCRIPTION=Basic retrofit client for OpenAI's GPT-3 API

409
client/pom.xml Normal file
View File

@ -0,0 +1,409 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>openai-j-client</artifactId>
<packaging>jar</packaging>
<name>OpenAI J Client</name>
<description>The module that constitutes the main USRealEstate data process system</description>
<licenses>
<license>
<name>The MIT license</name>
<url>https://opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>YuCheng Hu</name>
<id>honeymoose</id>
<email>huyuchengus@gmail.com</email>
<timezone>-5</timezone>
<organization>Open Source</organization>
<roles>
<role>Sr. Java Developer</role>
</roles>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/USRealEstate/Usreio-Parent.git</connection>
<developerConnection>scm:git:ssh://git@github.com/USRealEstate/Usreio-Parent.git</developerConnection>
<url>https://github.com/USRealEstate</url>
<tag>HEAD</tag>
</scm>
<issueManagement>
<system>JIRA</system>
<url>http://bug.ossez.com/projects/USVisaTrack</url>
</issueManagement>
<properties>
<!-- *.html files are in UTF-8, and *.properties are in iso-8859-1, so this configuration is actually incorrect, but this suppresses a warning
from Maven, and as long as we don't do filtering we should be OK. -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<build.type>private</build.type>
<!-- configuration for patch tracker plugin -->
<project.patchManagement.system>github</project.patchManagement.system>
<patch.request.organisation>jenkinsci</patch.request.organisation>
<patch.request.repository>jenkins</patch.request.repository>
<project.patchManagement.url>https://api.github.com</project.patchManagement.url>
<patch.tracker.serverId>jenkins-jira</patch.tracker.serverId>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>2.8.2</log4j.version>
<maven-plugin.version>2.14</maven-plugin.version>
<matrix-project.version>1.4.1</matrix-project.version>
<sorcerer.version>0.11</sorcerer.version>
<findbugs-maven-plugin.version>3.0.4</findbugs-maven-plugin.version>
<findbugs.failOnError>true</findbugs.failOnError>
<test-annotations.version>1.2</test-annotations.version>
<access-modifier.version>1.11</access-modifier.version>
<access-modifier-annotation.version>${access-modifier.version}
</access-modifier-annotation.version> <!-- differing only where needed for timestamped snapshots -->
<access-modifier-checker.version>${access-modifier.version}</access-modifier-checker.version>
<junit-jupiter.version>5.9.0</junit-jupiter.version>
<java.level>11</java.level>
<changelog.url>https://upcex.com/changelog</changelog.url>
</properties>
<dependencies>
<!-- LOGGING WITH SELF4J AND LOG4J2 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- APACHE COMMONS -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- / APACHE COMMONS -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
</dependency>
<!-- UTILITIES -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>com.configcat</groupId>
<artifactId>configcat-java-client</artifactId>
<version>7.2.0</version>
</dependency>
<!-- /UTILITIES -->
<!-- Date and Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<!-- TEST -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.23.1</version>
<scope>test</scope>
</dependency>
<!--/ TEST -->
<dependency>
<!-- for JRE requirement check annotation -->
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-annotations</artifactId>
<version>1.9</version>
<scope>provided</scope>
<optional>true</optional><!-- no need to have this at runtime -->
</dependency>
<dependency>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>${basedir}/src/filter/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<fork>true</fork>
<compilerReuseStrategy>alwaysNew</compilerReuseStrategy>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<configuration>
<quiet>true</quiet>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<argLine>-noverify
</argLine> <!-- some versions of JDK7/8 causes VerifyError during mock tests: http://code.google.com/p/powermock/issues/detail?id=504 -->
<systemPropertyVariables>
<java.io.tmpdir>${project.build.directory}</java.io.tmpdir>
<forkedProcessTimeoutInSeconds>3600</forkedProcessTimeoutInSeconds>
<java.awt.headless>true</java.awt.headless>
</systemPropertyVariables>
<trimStackTrace>false</trimStackTrace>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.kohsuke</groupId>
<artifactId>access-modifier-checker</artifactId>
<version>${access-modifier-checker.version}</version>
</plugin>
<plugin>
<groupId>com.cloudbees</groupId>
<artifactId>maven-license-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>compile</phase>
<configuration>
<requireCompleteLicenseInfo>true</requireCompleteLicenseInfo>
<script>../licenseCompleter.groovy</script>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jvnet.localizer</groupId>
<artifactId>maven-localizer-plugin</artifactId>
<version>1.24</version>
<configuration>
<outputEncoding>UTF-8</outputEncoding>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.hudson.tools</groupId>
<artifactId>maven-encoding-plugin</artifactId>
<version>1.1</version>
</plugin>
<plugin>
<groupId>com.infradna.tool</groupId>
<artifactId>bridge-method-injector</artifactId>
<version>1.17</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>antlr-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${findbugs-maven-plugin.version}</version>
<configuration>
<effort>Max</effort>
<threshold>High</threshold>
<!--Excludes file is located on the top level -->
<excludeFilterFile>../src/findbugs/findbugs-excludes.xml</excludeFilterFile>
<xmlOutput>true</xmlOutput>
<findbugsXmlOutput>false</findbugsXmlOutput>
</configuration>
<executions>
<execution>
<id>findbugs</id>
<goals>
<goal>check</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.19.0</version>
</plugin>
<plugin>
<groupId>org.jvnet.updatecenter2</groupId>
<artifactId>maven-makepkgs-plugin</artifactId>
<version>0.6.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
<dependencies>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>doxia-module-markdown</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>org.kohsuke</groupId>
<artifactId>wagon-gitsite</artifactId>
<version>0.3.5</version>
</extension>
</extensions>
</build>
<profiles>
</profiles>
</project>

View File

@ -1,4 +1,4 @@
package com.theokanning.openai; package com.ossez.openai;
import okhttp3.Interceptor; import okhttp3.Interceptor;
import okhttp3.Request; import okhttp3.Request;

View File

@ -1,25 +1,21 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.answer.AnswerRequest; import com.ossez.openai.edit.EditRequest;
import com.theokanning.openai.answer.AnswerResult; import com.ossez.openai.edit.EditResult;
import com.theokanning.openai.classification.ClassificationRequest; import com.ossez.openai.completion.CompletionRequest;
import com.theokanning.openai.classification.ClassificationResult; import com.ossez.openai.completion.CompletionResult;
import com.theokanning.openai.completion.CompletionRequest; import com.ossez.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.completion.CompletionResult; import com.ossez.openai.embedding.EmbeddingResult;
import com.theokanning.openai.edit.EditRequest; import com.ossez.openai.engine.Engine;
import com.theokanning.openai.edit.EditResult; import com.ossez.openai.file.File;
import com.theokanning.openai.embedding.EmbeddingRequest; import com.ossez.openai.finetune.FineTuneEvent;
import com.theokanning.openai.embedding.EmbeddingResult; import com.ossez.openai.finetune.FineTuneRequest;
import com.theokanning.openai.engine.Engine; import com.ossez.openai.finetune.FineTuneResult;
import com.theokanning.openai.file.File; import com.ossez.openai.image.CreateImageRequest;
import com.theokanning.openai.finetune.FineTuneEvent; import com.ossez.openai.image.ImageResult;
import com.theokanning.openai.finetune.FineTuneRequest; import com.ossez.openai.model.Model;
import com.theokanning.openai.finetune.FineTuneResult; import com.ossez.openai.moderation.ModerationRequest;
import com.theokanning.openai.model.Model; import com.ossez.openai.moderation.ModerationResult;
import com.theokanning.openai.moderation.ModerationRequest;
import com.theokanning.openai.moderation.ModerationResult;
import com.theokanning.openai.search.SearchRequest;
import com.theokanning.openai.search.SearchResult;
import io.reactivex.Single; import io.reactivex.Single;
import okhttp3.MultipartBody; import okhttp3.MultipartBody;
import okhttp3.RequestBody; import okhttp3.RequestBody;
@ -88,6 +84,15 @@ public interface OpenAiApi {
@DELETE("/v1/models/{fine_tune_id}") @DELETE("/v1/models/{fine_tune_id}")
Single<DeleteResult> deleteFineTune(@Path("fine_tune_id") String fineTuneId); Single<DeleteResult> deleteFineTune(@Path("fine_tune_id") String fineTuneId);
@POST("/v1/images/generations")
Single<ImageResult> createImage(@Body CreateImageRequest request);
@POST("/v1/images/edits")
Single<ImageResult> createImageEdit(@Body RequestBody requestBody);
@POST("/v1/images/variations")
Single<ImageResult> createImageVariation(@Body RequestBody requestBody);
@POST("/v1/moderations") @POST("/v1/moderations")
Single<ModerationResult> createModeration(@Body ModerationRequest request); Single<ModerationResult> createModeration(@Body ModerationRequest request);
@ -98,16 +103,4 @@ public interface OpenAiApi {
@Deprecated @Deprecated
@GET("/v1/engines/{engine_id}") @GET("/v1/engines/{engine_id}")
Single<Engine> getEngine(@Path("engine_id") String engineId); Single<Engine> getEngine(@Path("engine_id") String engineId);
@Deprecated
@POST("v1/answers")
Single<AnswerResult> createAnswer(@Body AnswerRequest request);
@Deprecated
@POST("v1/classifications")
Single<ClassificationResult> createClassification(@Body ClassificationRequest request);
@Deprecated
@POST("/v1/engines/{engine_id}/search")
Single<OpenAiResponse<SearchResult>> search(@Path("engine_id") String engineId, @Body SearchRequest request);
} }

View File

@ -1,29 +1,27 @@
package com.theokanning.openai; package com.ossez.openai;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.theokanning.openai.answer.AnswerRequest; import com.ossez.openai.edit.EditRequest;
import com.theokanning.openai.answer.AnswerResult; import com.ossez.openai.edit.EditResult;
import com.theokanning.openai.classification.ClassificationRequest; import com.ossez.openai.completion.CompletionRequest;
import com.theokanning.openai.classification.ClassificationResult; import com.ossez.openai.completion.CompletionResult;
import com.theokanning.openai.completion.CompletionRequest; import com.ossez.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.completion.CompletionResult; import com.ossez.openai.embedding.EmbeddingResult;
import com.theokanning.openai.edit.EditRequest; import com.ossez.openai.engine.Engine;
import com.theokanning.openai.edit.EditResult; import com.ossez.openai.file.File;
import com.theokanning.openai.embedding.EmbeddingRequest; import com.ossez.openai.finetune.FineTuneEvent;
import com.theokanning.openai.embedding.EmbeddingResult; import com.ossez.openai.finetune.FineTuneRequest;
import com.theokanning.openai.engine.Engine; import com.ossez.openai.finetune.FineTuneResult;
import com.theokanning.openai.file.File; import com.ossez.openai.image.CreateImageEditRequest;
import com.theokanning.openai.finetune.FineTuneEvent; import com.ossez.openai.image.CreateImageRequest;
import com.theokanning.openai.finetune.FineTuneRequest; import com.ossez.openai.image.CreateImageVariationRequest;
import com.theokanning.openai.finetune.FineTuneResult; import com.ossez.openai.image.ImageResult;
import com.theokanning.openai.model.Model; import com.ossez.openai.model.Model;
import com.theokanning.openai.moderation.ModerationRequest; import com.ossez.openai.moderation.ModerationRequest;
import com.theokanning.openai.moderation.ModerationResult; import com.ossez.openai.moderation.ModerationResult;
import com.theokanning.openai.search.SearchRequest;
import com.theokanning.openai.search.SearchResult;
import okhttp3.*; import okhttp3.*;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
@ -38,6 +36,7 @@ public class OpenAiService {
/** /**
* Creates a new OpenAiService that wraps OpenAiApi * Creates a new OpenAiService that wraps OpenAiApi
*
* @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
*/ */
public OpenAiService(String token) { public OpenAiService(String token) {
@ -46,7 +45,8 @@ public class OpenAiService {
/** /**
* Creates a new OpenAiService that wraps OpenAiApi * Creates a new OpenAiService that wraps OpenAiApi
* @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" *
* @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
* @param timeout http read timeout in seconds, 0 means no timeout * @param timeout http read timeout in seconds, 0 means no timeout
*/ */
public OpenAiService(String token, int timeout) { public OpenAiService(String token, int timeout) {
@ -73,6 +73,7 @@ public class OpenAiService {
/** /**
* Creates a new OpenAiService that wraps OpenAiApi * Creates a new OpenAiService that wraps OpenAiApi
*
* @param api OpenAiApi instance to use for all methods * @param api OpenAiApi instance to use for all methods
*/ */
public OpenAiService(OpenAiApi api) { public OpenAiService(OpenAiApi api) {
@ -91,7 +92,9 @@ public class OpenAiService {
return api.createCompletion(request).blockingGet(); return api.createCompletion(request).blockingGet();
} }
/** Use {@link OpenAiService#createCompletion(CompletionRequest)} and {@link CompletionRequest#model}instead */ /**
* Use {@link OpenAiService#createCompletion(CompletionRequest)} and {@link CompletionRequest#model}instead
*/
@Deprecated @Deprecated
public CompletionResult createCompletion(String engineId, CompletionRequest request) { public CompletionResult createCompletion(String engineId, CompletionRequest request) {
return api.createCompletion(engineId, request).blockingGet(); return api.createCompletion(engineId, request).blockingGet();
@ -101,7 +104,9 @@ public class OpenAiService {
return api.createEdit(request).blockingGet(); return api.createEdit(request).blockingGet();
} }
/** Use {@link OpenAiService#createEdit(EditRequest)} and {@link EditRequest#model}instead */ /**
* Use {@link OpenAiService#createEdit(EditRequest)} and {@link EditRequest#model}instead
*/
@Deprecated @Deprecated
public EditResult createEdit(String engineId, EditRequest request) { public EditResult createEdit(String engineId, EditRequest request) {
return api.createEdit(engineId, request).blockingGet(); return api.createEdit(engineId, request).blockingGet();
@ -111,7 +116,9 @@ public class OpenAiService {
return api.createEmbeddings(request).blockingGet(); return api.createEmbeddings(request).blockingGet();
} }
/** Use {@link OpenAiService#createEmbeddings(EmbeddingRequest)} and {@link EmbeddingRequest#model}instead */ /**
* Use {@link OpenAiService#createEmbeddings(EmbeddingRequest)} and {@link EmbeddingRequest#model}instead
*/
@Deprecated @Deprecated
public EmbeddingResult createEmbeddings(String engineId, EmbeddingRequest request) { public EmbeddingResult createEmbeddings(String engineId, EmbeddingRequest request) {
return api.createEmbeddings(engineId, request).blockingGet(); return api.createEmbeddings(engineId, request).blockingGet();
@ -166,6 +173,62 @@ public class OpenAiService {
return api.deleteFineTune(fineTuneId).blockingGet(); return api.deleteFineTune(fineTuneId).blockingGet();
} }
public ImageResult createImage(CreateImageRequest request) {
return api.createImage(request).blockingGet();
}
public ImageResult createImageEdit(CreateImageEditRequest request, String imagePath, String maskPath) {
java.io.File image = new java.io.File(imagePath);
java.io.File mask = null;
if (maskPath != null) {
mask = new java.io.File(maskPath);
}
return createImageEdit(request, image, mask);
}
public ImageResult createImageEdit(CreateImageEditRequest request, java.io.File image, java.io.File mask) {
RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image);
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MediaType.get("multipart/form-data"))
.addFormDataPart("prompt", request.getPrompt())
.addFormDataPart("size", request.getSize())
.addFormDataPart("response_format", request.getResponseFormat())
.addFormDataPart("image", "image", imageBody);
if (request.getN() != null) {
builder.addFormDataPart("n", request.getN().toString());
}
if (mask != null) {
RequestBody maskBody = RequestBody.create(MediaType.parse("image"), mask);
builder.addFormDataPart("mask", "mask", maskBody);
}
return api.createImageEdit(builder.build()).blockingGet();
}
public ImageResult createImageVariation(CreateImageVariationRequest request, String imagePath) {
java.io.File image = new java.io.File(imagePath);
return createImageVariation(request, image);
}
public ImageResult createImageVariation(CreateImageVariationRequest request, java.io.File image) {
RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image);
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MediaType.get("multipart/form-data"))
.addFormDataPart("size", request.getSize())
.addFormDataPart("response_format", request.getResponseFormat())
.addFormDataPart("image", "image", imageBody);
if (request.getN() != null) {
builder.addFormDataPart("n", request.getN().toString());
}
return api.createImageVariation(builder.build()).blockingGet();
}
public ModerationResult createModeration(ModerationRequest request) { public ModerationResult createModeration(ModerationRequest request) {
return api.createModeration(request).blockingGet(); return api.createModeration(request).blockingGet();
} }
@ -179,19 +242,4 @@ public class OpenAiService {
public Engine getEngine(String engineId) { public Engine getEngine(String engineId) {
return api.getEngine(engineId).blockingGet(); return api.getEngine(engineId).blockingGet();
} }
@Deprecated
public AnswerResult createAnswer(AnswerRequest request) {
return api.createAnswer(request).blockingGet();
}
@Deprecated
public ClassificationResult createClassification(ClassificationRequest request) {
return api.createClassification(request).blockingGet();
}
@Deprecated
public List<SearchResult> search(String engineId, SearchRequest request) {
return api.search(engineId, request).blockingGet().data;
}
} }

View File

@ -0,0 +1,48 @@
package com.ossez.openai;
import com.ossez.openai.completion.CompletionChoice;
import com.ossez.openai.completion.CompletionRequest;
import com.ossez.openai.completion.CompletionRequestBuilder;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class CompletionTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
CompletionRequest completionRequest = new CompletionRequestBuilder()
.setModel("text-davinci-003")
.setPrompt("讲一个关于程序员的笑话")
.setEcho(true)
// .setN(0)
.setMaxTokens(500)
.setUser("testing")
.setLogitBias(new HashMap<>())
.createCompletionRequest();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
System.out.println(choices.get(0).getText());
// System.out.println(choices.get(1).getText());
// assertEquals(5, choices.get(0).getText());
}
@Test
void createCompletionDeprecated() {
CompletionRequest completionRequest = new CompletionRequestBuilder()
.setPrompt("Somebody once told me the world is gonna roll me")
.setEcho(true)
.setUser("testing")
.createCompletionRequest();
List<CompletionChoice> choices = service.createCompletion("ada", completionRequest).getChoices();
assertFalse(choices.isEmpty());
}
}

View File

@ -0,0 +1,39 @@
package com.ossez.openai;
import com.ossez.openai.edit.EditRequest;
import com.ossez.openai.edit.EditRequestBuilder;
import com.ossez.openai.edit.EditResult;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class EditTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void edit() {
EditRequest request = new EditRequestBuilder()
.setModel("text-davinci-edit-001")
.setInput("What day of the wek is it?")
.setInstruction("Fix the spelling mistakes")
.createEditRequest();
EditResult result = service.createEdit( request);
System.out.println(result.getChoices().get(0).getText());
assertNotNull(result.getChoices().get(0).getText());
}
@Test
void editDeprecated() {
EditRequest request = new EditRequestBuilder()
.setInput("What day of the wek is it?")
.setInstruction("Fix the spelling mistakes")
.createEditRequest();
EditResult result = service.createEdit("text-davinci-edit-001", request);
assertNotNull(result.getChoices().get(0).getText());
}
}

View File

@ -1,7 +1,8 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.embedding.Embedding; import com.ossez.openai.embedding.Embedding;
import com.theokanning.openai.embedding.EmbeddingRequest; import com.ossez.openai.embedding.EmbeddingRequest;
import com.ossez.openai.embedding.EmbeddingRequestBuilder;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
@ -17,10 +18,10 @@ public class EmbeddingTest {
@Test @Test
void createEmbeddings() { void createEmbeddings() {
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() EmbeddingRequest embeddingRequest = new EmbeddingRequestBuilder()
.model("text-similarity-babbage-001") .setModel("text-similarity-babbage-001")
.input(Collections.singletonList("The food was delicious and the waiter...")) .setInput(Collections.singletonList("The food was delicious and the waiter..."))
.build(); .createEmbeddingRequest();
List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData(); List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData();
@ -30,9 +31,9 @@ public class EmbeddingTest {
@Test @Test
void createEmbeddingsDeprecated() { void createEmbeddingsDeprecated() {
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() EmbeddingRequest embeddingRequest = new EmbeddingRequestBuilder()
.input(Collections.singletonList("The food was delicious and the waiter...")) .setInput(Collections.singletonList("The food was delicious and the waiter..."))
.build(); .createEmbeddingRequest();
List<Embedding> embeddings = service.createEmbeddings("text-similarity-babbage-001", embeddingRequest).getData(); List<Embedding> embeddings = service.createEmbeddings("text-similarity-babbage-001", embeddingRequest).getData();

View File

@ -1,6 +1,6 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.engine.Engine; import com.ossez.openai.engine.Engine;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;

View File

@ -1,6 +1,6 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.file.File; import com.ossez.openai.file.File;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
import java.util.List; import java.util.List;

View File

@ -1,8 +1,7 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.finetune.FineTuneRequest; import com.ossez.openai.finetune.FineTuneResult;
import com.theokanning.openai.finetune.FineTuneEvent; import com.ossez.openai.finetune.FineTuneEvent;
import com.theokanning.openai.finetune.FineTuneResult;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
import java.util.List; import java.util.List;
@ -35,15 +34,15 @@ public class FineTuneTest {
@Test @Test
@Order(1) @Order(1)
void createFineTune() { void createFineTune() {
FineTuneRequest request = FineTuneRequest.builder() // FineTuneRequest request = FineTuneRequest.builder()
.trainingFile(fileId) // .trainingFile(fileId)
.model("ada") // .model("ada")
.build(); // .build();
//
FineTuneResult fineTune = service.createFineTune(request); // FineTuneResult fineTune = service.createFineTune(request);
fineTuneId = fineTune.getId(); // fineTuneId = fineTune.getId();
//
assertEquals("pending", fineTune.getStatus()); // assertEquals("pending", fineTune.getStatus());
} }
@Test @Test

View File

@ -0,0 +1,89 @@
package com.ossez.openai;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ImageTest {
static String filePath = "src/test/resources/penguin.png";
static String fileWithAlphaPath = "src/test/resources/penguin_with_alpha.png";
static String maskPath = "src/test/resources/mask.png";
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token, 30);
@Test
void createImageUrl() {
// CreateImageRequest createImageRequest = CreateImageRequest.builder()
// .prompt("penguin")
// .n(3)
// .size("256x256")
// .user("testing")
// .build();
//
// List<Image> images = service.createImage(createImageRequest).getData();
// assertEquals(3, images.size());
// assertNotNull(images.get(0).getUrl());
}
@Test
void createImageBase64() {
// CreateImageRequest createImageRequest = CreateImageRequest.builder()
// .prompt("penguin")
// .responseFormat("b64_json")
// .user("testing")
// .build();
//
// List<Image> images = service.createImage(createImageRequest).getData();
// assertEquals(1, images.size());
// assertNotNull(images.get(0).getB64Json());
}
@Test
void createImageEdit() {
// CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder()
// .prompt("a penguin with a red background")
// .responseFormat("url")
// .size("256x256")
// .user("testing")
// .n(2)
// .build();
//
// List<Image> images = service.createImageEdit(createImageRequest, fileWithAlphaPath, null).getData();
// assertEquals(2, images.size());
// assertNotNull(images.get(0).getUrl());
}
@Test
void createImageEditWithMask() {
// CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder()
// .prompt("a penguin with a red hat")
// .responseFormat("url")
// .size("256x256")
// .user("testing")
// .n(2)
// .build();
//
// List<Image> images = service.createImageEdit(createImageRequest, filePath, maskPath).getData();
// assertEquals(2, images.size());
// assertNotNull(images.get(0).getUrl());
}
@Test
void createImageVariation() {
// CreateImageVariationRequest createImageVariationRequest = CreateImageVariationRequest.builder()
// .responseFormat("url")
// .size("256x256")
// .user("testing")
// .n(2)
// .build();
//
// List<Image> images = service.createImageVariation(createImageVariationRequest, filePath).getData();
// assertEquals(2, images.size());
// assertNotNull(images.get(0).getUrl());
}
}

View File

@ -1,6 +1,6 @@
package com.theokanning.openai; package com.ossez.openai;
import com.theokanning.openai.model.Model; import com.ossez.openai.model.Model;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
@ -16,7 +16,6 @@ public class ModelTest {
@Test @Test
void listModels() { void listModels() {
List<Model> models = service.listModels(); List<Model> models = service.listModels();
assertFalse(models.isEmpty()); assertFalse(models.isEmpty());
} }

View File

@ -0,0 +1,24 @@
package com.ossez.openai;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ModerationTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createModeration() {
// ModerationRequest moderationRequest = ModerationRequest.builder()
// .input("I want to kill them")
// .model("text-moderation-latest")
// .build();
//
// Moderation moderationScore = service.createModeration(moderationRequest).getResults().get(0);
//
// assertTrue(moderationScore.isFlagged());
}
}

View File

@ -1,37 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.answer.AnswerRequest;
import com.theokanning.openai.answer.AnswerResult;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class AnswerTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createAnswer() {
AnswerRequest answerRequest = AnswerRequest.builder()
.documents(Arrays.asList("Puppy A is happy.", "Puppy B is sad."))
.question("which puppy is happy?")
.searchModel("ada")
.model("curie")
.examplesContext("In 2017, U.S. life expectancy was 78.6 years.")
.examples(Collections.singletonList(
Arrays.asList("What is human life expectancy in the United States?", "78 years.")
))
.maxTokens(5)
.stop(Arrays.asList("\n", "<|endoftext|>"))
.build();
AnswerResult result = service.createAnswer(answerRequest);
assertNotNull(result.getAnswers().get(0));
}
}

View File

@ -1,39 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.classification.ClassificationRequest;
import com.theokanning.openai.classification.ClassificationResult;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ClassificationTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
ClassificationRequest classificationRequest = ClassificationRequest.builder()
.examples(Arrays.asList(
Arrays.asList("A happy moment", "Positive"),
Arrays.asList("I am sad.", "Negative"),
Arrays.asList("I am feeling awesome", "Positive")
))
.query("It is a raining day :(")
.model("curie")
.searchModel("ada")
.labels(Arrays.asList("Positive", "Negative", "Neutral"))
.build();
ClassificationResult result = service.createClassification(classificationRequest);
assertNotNull(result.getCompletion());
}
}

View File

@ -1,43 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class CompletionTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("ada")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.user("testing")
.logitBias(new HashMap<>())
.build();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
assertFalse(choices.isEmpty());
}
@Test
void createCompletionDeprecated() {
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.user("testing")
.build();
List<CompletionChoice> choices = service.createCompletion("ada", completionRequest).getChoices();
assertFalse(choices.isEmpty());
}
}

View File

@ -1,38 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.edit.EditResult;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class EditTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void edit() {
EditRequest request = EditRequest.builder()
.model("text-davinci-edit-001")
.input("What day of the wek is it?")
.instruction("Fix the spelling mistakes")
.build();
EditResult result = service.createEdit( request);
assertNotNull(result.getChoices().get(0).getText());
}
@Test
void editDeprecated() {
EditRequest request = EditRequest.builder()
.input("What day of the wek is it?")
.instruction("Fix the spelling mistakes")
.build();
EditResult result = service.createEdit("text-davinci-edit-001", request);
assertNotNull(result.getChoices().get(0).getText());
}
}

View File

@ -1,26 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.moderation.ModerationRequest;
import com.theokanning.openai.moderation.Moderation;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ModerationTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createModeration() {
ModerationRequest moderationRequest = ModerationRequest.builder()
.input("I want to kill them")
.model("text-moderation-latest")
.build();
Moderation moderationScore = service.createModeration(moderationRequest).getResults().get(0);
assertTrue(moderationScore.isFlagged());
}
}

Some files were not shown because too many files have changed in this diff Show More