diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..8a60a21 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,88 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '43 7 * * 0' + +jobs: + analyze: + name: Analyze + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners + # Consider using larger runners for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} + permissions: + # required for all workflows + security-events: write + + # only required for workflows in private repositories + actions: read + contents: read + + strategy: + fail-fast: false + matrix: + language: [ 'java-kotlin' ] + # CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ] + # Use only 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - uses: actions/setup-java@v1 + with: + java-version: 17 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + queries: security-extended + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/publish-javadoc-gradle.yml b/.github/workflows/publish-javadoc-gradle.yml new file mode 100644 index 0000000..bb14338 --- /dev/null +++ b/.github/workflows/publish-javadoc-gradle.yml @@ -0,0 +1,21 @@ +name: Deploy Javadoc + +on: + push: + branches: + - master + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Deploy JavaDoc + uses: MathieuSoysal/Javadoc-publisher.yml@v2.5.0 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + javadoc-branch: javadoc + java-version: 17 + target-folder: "" + project: gradle \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..75fb4cc --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +codeofconduct@dannyj.nl. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/README.md b/README.md index 79ade7b..e231c33 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Javadoc](https://img.shields.io/badge/JavaDoc-Online-green)](https://dannyj1.github.io/mistral-java-client/) + # About **Mistral-java-client** is a Java client for the [Mistral AI](https://mistral.ai/) API. It allows you to easily interact @@ -62,6 +64,13 @@ dependencies { ``` +# Documentation + +You can find the javadocs for this library here: https://dannyj1.github.io/mistral-java-client/ + +The Mistral documentation also contains a lot of useful information about their models and what certain parameters +do: https://docs.mistral.ai/ + # Usage The MistralClient class contains all the methods needed to interact with the Mistral AI API. The following examples show @@ -166,9 +175,7 @@ ChatCompletionRequest request = ChatCompletionRequest.builder() .stream(true) .build(); -client. - -createChatCompletionStream(request, new ChatCompletionChunkCallback() { +client.createChatCompletionStream(request, new ChatCompletionChunkCallback() { @Override public void onChunkReceived (MessageChunk chunk){ // This method receives a chunk of the message as it is being generated. @@ -227,8 +234,8 @@ String apiKey = "API_KEY_HERE"; // Initialize the client. This should ideally only be done once. The instance should be re-used for multiple requests MistralClient client = new MistralClient(apiKey); List exampleTexts = List.of( - "This is a test sentence.", - "This is another test sentence." + "This is a test sentence.", + "This is another test sentence." ); EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..588cac7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +To report a vulnerability, please use the "privately reporting a security vulnerability" feature from GitHub. You can find the "Report a vulnerability" button under the security tab. For more information, see the [privately reporting a security vulnerability documentation](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability). diff --git a/build.gradle b/build.gradle index b647b30..aec853d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,12 @@ plugins { - id 'java' - id 'maven-publish' + id "java" + id "maven-publish" id "org.sonarqube" version "4.4.1.3373" + id "io.freefair.lombok" version "8.6" } -group = 'nl.dannyj' -version = '1.0.0' +group = "nl.dannyj" +version = "1.0.0" repositories { mavenCentral() @@ -13,23 +14,18 @@ repositories { dependencies { implementation "com.squareup.okhttp3:okhttp:4.12.0" - implementation 'com.fasterxml.jackson.core:jackson-databind:2.16.1' - implementation 'jakarta.validation:jakarta.validation-api:3.1.0-M1' - implementation 'org.hibernate.validator:hibernate-validator:8.0.1.Final' - implementation 'org.glassfish.expressly:expressly:5.0.0' - implementation 'com.squareup.okio:okio:3.8.0' - - compileOnly 'org.projectlombok:lombok:1.18.30' - annotationProcessor 'org.projectlombok:lombok:1.18.30' - - testImplementation platform('org.junit:junit-bom:5.9.1') - testImplementation 'org.junit.jupiter:junit-jupiter' - testCompileOnly 'org.projectlombok:lombok:1.18.30' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.30' + implementation "com.fasterxml.jackson.core:jackson-databind:2.16.1" + implementation "jakarta.validation:jakarta.validation-api:3.1.0-M1" + implementation "org.hibernate.validator:hibernate-validator:8.0.1.Final" + implementation "org.glassfish.expressly:expressly:5.0.0" + implementation "com.squareup.okio:okio:3.8.0" + + testImplementation platform("org.junit:junit-bom:5.9.1") + testImplementation "org.junit.jupiter:junit-jupiter" } java { - sourceCompatibility = '17' + sourceCompatibility = "17" } publishing { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e583..7f93135 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 23b9738..a80b22c 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,21 +1,7 @@ -# -# Copyright 2024 Danny Jelsma -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -#Mon Feb 19 21:37:05 CET 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1639641..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,13 +1,13 @@ #!/bin/sh # -# Copyright 2024 Danny Jelsma +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, @@ -55,7 +55,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +80,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,22 +131,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ @@ -205,6 +214,12 @@ set -- \ org.gradle.wrapper.GradleWrapperMain \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd3..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionRequest.java b/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionRequest.java index 7ed5bcc..e75613a 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionRequest.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionRequest.java @@ -7,6 +7,7 @@ import lombok.Data; import lombok.NoArgsConstructor; import nl.dannyj.mistral.models.Request; +import nl.dannyj.mistral.net.ChatCompletionChunkCallback; import java.util.List; @@ -22,6 +23,9 @@ public class ChatCompletionRequest implements Request { /** * ID of the model to use. You can use the List Available Models API to see all of your available models. + * + * @param model The model's ID. Can't be null or empty. + * @return The model's ID. */ @NotNull @NotBlank @@ -30,6 +34,9 @@ public class ChatCompletionRequest implements Request { /** * The prompt(s) to generate completions for, encoded as a list of dict with role and content. * Must contain at least one message and the first prompt role should be user or system. + * + * @param messages The messages/conversation to generate completions for. Can't be null or empty. + * @return The messages/conversation to generate completions for. */ @NotNull @Size(min = 1) @@ -39,6 +46,9 @@ public class ChatCompletionRequest implements Request { * What sampling temperature to use, between 0.0 and 1.0. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * We generally recommend altering this or top_p but not both. * Defaults to 0.7. + * + * @param temperature The sampling temperature to use. Has to be between 0.0 and 1.0. + * @return The sampling temperature to use. */ @DecimalMin("0.0") @DecimalMax("1.0") @@ -49,6 +59,9 @@ public class ChatCompletionRequest implements Request { * 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 temperature but not both. * Defaults to 1.0 (i.e., no nucleus sampling). + * + * @param topP the top p value to use. Has to be between 0.0 and 1.0. + * @return the top p value to use. */ @JsonProperty("top_p") @DecimalMin("0.0") @@ -60,6 +73,9 @@ public class ChatCompletionRequest implements Request { * The maximum number of tokens to generate in the completion. * The token count of your prompt plus max_tokens cannot exceed the model's context length. * Defaults to 32000, which is the maximum value for all currently available models. + * + * @param maxTokens The maximum number of tokens to generate in the completion. Has to be positive or zero. + * @return The maximum number of tokens to generate in the completion. */ @JsonProperty("max_tokens") @Builder.Default @@ -67,7 +83,10 @@ public class ChatCompletionRequest implements Request { private Integer maxTokens = 32000; /** - * Currently not implemented, setting this to true will cause issues. + * Whether to stream back partial progress. When set to true, the {@link nl.dannyj.mistral.MistralClient#createChatCompletionStream(ChatCompletionRequest, ChatCompletionChunkCallback)} method has to be used. + * + * @param stream Whether to stream back partial progress. Setting to null will default to false. + * @return Whether to stream back partial progress. */ @Builder.Default private Boolean stream = null; @@ -76,6 +95,9 @@ public class ChatCompletionRequest implements Request { * Whether to inject a safety prompt before all conversations. * Toggling the safe prompt will prepend your messages with the following system prompt: * Always assist with care, respect, and truth. Respond with utmost utility yet securely. Avoid harmful, unethical, prejudiced, or negative content. Ensure replies promote fairness and positivity. + * + * @param safePrompt Whether to inject a safety prompt before all conversations. + * @return Whether to inject a safety prompt before all conversations. */ @JsonProperty("safe_prompt") @Builder.Default @@ -83,6 +105,9 @@ public class ChatCompletionRequest implements Request { /** * The seed to use for random sampling. If set, different calls will generate deterministic results. + * + * @param randomSeed The seed to use for random sampling. Set to null for a random seed. + * @return The seed to use for random sampling. */ @JsonProperty("random_seed") @Builder.Default @@ -90,7 +115,10 @@ public class ChatCompletionRequest implements Request { /** * The response format of the completion request. Defaults to "text". - * Currently only usable when using mistral small and mistral large models. For other models, this MUST be set to null. Otherwise, you may get a 422 Unprocessable Content error. + * Currently only available when using mistral small and mistral large models. For other models, this MUST be set to null. Otherwise, you may get a 422 Unprocessable Content error. + * + * @param responseFormat The response format of the completion request. Currently only available when using mistral small and mistral large models. For other models, this MUST be set to null. + * @return The response format of the completion request. */ @JsonProperty("response_format") private ResponseFormat responseFormat = null; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionResponse.java b/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionResponse.java index afa8b43..d43cb76 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionResponse.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/ChatCompletionResponse.java @@ -37,6 +37,8 @@ public class ChatCompletionResponse implements Response { /** * Unique identifier for this response. + * + * @return the id of the response. */ private String id; @@ -47,21 +49,29 @@ public class ChatCompletionResponse implements Response { /** * The time the chat completion was created in seconds since the epoch. + * + * @return the time the chat completion was created. */ private long created; /** * The model used to generate the completion. + * + * @return the model used to generate the completion. */ private String model; /** * The generated completions. + * + * @return the generated completions. */ private List choices; /** * The tokens used to generate the completion. + * + * @return the amount of tokens used to generate the completion. */ private Usage usage; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/Choice.java b/src/main/java/nl/dannyj/mistral/models/completion/Choice.java index 348dce8..4ac648f 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/Choice.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/Choice.java @@ -23,7 +23,7 @@ import lombok.ToString; /** - * A choice in a completion. + * Represents a choice in a chat completion. A choice contains the message that was generated and the reason for the completion to finish. */ @Getter @AllArgsConstructor @@ -33,16 +33,22 @@ public class Choice { /** * The index of the choice. Starts at 0. + * + * @return the index of the choice */ private int index; /** * The message that was generated. + * + * @return the message that was generated */ private Message message; /** * Reason for the completion to finish. + * + * @return the reason for the completion to finish */ @JsonProperty("finish_reason") private String finishReason; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/DeltaChoice.java b/src/main/java/nl/dannyj/mistral/models/completion/DeltaChoice.java index 1ccdd1b..0aae743 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/DeltaChoice.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/DeltaChoice.java @@ -23,7 +23,7 @@ import lombok.ToString; /** - * A choice of a streamed message chunk in a completion. + * Represents a choice of a streamed message chunk in a completion. A choice contains the message that was generated and the reason for the completion to finish. */ @Getter @AllArgsConstructor @@ -33,17 +33,23 @@ public class DeltaChoice { /** * The index of the choice. Starts at 0. + * + * @return the index of the choice */ private int index; /** * The message that was generated. + * + * @return the message that was generated */ @JsonProperty("delta") private Message message; /** * Reason for the completion to finish. + * + * @return the reason for the completion to finish */ @JsonProperty("finish_reason") private String finishReason; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/Message.java b/src/main/java/nl/dannyj/mistral/models/completion/Message.java index b6c5413..c9542fc 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/Message.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/Message.java @@ -25,7 +25,7 @@ import java.util.List; /** - * A message in a conversation. + * A message in a conversation. A message contains the role of the message, and the content of the message. */ @Data @AllArgsConstructor @@ -35,12 +35,18 @@ public class Message { /** * The role of the message. * Currently, there are 3 roles: user, assistant, and system. + * + * @param role The role of the message. + * @return The role of the message. */ @NotNull private MessageRole role; /** * The content of the message. + * + * @param content The content of the message. + * @return The content of the message. */ @NotNull private String content; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/MessageChunk.java b/src/main/java/nl/dannyj/mistral/models/completion/MessageChunk.java index 3195ad8..259f314 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/MessageChunk.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/MessageChunk.java @@ -17,7 +17,7 @@ package nl.dannyj.mistral.models.completion; import lombok.AllArgsConstructor; -import lombok.Data; +import lombok.Getter; import lombok.NoArgsConstructor; import nl.dannyj.mistral.models.usage.Usage; @@ -27,38 +27,50 @@ * A chunk of a message in a conversation. * Returned when using streaming chat completions. */ -@Data +@Getter @AllArgsConstructor @NoArgsConstructor public class MessageChunk { /** * The ID of the message chunk. + * + * @return the id of the message chunk */ private String id; /** * Always chat.completion.chunk + * + * @return the object type of the message chunk */ private String object; /** * The time the message chunk was created. + * + * @return the time the message chunk was created in seconds since the epoch */ private long created; /** * The model used to generate the completions. + * + * @return the id of the model used to generate the completions */ private String model; /** - * The generated completions. + * The generated delta completions. + * + * @return the generated delta completions */ private List choices; /** * The tokens used to generate the completion. + * + * @return the tokens used to generate the completion */ private Usage usage; } diff --git a/src/main/java/nl/dannyj/mistral/models/completion/MessageRole.java b/src/main/java/nl/dannyj/mistral/models/completion/MessageRole.java index b47b0d1..cab0668 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/MessageRole.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/MessageRole.java @@ -34,7 +34,9 @@ public enum MessageRole { } /** - * @return Lowercase string representation of the role. To be used when interacting with the API. + * Returns a lowercase string representation of the role. To be used when interacting with the API. + * + * @return A lowercase string representation of the role. */ @JsonValue public String getRole() { diff --git a/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormat.java b/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormat.java index 1352e85..a1e5716 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormat.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormat.java @@ -30,7 +30,10 @@ public class ResponseFormat { /** - * The type of the response format. + * The type of the response format. Currently, can either be TEXT or JSON. + * + * @param type The type of the response format. + * @return The type of the response format. */ @NotNull private ResponseFormats type = ResponseFormats.TEXT; diff --git a/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormats.java b/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormats.java index 727d42e..f435cc1 100644 --- a/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormats.java +++ b/src/main/java/nl/dannyj/mistral/models/completion/ResponseFormats.java @@ -33,7 +33,9 @@ public enum ResponseFormats { } /** - * @return Lowercase string representation of the format, as expected by the API. + * Returns a lowercase string representation of the format. To be used when interacting with the API. + * + * @return Lowercase string representation of the format. */ @JsonValue public String getFormat() { diff --git a/src/main/java/nl/dannyj/mistral/models/completion/StreamedMessage.java b/src/main/java/nl/dannyj/mistral/models/completion/StreamedMessage.java deleted file mode 100644 index 664d4f8..0000000 --- a/src/main/java/nl/dannyj/mistral/models/completion/StreamedMessage.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2024 Danny Jelsma - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package nl.dannyj.mistral.models.completion; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class StreamedMessage { - - private String role; - - private String content; - - @JsonProperty("tool_calls") - private List toolCalls; - -} diff --git a/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingRequest.java b/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingRequest.java index ded1d68..53f3014 100644 --- a/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingRequest.java +++ b/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingRequest.java @@ -40,6 +40,9 @@ public class EmbeddingRequest implements Request { /** * The ID of the model to use for this request. + * + * @param model The model ID. + * @return The model ID. */ @NotNull @NotBlank @@ -47,13 +50,19 @@ public class EmbeddingRequest implements Request { /** * The list of strings to embed. + * + * @param input The list of strings to embed. Each entry will be embedded separately. + * @return The list of strings to embed. */ @NotNull @Size(min = 1) private List input; /** - * The format of the output data. The valid values for this are not documented, so assume only "float" is valid for now. + * The format of the output data. + * + * @param encodingFormat The format of the output data. Can only be "float" is valid for now. + * @return The format of the output data. */ @JsonProperty("encoding_format") @Builder.Default diff --git a/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingResponse.java b/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingResponse.java index 19fa5fb..997f5f8 100644 --- a/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingResponse.java +++ b/src/main/java/nl/dannyj/mistral/models/embedding/EmbeddingResponse.java @@ -37,26 +37,36 @@ public class EmbeddingResponse implements Response { /** * Unique identifier for this response. + * + * @return the id of the response */ private String id; /** * Undocumented, seems to be the type of the response. + * + * @return the object type */ private String object; /** * The embeddings that were created for the list of input strings. + * + * @return a list of float embeddings */ private List data; /** * The model used to create the embeddings. + * + * @return the ID of the model used to generate the embeddings */ private String model; /** * The token usage of the request. + * + * @return the usage of the request */ private Usage usage; diff --git a/src/main/java/nl/dannyj/mistral/models/embedding/FloatEmbedding.java b/src/main/java/nl/dannyj/mistral/models/embedding/FloatEmbedding.java index c4d9fcc..24ae53b 100644 --- a/src/main/java/nl/dannyj/mistral/models/embedding/FloatEmbedding.java +++ b/src/main/java/nl/dannyj/mistral/models/embedding/FloatEmbedding.java @@ -31,16 +31,22 @@ public class FloatEmbedding { /** * Undocumented, seems to be the type of the response. + * + * @return the type of the response */ private String object; /** * The embeddings for the input strings. See the mistral documentation for more details on embeddings. + * + * @return the float embeddings for the input string */ private List embedding; /** * The index of the input string in the input list. + * + * @return the index of the input string in the input list */ private int index; diff --git a/src/main/java/nl/dannyj/mistral/models/model/ListModelsResponse.java b/src/main/java/nl/dannyj/mistral/models/model/ListModelsResponse.java index 0647d12..8f40f15 100644 --- a/src/main/java/nl/dannyj/mistral/models/model/ListModelsResponse.java +++ b/src/main/java/nl/dannyj/mistral/models/model/ListModelsResponse.java @@ -36,11 +36,15 @@ public class ListModelsResponse implements Response { /** * Undocumented, seems to be the type of the response. + * + * @return The type of the response. */ private String object; /** * The list of available models. + * + * @return The list of available models. */ @JsonProperty("data") private List models; diff --git a/src/main/java/nl/dannyj/mistral/models/model/Model.java b/src/main/java/nl/dannyj/mistral/models/model/Model.java index 19e185e..395bf98 100644 --- a/src/main/java/nl/dannyj/mistral/models/model/Model.java +++ b/src/main/java/nl/dannyj/mistral/models/model/Model.java @@ -36,6 +36,8 @@ public class Model { /** * The ID of the model. Should be used to refer to the model in other API calls. + * + * @return The ID of the model. */ private String id; @@ -43,11 +45,15 @@ public class Model { /** * Creation time of the model in seconds since the Unix epoch. + * + * @return The creation time of the model in seconds since the Unix epoch. */ private long created; /** * Owner of the model. + * + * @return The owner of the model. */ @JsonProperty("owned_by") private String ownedBy; diff --git a/src/main/java/nl/dannyj/mistral/models/usage/Usage.java b/src/main/java/nl/dannyj/mistral/models/usage/Usage.java index a594510..e025d32 100644 --- a/src/main/java/nl/dannyj/mistral/models/usage/Usage.java +++ b/src/main/java/nl/dannyj/mistral/models/usage/Usage.java @@ -30,18 +30,24 @@ public class Usage { /** * The number of tokens used for the prompt ("input tokens"). + * + * @return the number of tokens used for the prompt */ @JsonProperty("prompt_tokens") private int promptTokens; /** * The total number of tokens used (prompt tokens + completion tokens). + * + * @return the total number of tokens used */ @JsonProperty("total_tokens") private int totalTokens; /** * The number of tokens used for the completion ("output tokens"). + * + * @return the number of tokens used for the completion */ @JsonProperty("completion_tokens") private int completionTokens;