62 Commits

Author SHA1 Message Date
honeymoose 488f40b789 Change JDK version from 11 to 17 2023-03-28 10:07:37 -04:00
honeymoose 5e644ceffd 修改许可证信息 2023-03-13 11:30:37 -04:00
honeymoose 8619ecc46e 修改编译使用的 JDK 为 JDK 17 2023-03-13 11:27:35 -04:00
honeymoose 666c38e7b1 修改自述文件来提供允许 OpenAI 的方法 2023-03-10 12:34:30 -05:00
honeymoose 30dfac5f0a 更新项目提交 Bug 的链接 2023-03-10 11:05:26 -05:00
honeymoose ce616c7816 更新 POM 文件 2023-03-10 10:59:18 -05:00
honeymoose a991582b80 更新自述文件,并且将 Key 配置到环境文件中 2023-03-10 09:07:44 -05:00
honeymoose 7d3b7c7eb1 更新联系方式使用 SharkFly 公众号来进行 OpenAI 的测试 2023-03-07 08:38:15 -05:00
honeymoose 4fd7096e65 更新 Apache 使用的版本 2023-01-13 19:36:18 -05:00
honeymoose 5967337229 Update the test folder and sub-task 2023-01-07 08:41:19 -05:00
honeymoose 09aa7fdeb6 Update README file 2023-01-06 18:40:06 -05:00
honeymoose 8babebac7a Update README file to include more info to project. 2023-01-06 18:36:55 -05:00
honeymoose c796112903 Clean up the file we don't need it 2023-01-06 18:22:01 -05:00
honeymoose f23170b45c update the maven repo 2023-01-06 16:17:12 -05:00
honeymoose 9b907d0d9a update to new name 2023-01-06 14:41:47 -05:00
honeymoose 65a30def30 Update Readme file 2023-01-06 14:40:52 -05:00
honeymoose 85961e264c Update Readme file 2023-01-06 13:32:10 -05:00
honeymoose 633b877145 update the git file 2023-01-06 13:27:55 -05:00
honeymoose 3bf8d33cd7 Re-name the all package and start build base on those new package name 2023-01-06 13:24:09 -05:00
honeymoose 062798c73a Delete all lombok from project and build as JDK version 11 2023-01-06 13:20:51 -05:00
honeymoose f63a2438dc Add client module to package 2023-01-06 12:47:41 -05:00
honeymoose 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
Theo Kanning 48cd7272f7 Bump version to 0.8.1 (#43) 2022-12-04 13:41:14 -06:00
Theo Kanning 1600841a58 Update lombok to 1.18.24 (#42)
Not sure why I never had compiling issues and others did, but I see no reason not to update this.
2022-12-04 12:55:17 -06:00
Theo Kanning 8d7f240010 Add logit bias parameter to CompletionRequest (#41) 2022-12-04 12:49:26 -06:00
Theo Kanning c76923926e Remove deprecated endpoints from example project (#40)
The engine APIs are deprecated, and OpenAI will shut them down eventually
2022-12-04 12:44:30 -06:00
Robin Glauser 0caab13666 Updating example to not use new api (#33) 2022-12-04 12:39:31 -06:00
Theo Kanning 5e14d4f62b Add usage data to Completion and Embedding APIs (#39)
Also changed EditResult to use the new shared object
2022-12-04 12:37:28 -06:00
Theo Kanning 83df513ddc Bump version to 0.8.0 (#29) 2022-08-22 14:32:40 -05:00
Theo Kanning 515a5fc47d Add deprecation info to README (#28)
Answers, Classifications, Searchs, and old v1/engine endpoints are all deprecated.
2022-08-22 14:29:42 -05:00
Theo Kanning 553e22fea2 Add Model support and new v1 endpoints (#27)
The old endpoints are marked as deprecated
Also marked response fields as public for easier access
2022-08-22 13:55:20 -05:00
Theo Kanning 252db27577 Update EditResult and fix the Edit test (#26)
OpenAI's example curl used an invalid engine, and the api returned a confusing error message.
Now everything works with text-davinci-edit-001
2022-08-19 11:05:12 -05:00
Theo Kanning ff06ffb309 Mark Answer, Completion, and Search APIs as deprecated (#25)
OpenAI has officially deprecated these APIs, but I'll leave them in as long as the endpoints still work
The engines api is also deprecated, but I'll get to that when I add
model support.
2022-08-19 10:49:22 -05:00
Theo Kanning d1f274800a Add moderation support (#24)
Adding support for the new Moderations api https://beta.openai.com/docs/guides/moderation

Fixes https://github.com/TheoKanning/openai-java/issues/20
2022-08-19 10:32:33 -05:00
Theo Kanning 77219d497b Add user to CompletionRequest (#23)
Fixes https://github.com/TheoKanning/openai-java/issues/19
2022-08-19 09:44:38 -05:00
Jacek Lipiec 1391f4074d Fix typo in the LICENSE.md (#22)
As I assume it was by mistake; functionally it wasn't a MIT license :)
2022-08-19 09:31:56 -05:00
Theo Kanning 6f5a4ada76 Update version to 0.7.0 (#18) 2022-06-29 11:54:30 -05:00
Theo Kanning 4d5878db07 Add OpenAiService constructor that takes timeout parameter (#17)
If certain engines are timing out regularly, then OpenAiService needs a timeout parameter.
I also added a constructor that takes an OpenAiApi, and this will allow users to customize their api settings much more easily.

If we need more parameters later, I might add a builder for OpenAiService.

Based on feedback in https://github.com/TheoKanning/openai-java/issues/5
2022-06-29 11:43:29 -05:00
Theo Kanning 9e0a26b576 Update to version 0.6.0 (#16) 2022-04-28 16:53:41 -05:00
Theo Kanning bcfb5da378 Add supported apis to readme (#15) 2022-04-28 16:50:15 -05:00
Theo Kanning 7f39df6e0b Add Edit request functionality (#14) 2022-04-28 16:48:33 -05:00
Theo Kanning 900e13bbda Add embeddings support (#13) 2022-04-28 16:42:13 -05:00
Theo Kanning 9f5b64b151 Add answer support (#12) 2022-04-28 16:20:15 -05:00
Theo Kanning 103c34da94 Add classification support (#11) 2022-04-28 15:55:27 -05:00
Theo Kanning ed2f1152e8 Add more tests and run them before each merge (#10)
These tests are very basic sanity checks
2022-04-28 14:49:54 -05:00
Theo Kanning d3074e113e Fix build action trigger (#9) 2022-04-28 14:19:42 -05:00
Theo Kanning 4dd974cf98 Switch to publishing plugin (#8)
This should make publishing from CI easier from now on
2022-04-28 14:19:36 -05:00
Theo Kanning 9a05c6ac77 Add file and fine-tune api support (#6) 2022-04-19 18:50:44 -05:00
Theo Kanning d410abe1b5 Update badge to show maven central 2021-03-09 21:31:03 -06:00
Theo Kanning b10b9c30f2 Fix CI build
Failed because everything in gradle.properties is only available locally
2021-03-09 21:28:16 -06:00
Theo Kanning 217116b819 Publish to OSSRH instead of Bintray (#4) 2021-03-09 20:52:48 -06:00
Theo Kanning cdfceb0783 Fix readme links 2021-03-01 09:31:39 -06:00
Theo Kanning c14c98c915 Update Readme
Fixed typo
2020-10-07 09:47:48 -05:00
Theo Kanning 9529928f0a Update Readme
Changed badge color from that ugly orange to a nice green
2020-10-07 09:43:04 -05:00
Theo Kanning 70019fa7bb Update Readme
Added version badge and download instructions
2020-10-07 09:38:16 -05:00
89 changed files with 5280 additions and 1032 deletions
-6
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
-26
View File
@@ -1,26 +0,0 @@
# This workflow will build a Java project with Gradle
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Java CI with Gradle
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
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: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build with Gradle
run: ./gradlew build
-24
View File
@@ -1,24 +0,0 @@
name: Publish Artifacts
on:
release:
types: [published]
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: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Publish Artifacts
run: ./gradlew api:bintrayUpload client:bintrayUpload -DlibraryVersion=${GITHUB_REF##*/}
env:
BINTRAY_USER : ${{ secrets.BINTRAY_USER }}
BINTRAY_KEY : ${{ secrets.BINTRAY_KEY }}
+233 -31
View File
@@ -1,33 +1,235 @@
# Compiled class file
*.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
build
# Ignore Gradle GUI config
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
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
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
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
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
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>
Generated
+12
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>
Generated
+7
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>
+2 -2
View File
@@ -1,6 +1,6 @@
T License
MIT License
Copyright (c) [year] [fullname]
Copyright (c) 2023 OSSEZ
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+128 -14
View File
@@ -1,39 +1,153 @@
# OpenAI-Java
# OpenAI-J
<p align="center">
<a href="https://github.com/honeymoose">
<img height=85 src="https://avatars1.githubusercontent.com/u/45009982?s=200&v=4">
</a>
<br>This project builds by JDK 17 and OpenJ9 for JVM.
</p>
* [社区和讨论 (community)](https://www.ossez.com/tag/chat-gpt)
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:
- `api` : request/response POJOs for the GPT-3 engine, completion, and search APIs.
- `client` : a basic retrofit client for the GPT-3 endpoints
- `client` : a basic retrofit client for the GPT-3 endpoints, includes the `api` module
as well as an example project using the client.
## Usage
### Importing into a gradle project
`implementation 'com.theokanning.openai-gpt3-java:api:<version>'`
or
`implementation 'com.theokanning.openai-gpt3-java:client:<version>'`
### Using OpenAiService
If you're looking for the fastest solution, import the `client` and use [OpenAiService](client/src/main/java/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()
.prompt("Somebody once told me the world is gonna roll me")
.model("ada")
.echo(true)
.build();
service.createCompletion("ada", completionRequest).getChoices().forEach(System.out::println);
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
```
### Using OpenAiApi Retrofit client
If you're using retrofit, you can import the `client` module and use the [OpenAiApi](client/src/main/java/openai/OpenAiApi.java).
You'll have to add your auth token as a header (see [AuthenticationInterceptor](client/src/main/java/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.
### Using data classes only
If you want to make your own client, just import the POJOs from the `api` module.
Your client will need to use snake case to work with the OpenAI API.
## Running the example project
All the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your OpenAI api token
```
export OPENAI_TOKEN="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
./gradlew example:run
```
## License
Published under the MIT License
There is an [example](https://github.com/honeymoose/OpenAI-J/blob/main/example/src/main/java/com/ossez/openai/example/OpenAiApiExample.java) project
with a OpenAiApiExample file contain main function to run.
Also, you can run all tests by JUnit too.
[OpenAI-J 如何进行测试](https://www.ossez.com/t/openai-j/14338)
## 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`.
The code includes upgrade instructions for all deprecated endpoints.
I won't remove the old endpoints from this library until OpenAI shuts them down.
# FAQ (常见问题)
## 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)
-77
View File
@@ -1,77 +0,0 @@
apply plugin: 'java-library'
apply plugin: 'com.jfrog.bintray'
apply plugin: 'maven-publish'
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.12'
annotationProcessor 'org.projectlombok:lombok:1.18.12'
}
ext {
libraryVersion = System.getProperty("libraryVersion")
}
version = libraryVersion
group = 'com.theokanning.openai-gpt3-java'
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
publishing {
publications {
ApiPublication(MavenPublication) {
from components.java
artifact sourcesJar
artifact javadocJar
groupId project.group
artifactId 'api'
version libraryVersion
pom {
description = 'POJOs for the OpenAI GPT-3 API'
name = 'api'
url = 'https://github.com/theokanning/openai-java'
developers {
developer {
id = "theokanning"
name = "Theo Kanning"
email = "theokanning@gmail.com"
}
}
scm {
url = "https://github.com/theokanning/openai-java"
}
licenses {
license {
name = "The MIT License"
url = "https://www.mit.edu/~amini/LICENSE.md"
distribution = "repo"
}
}
}
}
}
}
bintray {
user = System.getenv("BINTRAY_USER")
key = System.getenv("BINTRAY_KEY")
publications = ['ApiPublication']
pkg {
repo = 'openai-gpt3-java'
name = 'api'
vcsUrl = 'https://github.com/TheoKanning/openai-java.git'
licenses = ["MIT"]
publish = false
version {
name = libraryVersion
}
}
}
+77
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>
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,256 @@
package com.ossez.openai.completion;
import java.util.List;
import java.util.Map;
/**
* A request for OpenAi to generate a predicted completion for a prompt.
* All fields are nullable.
*
* https://beta.openai.com/docs/api-reference/completions/create
*/
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.
* Required if specifying a fine tuned model or if using the new v1/completions endpoint.
*/
String model;
/**
* An optional prompt to complete from
*/
String prompt;
/**
* The maximum number of tokens to generate.
* Requests can use up to 2048 tokens shared between prompt and completion.
* (One token is roughly 4 characters for normal English text)
*/
Integer maxTokens;
/**
* 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 CompletionRequest#topP} but not both.
*/
Double temperature;
/**
* An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of
* the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are
* considered.
*
* We generally recommend using this or {@link CompletionRequest#temperature} but not both.
*/
Double topP;
/**
* How many completions to generate for each prompt.
*
* Because this parameter generates many completions, it can quickly consume your token quota.
* Use carefully and ensure that you have reasonable settings for {@link CompletionRequest#maxTokens} and {@link CompletionRequest#stop}.
*/
Integer n;
/**
* Whether to stream back partial progress.
* If set, tokens will be sent as data-only server-sent events as they become available,
* with the stream terminated by a data: DONE message.
*/
Boolean stream;
/**
* 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;
/**
* Echo back the prompt in addition to the completion
*/
Boolean echo;
/**
* Up to 4 sequences where the API will stop generating further tokens.
* The returned text will not contain the stop sequence.
*/
List<String> stop;
/**
* Number between 0 and 1 (default 0) that penalizes new tokens based on whether they appear in the text so far.
* Increases the model's likelihood to talk about new topics.
*/
Double presencePenalty;
/**
* Number between 0 and 1 (default 0) that penalizes new tokens based on their existing frequency in the text so far.
* Decreases the model's likelihood to repeat the same line verbatim.
*/
Double frequencyPenalty;
/**
* Generates best_of completions server-side and returns the "best"
* (the one with the lowest log probability per token).
* Results cannot be streamed.
*
* When used with {@link CompletionRequest#n}, best_of controls the number of candidate completions and n specifies how many to return,
* best_of must be greater than n.
*/
Integer bestOf;
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100.
*
* https://beta.openai.com/docs/api-reference/completions/create#completions/create-logit_bias
*/
Map<String, Integer> logitBias;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,110 @@
package com.ossez.openai.edit;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Given a prompt and an instruction, OpenAi will return an edited version of the prompt
*
* https://beta.openai.com/docs/api-reference/edits/create
*/
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.
* Required if using the new v1/edits endpoint.
*/
String model;
/**
* The input text to use as a starting point for the edit.
*/
String input;
/**
* The instruction that tells the model how to edit the prompt.
* For example, "Fix the spelling mistakes"
*/
@NonNull
String instruction;
/**
* How many edits to generate for the input and instruction.
*/
Integer n;
/**
* 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 altering this or {@link EditRequest#topP} but not both.
*/
Double temperature;
/**
* An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of
* the tokens with top_p probability mass.So 0.1 means only the tokens comprising the top 10% probability mass are
* considered.
*
* We generally recommend altering this or {@link EditRequest#temperature} but not both.
*/
@JsonProperty("top_p")
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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,62 @@
package com.ossez.openai.embedding;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
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.
* Required if using the new v1/embeddings endpoint.
*/
String model;
/**
* Input text to get embeddings for, encoded as a string or array of tokens.
* To get embeddings for multiple inputs in a single request, pass an array of strings or array of token arrays.
* Each input must not exceed 2048 tokens in length.
* <p>
* Unless your are embedding code, we suggest replacing newlines (\n) in your input with a single space,
* as we have observed inferior results when newlines are present.
*/
@NonNull
List<String> input;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -0,0 +1,64 @@
package com.ossez.openai.engine;
/**
* GPT-3 engine details
*
* https://beta.openai.com/docs/api-reference/retrieve-engine
*/
@Deprecated
public class Engine {
/**
* An identifier for this engine, used to specify an engine for completions or searching.
*/
public String id;
/**
* The type of object returned, should be "engine"
*/
public String object;
/**
* The owner of the GPT-3 engine, typically "openai"
*/
public String owner;
/**
* Whether the engine is ready to process requests or not
*/
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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,204 @@
package com.ossez.openai.finetune;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
/**
* A request for OpenAi to create a fine-tuned model
* All fields except trainingFile are nullable.
*
* https://beta.openai.com/docs/api-reference/fine-tunes/create
*/
public class FineTuneRequest {
/**
* The ID of an uploaded file that contains training data.
*/
@NonNull
String trainingFile;
/**
* The ID of an uploaded file that contains validation data.
*/
String validationFile;
/**
* The name of the base model to fine-tune. You can select one of "ada", "babbage", "curie", or "davinci".
* To learn more about these models, see the Engines documentation.
*/
String model;
/**
* The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.
*/
Integer nEpochs;
/**
* The batch size to use for training.
* The batch size is the number of training examples used to train a single forward and backward pass.
*
* By default, the batch size will be dynamically configured to be ~0.2% of the number of examples in the training
* set, capped at 256 - in general, we've found that larger batch sizes tend to work better for larger datasets.
*/
Integer batchSize;
/**
* The learning rate multiplier to use for training.
* The fine-tuning learning rate is the original learning rate used for pretraining multiplied by this value.
*
* By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on final batch_size
* (larger learning rates tend to perform better with larger batch sizes).
* We recommend experimenting with values in the range 0.02 to 0.2 to see what produces the best results.
*/
Double learningRateMultiplier;
/**
* The weight to use for loss on the prompt tokens.
* This controls how much the model tries to learn to generate the prompt
* (as compared to the completion which always has a weight of 1.0),
* and can add a stabilizing effect to training when completions are short.
*
* If prompts are extremely long (relative to completions), it may make sense to reduce this weight so as to
* avoid over-prioritizing learning the prompt.
*/
Double promptLossWeight;
/**
* If set, we calculate classification-specific metrics such as accuracy and F-1 score using the validation set
* at the end of every epoch. These metrics can be viewed in the results file.
*
* In order to compute classification metrics, you must provide a validation_file.
* Additionally, you must specify {@link FineTuneRequest#classificationNClasses} for multiclass
* classification or {@link FineTuneRequest#classificationPositiveClass} for binary classification.
*/
Boolean computeClassificationMetrics;
/**
* The number of classes in a classification task.
*
* This parameter is required for multiclass classification.
*/
@JsonProperty("classification_n_classes")
Integer classificationNClasses;
/**
* The positive class in binary classification.
*
* This parameter is needed to generate precision, recall, and F1 metrics when doing binary classification.
*/
String classificationPositiveClass;
/**
* If this is provided, we calculate F-beta scores at the specified beta values.
* The F-beta score is a generalization of F-1 score. This is only used for binary classification.
*
* With a beta of 1 (i.e. the F-1 score), precision and recall are given the same weight.
* A larger beta score puts more weight on recall and less on precision.
* A smaller beta score puts more weight on precision and less on recall.
*/
List<Double> classificationBetas;
/**
* A string of up to 40 characters that will be added to your fine-tuned model name.
*/
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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,52 @@
package com.ossez.openai.moderation;
/**
* An object containing the moderation data for a single input string
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
public class Moderation {
/**
* Set to true if the model classifies the content as violating OpenAI's content policy, false otherwise
*/
public boolean flagged;
/**
* Object containing per-category binary content policy violation flags.
* For each category, the value is true if the model flags the corresponding category as violated, false otherwise.
*/
public ModerationCategories categories;
/**
* Object containing per-category raw scores output by the model, denoting the model's confidence that the
* input violates the OpenAI's policy for the category.
* The value is between 0 and 1, where higher values denote higher confidence.
* The scores should not be interpreted as probabilities.
*/
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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,40 @@
package com.ossez.openai.moderation;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A request for OpenAi to detect if text violates OpenAi's content policy.
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
public class ModerationRequest {
/**
* The input text to classify.
*/
@NonNull
String input;
/**
* The name of the model to use, defaults to text-moderation-stable.
*/
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;
}
}
@@ -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;
}
}
@@ -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;
}
@@ -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/create-completion
*/
@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;
}
@@ -1,107 +0,0 @@
package com.theokanning.openai.completion;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* A request for OpenAi to generate a predicted completion for a prompt.
* All fields are nullable.
*
* Documentation taken from
* https://beta.openai.com/docs/api-reference/create-completion
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CompletionRequest {
/**
* An optional prompt to complete from
*/
String prompt;
/**
* The maximum number of tokens to generate.
* Requests can use up to 2048 tokens shared between prompt and completion.
* (One token is roughly 4 characters for normal English text)
*/
Integer maxTokens;
/**
* 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;
/**
* An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of
* the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are
* considered.
*
* We generally recommend using this or {@link temperature} but not both.
*/
Double topP;
/**
* How many completions to generate for each prompt.
*
* Because this parameter generates many completions, it can quickly consume your token quota.
* Use carefully and ensure that you have reasonable settings for {@link max_tokens} and {@link stop}.
*/
Integer n;
/**
* Whether to stream back partial progress.
* If set, tokens will be sent as data-only server-sent events as they become available,
* with the stream terminated by a data: DONE message.
*/
Boolean stream;
/**
* 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;
/**
* Echo back the prompt in addition to the completion
*/
Boolean echo;
/**
* Up to 4 sequences where the API will stop generating further tokens.
* The returned text will not contain the stop sequence.
*/
List<String> stop;
/**
* Number between 0 and 1 (default 0) that penalizes new tokens based on whether they appear in the text so far.
* Increases the model's likelihood to talk about new topics.
*/
Double presencePenalty;
/**
* Number between 0 and 1 (default 0) that penalizes new tokens based on their existing frequency in the text so far.
* Decreases the model's likelihood to repeat the same line verbatim.
*/
Double frequencyPenalty;
/**
* Generates best_of completions server-side and returns the "best"
* (the one with the lowest log probability per token).
* Results cannot be streamed.
*
* When used with {@link n}, best_of controls the number of candidate completions and n specifies how many to return,
* best_of must be greater than n.
*/
Integer bestOf;
}
@@ -1,38 +0,0 @@
package com.theokanning.openai.completion;
import lombok.Data;
import java.util.List;
/**
* An object containing a response from the completion api
*
* https://beta.openai.com/docs/api-reference/create-completion
*/
@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 milliseconds.
*/
long created;
/**
* The GPT-3 model used
*/
String model;
/**
* A list of generated completions
*/
List<CompletionChoice> choices;
}
@@ -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;
}
@@ -1,31 +0,0 @@
package com.theokanning.openai.engine;
import lombok.Data;
/**
* GPT-3 engine details
*
* https://beta.openai.com/docs/api-reference/retrieve-engine
*/
@Data
public class Engine {
/**
* An identifier for this engine, used to specify an engine for completions or searching.
*/
public String id;
/**
* The type of object returned, should be "engine"
*/
public String object;
/**
* The owner of the GPT-3 engine, typically "openai"
*/
public String owner;
/**
* Whether the engine is ready to process requests or not
*/
public boolean ready;
}
@@ -1,32 +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/search
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class SearchRequest {
/**
* Documents to search over
*/
List<String> documents;
/**
* Search query
*/
String query;
}
@@ -1,27 +0,0 @@
package com.theokanning.openai.search;
import lombok.Data;
/**
* A search result for a single document.
*
* https://beta.openai.com/docs/api-reference/search
*/
@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;
}
-14
View File
@@ -1,14 +0,0 @@
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4"
}
}
allprojects {
repositories {
jcenter()
}
}
-79
View File
@@ -1,79 +0,0 @@
apply plugin: 'java-library'
apply plugin: 'com.jfrog.bintray'
apply plugin: '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'
}
ext {
libraryVersion = System.getProperty("libraryVersion")
}
version = libraryVersion
group = 'com.theokanning.openai-gpt3-java'
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
publishing {
publications {
ClientPublication(MavenPublication) {
from components.java
artifact sourcesJar
artifact javadocJar
groupId project.group
artifactId 'client'
version libraryVersion
pom {
description = 'Basic retrofit client for OpenAI\'s GPT-3 API'
name = 'client'
url = 'https://github.com/theokanning/openai-java'
developers {
developer {
id = "theokanning"
name = "Theo Kanning"
email = "theokanning@gmail.com"
}
}
scm {
url = "https://github.com/theokanning/openai-java"
}
licenses {
license {
name = "The MIT License"
url = "https://www.mit.edu/~amini/LICENSE.md"
distribution = "repo"
}
}
}
}
}
}
bintray {
user = System.getenv("BINTRAY_USER")
key = System.getenv("BINTRAY_KEY")
publications = ['ClientPublication']
pkg {
repo = 'openai-gpt3-java'
name = 'client'
vcsUrl = 'https://github.com/TheoKanning/openai-java.git'
licenses = ["MIT"]
publish = false
version {
name = libraryVersion
}
}
}
+409
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>
@@ -1,4 +1,4 @@
package com.theokanning.openai;
package com.ossez.openai;
import okhttp3.Interceptor;
import okhttp3.Request;
@@ -0,0 +1,106 @@
package com.ossez.openai;
import com.ossez.openai.edit.EditRequest;
import com.ossez.openai.edit.EditResult;
import com.ossez.openai.completion.CompletionRequest;
import com.ossez.openai.completion.CompletionResult;
import com.ossez.openai.embedding.EmbeddingRequest;
import com.ossez.openai.embedding.EmbeddingResult;
import com.ossez.openai.engine.Engine;
import com.ossez.openai.file.File;
import com.ossez.openai.finetune.FineTuneEvent;
import com.ossez.openai.finetune.FineTuneRequest;
import com.ossez.openai.finetune.FineTuneResult;
import com.ossez.openai.image.CreateImageRequest;
import com.ossez.openai.image.ImageResult;
import com.ossez.openai.model.Model;
import com.ossez.openai.moderation.ModerationRequest;
import com.ossez.openai.moderation.ModerationResult;
import io.reactivex.Single;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.*;
public interface OpenAiApi {
@GET("v1/models")
Single<OpenAiResponse<Model>> listModels();
@GET("/v1/models/{model_id}")
Single<Model> getModel(@Path("model_id") String modelId);
@POST("/v1/completions")
Single<CompletionResult> createCompletion(@Body CompletionRequest request);
@Deprecated
@POST("/v1/engines/{engine_id}/completions")
Single<CompletionResult> createCompletion(@Path("engine_id") String engineId, @Body CompletionRequest request);
@POST("/v1/edits")
Single<EditResult> createEdit(@Body EditRequest request);
@Deprecated
@POST("/v1/engines/{engine_id}/edits")
Single<EditResult> createEdit(@Path("engine_id") String engineId, @Body EditRequest request);
@POST("/v1/embeddings")
Single<EmbeddingResult> createEmbeddings(@Body EmbeddingRequest request);
@Deprecated
@POST("/v1/engines/{engine_id}/embeddings")
Single<EmbeddingResult> createEmbeddings(@Path("engine_id") String engineId, @Body EmbeddingRequest request);
@GET("/v1/files")
Single<OpenAiResponse<File>> listFiles();
@Multipart
@POST("/v1/files")
Single<File> uploadFile(@Part("purpose") RequestBody purpose, @Part MultipartBody.Part file);
@DELETE("/v1/files/{file_id}")
Single<DeleteResult> deleteFile(@Path("file_id") String fileId);
@GET("/v1/files/{file_id}")
Single<File> retrieveFile(@Path("file_id") String fileId);
@POST("/v1/fine-tunes")
Single<FineTuneResult> createFineTune(@Body FineTuneRequest request);
@POST("/v1/completions")
Single<CompletionResult> createFineTuneCompletion(@Body CompletionRequest request);
@GET("/v1/fine-tunes")
Single<OpenAiResponse<FineTuneResult>> listFineTunes();
@GET("/v1/fine-tunes/{fine_tune_id}")
Single<FineTuneResult> retrieveFineTune(@Path("fine_tune_id") String fineTuneId);
@POST("/v1/fine-tunes/{fine_tune_id}/cancel")
Single<FineTuneResult> cancelFineTune(@Path("fine_tune_id") String fineTuneId);
@GET("/v1/fine-tunes/{fine_tune_id}/events")
Single<OpenAiResponse<FineTuneEvent>> listFineTuneEvents(@Path("fine_tune_id") String fineTuneId);
@DELETE("/v1/models/{fine_tune_id}")
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")
Single<ModerationResult> createModeration(@Body ModerationRequest request);
@Deprecated
@GET("v1/engines")
Single<OpenAiResponse<Engine>> getEngines();
@Deprecated
@GET("/v1/engines/{engine_id}")
Single<Engine> getEngine(@Path("engine_id") String engineId);
}
@@ -0,0 +1,245 @@
package com.ossez.openai;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.ossez.openai.edit.EditRequest;
import com.ossez.openai.edit.EditResult;
import com.ossez.openai.completion.CompletionRequest;
import com.ossez.openai.completion.CompletionResult;
import com.ossez.openai.embedding.EmbeddingRequest;
import com.ossez.openai.embedding.EmbeddingResult;
import com.ossez.openai.engine.Engine;
import com.ossez.openai.file.File;
import com.ossez.openai.finetune.FineTuneEvent;
import com.ossez.openai.finetune.FineTuneRequest;
import com.ossez.openai.finetune.FineTuneResult;
import com.ossez.openai.image.CreateImageEditRequest;
import com.ossez.openai.image.CreateImageRequest;
import com.ossez.openai.image.CreateImageVariationRequest;
import com.ossez.openai.image.ImageResult;
import com.ossez.openai.model.Model;
import com.ossez.openai.moderation.ModerationRequest;
import com.ossez.openai.moderation.ModerationResult;
import okhttp3.*;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class OpenAiService {
OpenAiApi api;
/**
* Creates a new OpenAiService that wraps OpenAiApi
*
* @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
*/
public OpenAiService(String token) {
this(token, 10);
}
/**
* Creates a new OpenAiService that wraps OpenAiApi
*
* @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
* @param timeout http read timeout in seconds, 0 means no timeout
*/
public OpenAiService(String token, int timeout) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new AuthenticationInterceptor(token))
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.readTimeout(timeout, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.openai.com/")
.client(client)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
this.api = retrofit.create(OpenAiApi.class);
}
/**
* Creates a new OpenAiService that wraps OpenAiApi
*
* @param api OpenAiApi instance to use for all methods
*/
public OpenAiService(OpenAiApi api) {
this.api = api;
}
public List<Model> listModels() {
return api.listModels().blockingGet().data;
}
public Model getModel(String modelId) {
return api.getModel(modelId).blockingGet();
}
public CompletionResult createCompletion(CompletionRequest request) {
return api.createCompletion(request).blockingGet();
}
/**
* Use {@link OpenAiService#createCompletion(CompletionRequest)} and {@link CompletionRequest#model}instead
*/
@Deprecated
public CompletionResult createCompletion(String engineId, CompletionRequest request) {
return api.createCompletion(engineId, request).blockingGet();
}
public EditResult createEdit(EditRequest request) {
return api.createEdit(request).blockingGet();
}
/**
* Use {@link OpenAiService#createEdit(EditRequest)} and {@link EditRequest#model}instead
*/
@Deprecated
public EditResult createEdit(String engineId, EditRequest request) {
return api.createEdit(engineId, request).blockingGet();
}
public EmbeddingResult createEmbeddings(EmbeddingRequest request) {
return api.createEmbeddings(request).blockingGet();
}
/**
* Use {@link OpenAiService#createEmbeddings(EmbeddingRequest)} and {@link EmbeddingRequest#model}instead
*/
@Deprecated
public EmbeddingResult createEmbeddings(String engineId, EmbeddingRequest request) {
return api.createEmbeddings(engineId, request).blockingGet();
}
public List<File> listFiles() {
return api.listFiles().blockingGet().data;
}
public File uploadFile(String purpose, String filepath) {
java.io.File file = new java.io.File(filepath);
RequestBody purposeBody = RequestBody.create(okhttp3.MultipartBody.FORM, purpose);
RequestBody fileBody = RequestBody.create(MediaType.parse("text"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", filepath, fileBody);
return api.uploadFile(purposeBody, body).blockingGet();
}
public DeleteResult deleteFile(String fileId) {
return api.deleteFile(fileId).blockingGet();
}
public File retrieveFile(String fileId) {
return api.retrieveFile(fileId).blockingGet();
}
public FineTuneResult createFineTune(FineTuneRequest request) {
return api.createFineTune(request).blockingGet();
}
public CompletionResult createFineTuneCompletion(CompletionRequest request) {
return api.createFineTuneCompletion(request).blockingGet();
}
public List<FineTuneResult> listFineTunes() {
return api.listFineTunes().blockingGet().data;
}
public FineTuneResult retrieveFineTune(String fineTuneId) {
return api.retrieveFineTune(fineTuneId).blockingGet();
}
public FineTuneResult cancelFineTune(String fineTuneId) {
return api.cancelFineTune(fineTuneId).blockingGet();
}
public List<FineTuneEvent> listFineTuneEvents(String fineTuneId) {
return api.listFineTuneEvents(fineTuneId).blockingGet().data;
}
public DeleteResult deleteFineTune(String fineTuneId) {
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) {
return api.createModeration(request).blockingGet();
}
@Deprecated
public List<Engine> getEngines() {
return api.getEngines().blockingGet().data;
}
@Deprecated
public Engine getEngine(String engineId) {
return api.getEngine(engineId).blockingGet();
}
}
@@ -1,27 +0,0 @@
package com.theokanning.openai;
import com.theokanning.openai.engine.Engine;
import com.theokanning.openai.search.SearchRequest;
import io.reactivex.Single;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.search.SearchResult;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface OpenAiApi {
@GET("v1/engines")
Single<OpenAiResponse<Engine>> getEngines();
@GET("/v1/engines/{engine_id}")
Single<Engine> getEngine(@Path("engine_id") String engineId);
@POST("/v1/engines/{engine_id}/completions")
Single<CompletionResult> createCompletion(@Path("engine_id") String engineId, @Body CompletionRequest request);
@POST("/v1/engines/{engine_id}/search")
Single<OpenAiResponse<SearchResult>> search(@Path("engine_id") String engineId, @Body SearchRequest request);
}
@@ -1,61 +0,0 @@
package com.theokanning.openai;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.theokanning.openai.search.SearchRequest;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.engine.Engine;
import com.theokanning.openai.search.SearchResult;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class OpenAiService {
OpenAiApi api;
public OpenAiService(String token) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new AuthenticationInterceptor(token))
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.openai.com/")
.client(client)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
api = retrofit.create(OpenAiApi.class);
}
public List<Engine> getEngines() {
return api.getEngines().blockingGet().data;
}
public Engine getEngine(String engineId) {
return api.getEngine(engineId).blockingGet();
}
public CompletionResult createCompletion(String engineId, CompletionRequest request) {
return api.createCompletion(engineId, request).blockingGet();
}
public List<SearchResult> search(String engineId, SearchRequest request) {
return api.search(engineId, request).blockingGet().data;
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -0,0 +1,43 @@
package com.ossez.openai;
import com.ossez.openai.embedding.Embedding;
import com.ossez.openai.embedding.EmbeddingRequest;
import com.ossez.openai.embedding.EmbeddingRequestBuilder;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class EmbeddingTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createEmbeddings() {
EmbeddingRequest embeddingRequest = new EmbeddingRequestBuilder()
.setModel("text-similarity-babbage-001")
.setInput(Collections.singletonList("The food was delicious and the waiter..."))
.createEmbeddingRequest();
List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
@Test
void createEmbeddingsDeprecated() {
EmbeddingRequest embeddingRequest = new EmbeddingRequestBuilder()
.setInput(Collections.singletonList("The food was delicious and the waiter..."))
.createEmbeddingRequest();
List<Embedding> embeddings = service.createEmbeddings("text-similarity-babbage-001", embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
}
@@ -0,0 +1,30 @@
package com.ossez.openai;
import com.ossez.openai.engine.Engine;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class EngineTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void getEngines() {
List<Engine> engines = service.getEngines();
assertFalse(engines.isEmpty());
}
@Test
void getEngine() {
Engine ada = service.getEngine("ada");
assertEquals("ada", ada.id);
}
}
@@ -0,0 +1,55 @@
package com.ossez.openai;
import com.ossez.openai.file.File;
import org.junit.jupiter.api.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class FileTest {
static String filePath = "src/test/resources/fine-tuning-data.jsonl";
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
static String fileId;
@Test
@Order(1)
void uploadFile() throws Exception {
File file = service.uploadFile("fine-tune", filePath);
fileId = file.getId();
assertEquals("fine-tune", file.getPurpose());
assertEquals(filePath, file.getFilename());
// wait for file to be processed
TimeUnit.SECONDS.sleep(10);
}
@Test
@Order(2)
void listFiles() {
List<File> files = service.listFiles();
assertTrue(files.stream().anyMatch(file -> file.getId().equals(fileId)));
}
@Test
@Order(3)
void retrieveFile() {
File file = service.retrieveFile(fileId);
assertEquals(filePath, file.getFilename());
}
@Test
@Order(4)
void deleteFile() {
DeleteResult result = service.deleteFile(fileId);
assertTrue(result.isDeleted());
}
}
@@ -0,0 +1,79 @@
package com.ossez.openai;
import com.ossez.openai.finetune.FineTuneResult;
import com.ossez.openai.finetune.FineTuneEvent;
import org.junit.jupiter.api.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class FineTuneTest {
static OpenAiService service;
static String fileId;
static String fineTuneId;
@BeforeAll
static void setup() throws Exception {
String token = System.getenv("OPENAI_TOKEN");
service = new OpenAiService(token);
fileId = service.uploadFile("fine-tune", "src/test/resources/fine-tuning-data.jsonl").getId();
// wait for file to be processed
TimeUnit.SECONDS.sleep(10);
}
@AfterAll
static void teardown() {
service.deleteFile(fileId);
}
@Test
@Order(1)
void createFineTune() {
// FineTuneRequest request = FineTuneRequest.builder()
// .trainingFile(fileId)
// .model("ada")
// .build();
//
// FineTuneResult fineTune = service.createFineTune(request);
// fineTuneId = fineTune.getId();
//
// assertEquals("pending", fineTune.getStatus());
}
@Test
@Order(2)
void listFineTunes() {
List<FineTuneResult> fineTunes = service.listFineTunes();
assertTrue(fineTunes.stream().anyMatch(fineTune -> fineTune.getId().equals(fineTuneId)));
}
@Test
@Order(3)
void listFineTuneEvents() {
List<FineTuneEvent> events = service.listFineTuneEvents(fineTuneId);
assertFalse(events.isEmpty());
}
@Test
@Order(3)
void retrieveFineTune() {
FineTuneResult fineTune = service.retrieveFineTune(fineTuneId);
assertEquals("ada", fineTune.getModel());
}
@Test
@Order(4)
void cancelFineTune() {
FineTuneResult fineTune = service.cancelFineTune(fineTuneId);
assertEquals("cancelled", fineTune.getStatus());
}
}
@@ -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());
}
}
@@ -0,0 +1,30 @@
package com.ossez.openai;
import com.ossez.openai.model.Model;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class ModelTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void listModels() {
List<Model> models = service.listModels();
assertFalse(models.isEmpty());
}
@Test
void getModel() {
Model ada = service.getModel("ada");
assertEquals("ada", ada.id);
assertEquals("openai", ada.ownedBy);
assertFalse(ada.permission.isEmpty());
}
}
@@ -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());
}
}
@@ -0,0 +1,2 @@
{"prompt": "prompt", "completion": "text"}
{"prompt": "prompt", "completion": "text"}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

-10
View File
@@ -1,10 +0,0 @@
apply plugin: 'java'
apply plugin: 'application'
application {
mainClassName = 'example.OpenAiApiExample'
}
dependencies {
implementation project(":client")
}
+213
View File
@@ -0,0 +1,213 @@
<?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-example</artifactId>
<packaging>jar</packaging>
<name>OpenAI J Example</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>
<java.level>17</java.level>
</properties>
<dependencies>
<!-- LOGGING WITH SELF4J AND LOG4J2 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- UTILS -->
<dependency>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- / UTILS -->
<!-- TEST -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<!--/ TEST -->
<dependency>
<groupId>com.ossez.openai</groupId>
<artifactId>openai-j-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
</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>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.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins></plugins>
<extensions></extensions>
</build>
<profiles>
</profiles>
</project>
@@ -0,0 +1,25 @@
package com.ossez.openai.example;
import com.ossez.openai.OpenAiService;
import com.ossez.openai.completion.CompletionRequest;
import com.ossez.openai.completion.CompletionRequestBuilder;
/**
* Test Object for ChatGPT OpenAI
*/
public class OpenAiApiExample {
public static void main(String... args) {
String token = "sk-****************************************";
OpenAiService service = new OpenAiService(token);
System.out.println("\nCreating completion...");
CompletionRequest completionRequest = new CompletionRequestBuilder()
.setModel("text-davinci-003")
.setPrompt("长沙机场")
.setMaxTokens(700)
.setEcho(true)
.createCompletionRequest();
System.out.println(service.createCompletion(completionRequest).getChoices().get(0).getText());
}
}
@@ -1,37 +0,0 @@
package example;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.engine.Engine;
import com.theokanning.openai.search.SearchRequest;
import java.util.Arrays;
class OpenAiApiExample {
public static void main(String... args) {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
System.out.println("\nGetting available engines...");
service.getEngines().forEach(System.out::println);
System.out.println("\nGetting ada engine...");
Engine ada = service.getEngine("ada");
System.out.println(ada);
System.out.println("\nCreating completion...");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.build();
service.createCompletion("ada", completionRequest).getChoices().forEach(System.out::println);
System.out.println("\nSearching documents...");
SearchRequest searchRequest = SearchRequest.builder()
.documents(Arrays.asList("Water", "Earth", "Electricity", "Fire"))
.query("Pikachu")
.build();
service.search("ada", searchRequest).forEach(System.out::println);
}
}
Binary file not shown.
-5
View File
@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
-185
View File
@@ -1,185 +0,0 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
Vendored
-104
View File
@@ -1,104 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+534
View File
@@ -0,0 +1,534 @@
<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</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>OpenAI Java</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>https://bug.ossez.com/projects/OSS</url>
</issueManagement>
<modules>
<module>api</module>
<module>client</module>
<module>example</module>
</modules>
<properties>
<java.version>17</java.version>
<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>
<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>
</properties>
<!-- Note that the 'repositories' and 'pluginRepositories' blocks below are actually copy-pasted from the Jenkins org pom. This is on purpose
to keep jenkins core buildable even if one has *not* defined the specific details in the settings.xml file. -->
<repositories>
<!-- <repository>-->
<!-- <id>ossez-repo</id>-->
<!-- <name>Ossez-Repo-Snapshot</name>-->
<!-- <url>https://repo.ossez.com/repository/maven-snapshots/</url>-->
<!-- <snapshots>-->
<!-- <enabled>true</enabled>-->
<!-- </snapshots>-->
<!-- <releases>-->
<!-- <enabled>false</enabled>-->
<!-- </releases>-->
<!-- </repository>-->
</repositories>
<pluginRepositories>
</pluginRepositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17-kohsuke-1</version>
</dependency>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>access-modifier-annotation</artifactId>
<version>${access-modifier-annotation.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<distributionManagement>
<!-- <repository>-->
<!-- <id>ossez-repo</id>-->
<!-- <url>https://repo.ossez.com/repository/maven-releases/</url>-->
<!-- </repository>-->
<!-- <snapshotRepository>-->
<!-- <id>ossrh</id>-->
<!-- <url>https://oss.sonatype.org/content/repositories/snapshots</url>-->
<!-- </snapshotRepository>-->
</distributionManagement>
<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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
<!-- / APACHE COMMONS -->
<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.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.14.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>
<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>
<!--/ 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>
</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>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</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-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-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</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-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.1</version>
<configuration>
<source>11</source>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</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>
-5
View File
@@ -1,5 +0,0 @@
rootProject.name = 'openai-java'
include 'api'
include 'client'
include 'example'