New code for maven

This commit is contained in:
YuCheng Hu 2023-01-06 12:36:47 -05:00
parent add90c312a
commit 0fc2159293
52 changed files with 4339 additions and 0 deletions

500
openai-j-api/pom.xml Normal file
View File

@ -0,0 +1,500 @@
<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</groupId>
<artifactId>openai-j-api</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</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/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>
<modules>
<module>openai-j-api</module>
<module>openai-j-client</module>
</modules>
<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>
<!-- 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>
<site>
<id>github-pages</id>
<url>gitsite:git@github.com/USRealEstate/Usreio-Docs.git:core</url>
</site>
<repository>
<id>ossez-repo</id>
<url>https://repo.ossez.com/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>ossez-repo</id>
<url>https://repo.ossez.com/repository/maven-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.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</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>
</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.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<fork>true</fork>
<compilerReuseStrategy>alwaysNew</compilerReuseStrategy>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<configuration>
<quiet>true</quiet>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<argLine>-noverify
</argLine> <!-- some versions of JDK7/8 causes VerifyError during mock tests: http://code.google.com/p/powermock/issues/detail?id=504 -->
<systemPropertyVariables>
<java.io.tmpdir>${project.build.directory}</java.io.tmpdir>
<forkedProcessTimeoutInSeconds>3600</forkedProcessTimeoutInSeconds>
<java.awt.headless>true</java.awt.headless>
</systemPropertyVariables>
<trimStackTrace>false</trimStackTrace>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.kohsuke</groupId>
<artifactId>access-modifier-checker</artifactId>
<version>${access-modifier-checker.version}</version>
</plugin>
<plugin>
<groupId>com.cloudbees</groupId>
<artifactId>maven-license-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>compile</phase>
<configuration>
<requireCompleteLicenseInfo>true</requireCompleteLicenseInfo>
<script>../licenseCompleter.groovy</script>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jvnet.localizer</groupId>
<artifactId>maven-localizer-plugin</artifactId>
<version>1.24</version>
<configuration>
<outputEncoding>UTF-8</outputEncoding>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.hudson.tools</groupId>
<artifactId>maven-encoding-plugin</artifactId>
<version>1.1</version>
</plugin>
<plugin>
<groupId>com.infradna.tool</groupId>
<artifactId>bridge-method-injector</artifactId>
<version>1.17</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>antlr-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${findbugs-maven-plugin.version}</version>
<configuration>
<effort>Max</effort>
<threshold>High</threshold>
<!--Excludes file is located on the top level -->
<excludeFilterFile>../src/findbugs/findbugs-excludes.xml</excludeFilterFile>
<xmlOutput>true</xmlOutput>
<findbugsXmlOutput>false</findbugsXmlOutput>
</configuration>
<executions>
<execution>
<id>findbugs</id>
<goals>
<goal>check</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.19.0</version>
</plugin>
<plugin>
<groupId>org.jvnet.updatecenter2</groupId>
<artifactId>maven-makepkgs-plugin</artifactId>
<version>0.6.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
<dependencies>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>doxia-module-markdown</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>org.kohsuke</groupId>
<artifactId>wagon-gitsite</artifactId>
<version>0.3.5</version>
</extension>
</extensions>
</build>
<profiles>
</profiles>
</project>

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,239 @@
package com.theokanning.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 {
/**
* 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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,100 @@
package com.theokanning.openai.edit;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* 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 {
/**
* 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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,55 @@
package com.theokanning.openai.embedding;
import java.util.List;
public class EmbeddingRequest {
/**
* 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;
}
}

View File

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

View File

@ -0,0 +1,63 @@
package com.theokanning.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;
}
}

View File

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

View File

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

View File

@ -0,0 +1,203 @@
package com.theokanning.openai.finetune;
import com.fasterxml.jackson.annotation.JsonProperty;
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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,82 @@
package com.theokanning.openai.image;
import lombok.*;
/**
* 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
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CreateImageRequest {
/**
* A text description of the desired image(s). The maximum length in 1000 characters.
*/
@NonNull
String prompt;
/**
* The number of images to generate. Must be between 1 and 10. Defaults to 1.
*/
Integer n;
/**
* The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024".
*/
String size;
/**
* The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url.
*/
String responseFormat;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

View File

@ -0,0 +1,68 @@
package com.theokanning.openai.image;
import lombok.*;
/**
* 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
*/
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CreateImageVariationRequest {
/**
* The number of images to generate. Must be between 1 and 10. Defaults to 1.
*/
Integer n;
/**
* The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024".
*/
String size;
/**
* The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url.
*/
String responseFormat;
/**
* A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
*/
String user;
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getResponseFormat() {
return responseFormat;
}
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,54 @@
package com.theokanning.openai.moderation;
import lombok.Data;
/**
* An object containing the moderation data for a single input string
*
* https://beta.openai.com/docs/api-reference/moderations/create
*/
@Data
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;
}
}

View File

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

View File

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

View File

@ -0,0 +1,39 @@
package com.theokanning.openai.moderation;
/**
* 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;
}
}

View File

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

View File

@ -0,0 +1,28 @@
package com.theokanning.openai;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
/**
* OkHttp Interceptor that adds an authorization token header
*/
public class AuthenticationInterceptor implements Interceptor {
private final String token;
AuthenticationInterceptor(String token) {
this.token = token;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.header("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}

View File

@ -0,0 +1,107 @@
package com.theokanning.openai;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.edit.EditResult;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.embedding.EmbeddingResult;
import com.theokanning.openai.engine.Engine;
import com.theokanning.openai.file.File;
import com.theokanning.openai.finetune.FineTuneEvent;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.finetune.FineTuneResult;
import com.theokanning.openai.image.CreateImageEditRequest;
import com.theokanning.openai.image.CreateImageRequest;
import com.theokanning.openai.image.ImageResult;
import com.theokanning.openai.model.Model;
import com.theokanning.openai.moderation.ModerationRequest;
import com.theokanning.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);
}

View File

@ -0,0 +1,242 @@
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.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.edit.EditResult;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.embedding.EmbeddingResult;
import com.theokanning.openai.engine.Engine;
import com.theokanning.openai.file.File;
import com.theokanning.openai.finetune.FineTuneEvent;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.finetune.FineTuneResult;
import com.theokanning.openai.image.*;
import com.theokanning.openai.model.Model;
import com.theokanning.openai.moderation.ModerationRequest;
import com.theokanning.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();
}
}

View File

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

View File

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

View File

@ -0,0 +1,42 @@
package com.theokanning.openai;
import com.theokanning.openai.embedding.Embedding;
import com.theokanning.openai.embedding.EmbeddingRequest;
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 = EmbeddingRequest.builder()
.model("text-similarity-babbage-001")
.input(Collections.singletonList("The food was delicious and the waiter..."))
.build();
List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
@Test
void createEmbeddingsDeprecated() {
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder()
.input(Collections.singletonList("The food was delicious and the waiter..."))
.build();
List<Embedding> embeddings = service.createEmbeddings("text-similarity-babbage-001", embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
}

View File

@ -0,0 +1,30 @@
package com.theokanning.openai;
import com.theokanning.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);
}
}

View File

@ -0,0 +1,55 @@
package com.theokanning.openai;
import com.theokanning.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());
}
}

View File

@ -0,0 +1,80 @@
package com.theokanning.openai;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.finetune.FineTuneEvent;
import com.theokanning.openai.finetune.FineTuneResult;
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());
}
}

View File

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

View File

@ -0,0 +1,31 @@
package com.theokanning.openai;
import com.theokanning.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());
}
}

View File

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

View File

@ -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

View File

@ -0,0 +1,10 @@
apply plugin: 'java'
apply plugin: 'application'
application {
mainClass.set('example.OpenAiApiExample')
}
dependencies {
implementation project(":client")
}

View File

@ -0,0 +1,20 @@
package example;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
class OpenAiApiExample {
public static void main(String... args) {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
System.out.println("\nCreating completion...");
CompletionRequest completionRequest = CompletionRequest.builder()
.model("ada")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.user("testing")
.build();
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
}
}

489
pom.xml Normal file
View File

@ -0,0 +1,489 @@
<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</groupId>
<artifactId>openai-j</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>OpenAI Java 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>
<modules>
<module>openai-j-api</module>
<!-- <module>openai-j-client</module>-->
</modules>
<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>
<!-- 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>
<site>
<id>github-pages</id>
<url>gitsite:git@github.com/USRealEstate/Usreio-Docs.git:core</url>
</site>
<repository>
<id>ossez-repo</id>
<url>https://repo.ossez.com/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>ossez-repo</id>
<url>https://repo.ossez.com/repository/maven-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.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</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.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.4</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>
</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>