index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training/transferlearning/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains examples of transfer learning. */ package ai.djl.examples.training.transferlearning;
0
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training/util/Arguments.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.examples.training.util; import ai.djl.Device; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Arguments { private int epoch; private int batchSize; private int maxGpus; private boolean isSymbolic; private boolean preTrained; private String outputDir; private long limit; private String modelDir; private Map<String, String> criteria; public Arguments(CommandLine cmd) { if (cmd.hasOption("epoch")) { epoch = Integer.parseInt(cmd.getOptionValue("epoch")); } else { epoch = 2; } maxGpus = Device.getGpuCount(); if (cmd.hasOption("max-gpus")) { maxGpus = Math.min(Integer.parseInt(cmd.getOptionValue("max-gpus")), maxGpus); } if (cmd.hasOption("batch-size")) { batchSize = Integer.parseInt(cmd.getOptionValue("batch-size")); } else { batchSize = maxGpus > 0 ? 32 * maxGpus : 32; } isSymbolic = cmd.hasOption("symbolic-model"); preTrained = cmd.hasOption("pre-trained"); if (cmd.hasOption("output-dir")) { outputDir = cmd.getOptionValue("output-dir"); } else { outputDir = "build/model"; } if (cmd.hasOption("max-batches")) { limit = Long.parseLong(cmd.getOptionValue("max-batches")) * batchSize; } else { limit = Long.MAX_VALUE; } if (cmd.hasOption("model-dir")) { modelDir = cmd.getOptionValue("model-dir"); } else { modelDir = null; } if (cmd.hasOption("criteria")) { Type type = new TypeToken<Map<String, Object>>() {}.getType(); criteria = new Gson().fromJson(cmd.getOptionValue("criteria"), type); } } public static Arguments parseArgs(String[] args) throws ParseException { Options options = Arguments.getOptions(); DefaultParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, null, false); return new Arguments(cmd); } public static Options getOptions() { Options options = new Options(); options.addOption( Option.builder("e") .longOpt("epoch") .hasArg() .argName("EPOCH") .desc("Numbers of epochs user would like to run") .build()); options.addOption( Option.builder("b") .longOpt("batch-size") .hasArg() .argName("BATCH-SIZE") .desc("The batch size of the training data.") .build()); options.addOption( Option.builder("g") .longOpt("max-gpus") .hasArg() .argName("MAXGPUS") .desc("Max number of GPUs to use for training") .build()); options.addOption( Option.builder("s") .longOpt("symbolic-model") .argName("SYMBOLIC") .desc("Use symbolic model, use imperative model if false") .build()); options.addOption( Option.builder("p") .longOpt("pre-trained") .argName("PRE-TRAINED") .desc("Use pre-trained weights") .build()); options.addOption( Option.builder("o") .longOpt("output-dir") .hasArg() .argName("OUTPUT-DIR") .desc("Use output to determine directory to save your model parameters") .build()); options.addOption( Option.builder("m") .longOpt("max-batches") .hasArg() .argName("max-batches") .desc( "Limit each epoch to a fixed number of iterations to test the training script") .build()); options.addOption( Option.builder("d") .longOpt("model-dir") .hasArg() .argName("MODEL-DIR") .desc("pre-trained model file directory") .build()); options.addOption( Option.builder("r") .longOpt("criteria") .hasArg() .argName("CRITERIA") .desc("The criteria used for the model.") .build()); return options; } public int getBatchSize() { return batchSize; } public int getEpoch() { return epoch; } public int getMaxGpus() { return maxGpus; } public boolean isSymbolic() { return isSymbolic; } public boolean isPreTrained() { return preTrained; } public String getModelDir() { return modelDir; } public String getOutputDir() { return outputDir; } public long getLimit() { return limit; } public Map<String, String> getCriteria() { return criteria; } }
0
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training
java-sources/ai/djl/examples/0.6.0/ai/djl/examples/training/util/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains utilities used for the training examples. */ package ai.djl.examples.training.util;
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/FtAbstractBlock.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext; import ai.djl.fasttext.jni.FtWrapper; import ai.djl.nn.AbstractSymbolBlock; import ai.djl.nn.ParameterList; import java.nio.file.Path; /** * A parent class containing shared behavior for {@link ai.djl.nn.SymbolBlock}s based on fasttext * models. */ public abstract class FtAbstractBlock extends AbstractSymbolBlock implements AutoCloseable { protected FtWrapper fta; protected Path modelFile; /** * Constructs a {@link FtAbstractBlock}. * * @param fta the {@link FtWrapper} containing the "fasttext model" */ public FtAbstractBlock(FtWrapper fta) { this.fta = fta; } /** * Returns the fasttext model file for the block. * * @return the fasttext model file for the block */ public Path getModelFile() { return modelFile; } /** * Embeds a word using fasttext. * * @param word the word to embed * @return the embedding * @see ai.djl.modality.nlp.embedding.WordEmbedding */ public float[] embedWord(String word) { return fta.getWordVector(word); } /** {@inheritDoc} */ @Override public ParameterList getDirectParameters() { throw new UnsupportedOperationException("Not yet supported"); } /** {@inheritDoc} */ @Override public void close() { fta.unloadModel(); fta.close(); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/FtModel.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext; import ai.djl.Device; import ai.djl.MalformedModelException; import ai.djl.Model; import ai.djl.fasttext.jni.FtWrapper; import ai.djl.fasttext.zoo.nlp.textclassification.FtTextClassification; import ai.djl.fasttext.zoo.nlp.word_embedding.FtWordEmbeddingBlock; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.nn.Block; import ai.djl.training.Trainer; import ai.djl.training.TrainingConfig; import ai.djl.translate.Translator; import ai.djl.util.PairList; import ai.djl.util.Utils; import ai.djl.util.passthrough.PassthroughNDManager; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** * {@code FtModel} is the fastText implementation of {@link Model}. * * <p>FtModel contains all the methods in Model to load and process a model. However, it only * supports training by using {@link TrainFastText}. */ public class FtModel implements Model { FtAbstractBlock block; private Path modelDir; private String modelName; private Map<String, String> properties; /** * Constructs a new Model. * * @param name the model name */ public FtModel(String name) { this.modelName = name; properties = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void load(Path modelPath, String prefix, Map<String, ?> options) throws IOException, MalformedModelException { if (Files.notExists(modelPath)) { throw new FileNotFoundException( "Model directory doesn't exist: " + modelPath.toAbsolutePath()); } modelDir = modelPath.toAbsolutePath(); Path modelFile = findModelFile(prefix); if (modelFile == null) { modelFile = findModelFile(modelDir.toFile().getName()); if (modelFile == null) { throw new FileNotFoundException("No .ftz or .bin file found in : " + modelPath); } } String modelFilePath = modelFile.toString(); FtWrapper fta = FtWrapper.newInstance(); if (!fta.checkModel(modelFilePath)) { throw new MalformedModelException("Malformed FastText model file:" + modelFilePath); } fta.loadModel(modelFilePath); if (options != null) { for (Map.Entry<String, ?> entry : options.entrySet()) { properties.put(entry.getKey(), entry.getValue().toString()); } } String modelType = fta.getModelType(); properties.put("model-type", modelType); if ("sup".equals(modelType)) { String labelPrefix = properties.getOrDefault( "label-prefix", FtTextClassification.DEFAULT_LABEL_PREFIX); block = new FtTextClassification(fta, labelPrefix); modelDir = block.getModelFile(); } else if ("cbow".equals(modelType) || "sg".equals(modelType)) { block = new FtWordEmbeddingBlock(fta); modelDir = block.getModelFile(); } else { throw new MalformedModelException("Unexpected FastText model type: " + modelType); } } /** {@inheritDoc} */ @Override public void load(InputStream modelStream, Map<String, ?> options) { throw new UnsupportedOperationException("Not supported."); } private Path findModelFile(String prefix) { if (Files.isRegularFile(modelDir)) { Path file = modelDir; modelDir = modelDir.getParent(); String fileName = file.toFile().getName(); if (fileName.endsWith(".ftz") || fileName.endsWith(".bin")) { modelName = fileName.substring(0, fileName.length() - 4); } else { modelName = fileName; } return file; } if (prefix == null) { prefix = modelName; } Path modelFile = modelDir.resolve(prefix); if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) { if (prefix.endsWith(".ftz") || prefix.endsWith(".bin")) { return null; } modelFile = modelDir.resolve(prefix + ".ftz"); if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) { modelFile = modelDir.resolve(prefix + ".bin"); if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) { return null; } } } return modelFile; } /** {@inheritDoc} */ @Override public void save(Path modelDir, String newModelName) {} /** {@inheritDoc} */ @Override public Path getModelPath() { return modelDir; } /** {@inheritDoc} */ @Override public FtAbstractBlock getBlock() { return block; } /** {@inheritDoc} */ @Override public void setBlock(Block block) { if (!(block instanceof FtAbstractBlock)) { throw new IllegalArgumentException("Expected a FtAbstractBlock Block"); } this.block = (FtAbstractBlock) block; } /** {@inheritDoc} */ @Override public String getName() { return modelName; } /** {@inheritDoc} */ @Override public Trainer newTrainer(TrainingConfig trainingConfig) { throw new UnsupportedOperationException( "FastText only supports training using the FtAbstractBlocks"); } /** {@inheritDoc} */ @Override public <I, O> Predictor<I, O> newPredictor(Translator<I, O> translator, Device device) { return new Predictor<>(this, translator, device, false); } /** {@inheritDoc} */ @Override public void setDataType(DataType dataType) {} /** {@inheritDoc} */ @Override public DataType getDataType() { return DataType.UNKNOWN; } /** {@inheritDoc} */ @Override public PairList<String, Shape> describeInput() { return null; } /** {@inheritDoc} */ @Override public PairList<String, Shape> describeOutput() { return null; } /** {@inheritDoc} */ @Override public String[] getArtifactNames() { return Utils.EMPTY_ARRAY; } /** {@inheritDoc} */ @Override public <T> T getArtifact(String name, Function<InputStream, T> function) { return null; } /** {@inheritDoc} */ @Override public URL getArtifact(String artifactName) { return null; } /** {@inheritDoc} */ @Override public InputStream getArtifactAsStream(String name) { return null; } /** {@inheritDoc} */ @Override public NDManager getNDManager() { return PassthroughNDManager.INSTANCE; } /** {@inheritDoc} */ @Override public void setProperty(String key, String value) { properties.put(key, value); } /** {@inheritDoc} */ @Override public String getProperty(String key) { return properties.get(key); } /** {@inheritDoc} */ @Override public Map<String, String> getProperties() { return properties; } /** {@inheritDoc} */ @Override public void close() { block.close(); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(200); sb.append("Model (\n\tName: ").append(modelName); if (modelDir != null) { sb.append("\n\tModel location: ").append(modelDir.toAbsolutePath()); } for (Map.Entry<String, String> entry : properties.entrySet()) { sb.append("\n\t").append(entry.getKey()).append(": ").append(entry.getValue()); } sb.append("\n)"); return sb.toString(); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/FtTrainingConfig.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext; import ai.djl.Device; import ai.djl.nn.Parameter; import ai.djl.training.TrainingConfig; import ai.djl.training.evaluator.Evaluator; import ai.djl.training.initializer.Initializer; import ai.djl.training.listener.TrainingListener; import ai.djl.training.loss.Loss; import ai.djl.training.optimizer.Optimizer; import ai.djl.util.PairList; import ai.djl.util.Utils; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.function.Predicate; /** An interface that is responsible for holding the configuration required by fastText training. */ public class FtTrainingConfig implements TrainingConfig { private FtTrainingMode trainingMode; private Path outputDir; private String modelName; private int epoch; private int minWordCount; private int minLabelCount; private int maxNgramLength; private int minCharLength; private int maxCharLength; private int bucket; private float samplingThreshold; private String labelPrefix; private float learningRate; private int learningRateUpdateRate; private int wordVecSize; private int contextWindow; private int numNegativesSampled; private int threads; private String loss; FtTrainingConfig(Builder builder) { trainingMode = builder.trainingMode; outputDir = builder.outputDir; modelName = builder.modelName; epoch = builder.epoch; minWordCount = builder.minWordCount; minLabelCount = builder.minLabelCount; maxNgramLength = builder.maxNgramLength; minCharLength = builder.minCharLength; maxCharLength = builder.maxCharLength; bucket = builder.bucket; samplingThreshold = builder.samplingThreshold; labelPrefix = builder.labelPrefix; learningRate = builder.learningRate; learningRateUpdateRate = builder.learningRateUpdateRate; wordVecSize = builder.wordVecSize; contextWindow = builder.contextWindow; numNegativesSampled = builder.numNegativesSampled; threads = builder.threads; loss = builder.loss; } /** * Returns the @{link FtTrainingMode}. * * @return the @{code FtTrainingMode} */ public FtTrainingMode getTrainingMode() { return trainingMode; } /** * Returns the output directory. * * @return the output directory */ public Path getOutputDir() { return outputDir; } /** * Return the name of the model. * * @return the name of the model */ public String getModelName() { return modelName; } /** * Returns number of epochs. * * @return number of epochs */ public int getEpoch() { return epoch; } /** * Return minimal number of word occurrences. * * @return minimal number of word occurrences */ public int getMinWordCount() { return minWordCount; } /** * Returns minimal number of label occurrences. * * @return minimal number of label occurrences */ public int getMinLabelCount() { return minLabelCount; } /** * Returns maximum length of word ngram. * * @return maximum length of word ngram */ public int getMaxNgramLength() { return maxNgramLength; } /** * Return minimum length of char ngram. * * @return minimum length of char ngram */ public int getMinCharLength() { return minCharLength; } /** * Return maximum length of char ngram. * * @return maximum length of char ngram */ public int getMaxCharLength() { return maxCharLength; } /** * Returns number of buckets. * * @return number of buckets */ public int getBucket() { return bucket; } /** * Returns sampling threshold. * * @return sampling threshold */ public float getSamplingThreshold() { return samplingThreshold; } /** * Return label prefix. * * @return label prefix */ public String getLabelPrefix() { return labelPrefix; } /** * Returns learning rate. * * @return learning rate */ public float getLearningRate() { return learningRate; } /** * Returns the rate of updates for the learning rate. * * @return the rate of updates for the learning rate */ public int getLearningRateUpdateRate() { return learningRateUpdateRate; } /** * Returns size of word vectors. * * @return size of word vectors */ public int getWordVecSize() { return wordVecSize; } /** * Returns size of the context window. * * @return size of the context window */ public int getContextWindow() { return contextWindow; } /** * Returns number of negatives sampled. * * @return number of negatives sampled */ public int getNumNegativesSampled() { return numNegativesSampled; } /** * Returns number training threads. * * @return number training threads */ public int getThreads() { return threads; } /** * Returns the loss function. * * @return the loss function */ public String getLoss() { return loss; } /** {@inheritDoc} */ @Override public Device[] getDevices() { return new Device[0]; } /** {@inheritDoc} */ @Override public PairList<Initializer, Predicate<Parameter>> getInitializers() { return null; } /** {@inheritDoc} */ @Override public Optimizer getOptimizer() { return null; } /** {@inheritDoc} */ @Override public Loss getLossFunction() { return null; } /** {@inheritDoc} */ @Override public ExecutorService getExecutorService() { return null; } /** {@inheritDoc} */ @Override public List<Evaluator> getEvaluators() { return Collections.emptyList(); } /** {@inheritDoc} */ @Override public List<TrainingListener> getTrainingListeners() { return Collections.emptyList(); } /** * Returns the fastText command in an array. * * @param input training dataset file path * @return the fastText command in an array */ public String[] toCommand(String input) { Path modelFile = outputDir.resolve(modelName).toAbsolutePath(); List<String> cmd = new ArrayList<>(); cmd.add("fasttext"); cmd.add(trainingMode.name().toLowerCase()); cmd.add("-input"); cmd.add(input); cmd.add("-output"); cmd.add(modelFile.toString()); if (epoch >= 0) { cmd.add("-epoch"); cmd.add(String.valueOf(epoch)); } if (minWordCount >= 0) { cmd.add("-minCount"); cmd.add(String.valueOf(minWordCount)); } if (minLabelCount >= 0) { cmd.add("-minCountLabel"); cmd.add(String.valueOf(minLabelCount)); } if (maxNgramLength >= 0) { cmd.add("-wordNgrams"); cmd.add(String.valueOf(maxNgramLength)); } if (minCharLength >= 0) { cmd.add("-minn"); cmd.add(String.valueOf(minCharLength)); } if (maxCharLength >= 0) { cmd.add("-maxn"); cmd.add(String.valueOf(maxCharLength)); } if (bucket >= 0) { cmd.add("-bucket"); cmd.add(String.valueOf(bucket)); } if (samplingThreshold >= 0) { cmd.add("-t"); cmd.add(String.valueOf(samplingThreshold)); } if (labelPrefix != null) { cmd.add("-label"); cmd.add(labelPrefix); } if (learningRate >= 0) { cmd.add("-lr"); cmd.add(String.valueOf(learningRate)); } if (learningRateUpdateRate >= 0) { cmd.add("-lrUpdateRate"); cmd.add(String.valueOf(learningRateUpdateRate)); } if (wordVecSize >= 0) { cmd.add("-dim"); cmd.add(String.valueOf(wordVecSize)); } if (contextWindow >= 0) { cmd.add("-ws"); cmd.add(String.valueOf(contextWindow)); } if (numNegativesSampled >= 0) { cmd.add("-neg"); cmd.add(String.valueOf(numNegativesSampled)); } if (threads >= 0) { cmd.add("-thread"); cmd.add(String.valueOf(threads)); } if (loss != null) { cmd.add("-loss"); cmd.add(loss); } return cmd.toArray(Utils.EMPTY_ARRAY); } /** * Creates a builder to build a {@code FtTrainingConfig}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** A builder to construct a {@code FtTrainingConfig}. */ public static final class Builder { FtTrainingMode trainingMode = FtTrainingMode.SUPERVISED; Path outputDir; String modelName; int epoch = -1; int minWordCount = -1; int minLabelCount = -1; int maxNgramLength = -1; int minCharLength = -1; int maxCharLength = -1; int bucket = -1; float samplingThreshold = -1f; String labelPrefix; float learningRate = -1f; int learningRateUpdateRate = -1; int wordVecSize = -1; int contextWindow = -1; int numNegativesSampled = -1; int threads = -1; String loss; Builder() {} /** * Sets the output directory. * * @param outputDir the output directory * @return this builder */ public Builder setOutputDir(Path outputDir) { this.outputDir = outputDir; return this; } /** * Sets the name of the model. * * @param modelName the name of the model * @return this builder */ public Builder setModelName(String modelName) { this.modelName = modelName; return this; } /** * Sets the optional {@link FtTrainingMode}. * * @param trainingMode the optional {@code FtTrainingMode} (default {@link * FtTrainingMode#SUPERVISED} * @return this builder */ public Builder optTrainingMode(FtTrainingMode trainingMode) { this.trainingMode = trainingMode; return this; } /** * Sets the optional number of epochs. * * @param epoch the optional number of epochs (default 5) * @return this builder */ public Builder optEpoch(int epoch) { this.epoch = epoch; return this; } /** * Sets the optional minimal number of word occurrences. * * @param minWordCount the optional minimal number of word occurrences (default 1) * @return this builder */ public Builder optMinWordCount(int minWordCount) { this.minWordCount = minWordCount; return this; } /** * Sets the optional minimal number of label occurrences. * * @param minLabelCount the optional minimal number of label occurrences (default 0) * @return this builder */ public Builder optMinLabelCount(int minLabelCount) { this.minLabelCount = minLabelCount; return this; } /** * Sets the optional maximum length of word ngram. * * @param maxNgramLength the optional maximum length of word ngram (default 1) * @return this builder */ public Builder optMaxNGramLength(int maxNgramLength) { this.maxNgramLength = maxNgramLength; return this; } /** * Sets the optional minimum length of char ngram. * * @param minCharLength the optional minimum length of char ngram (default 0) * @return this builder */ public Builder optMinCharLength(int minCharLength) { this.minCharLength = minCharLength; return this; } /** * Sets the optional maximum length of char ngram. * * @param maxCharLength the optional maximum length of char ngram (default 0) * @return this builder */ public Builder optMaxCharLength(int maxCharLength) { this.maxCharLength = maxCharLength; return this; } /** * Sets the optional number of buckets. * * @param bucket the optional number of buckets (default 2000000) * @return this builder */ public Builder optBucket(int bucket) { this.bucket = bucket; return this; } /** * Sets the optional sampling threshold. * * @param samplingThreshold the optional sampling threshold (default 0.0001) * @return this builder */ public Builder optSamplingThreshold(float samplingThreshold) { this.samplingThreshold = samplingThreshold; return this; } /** * Sets the optional label prefix. * * @param labelPrefix the optional label prefix (default "__lable__") * @return this builder */ public Builder optLabelPrefix(String labelPrefix) { this.labelPrefix = labelPrefix; return this; } /** * Sets the optional learning rate. * * @param learningRate the optional learning rate (default 0.1) * @return this builder */ public Builder optLearningRate(float learningRate) { this.learningRate = learningRate; return this; } /** * Sets the optional rate of updates for the learning rate. * * @param learningRateUpdateRate the optional rate of updates for the learning rate (default * 100) * @return this builder */ public Builder optLearningRateUpdateRate(int learningRateUpdateRate) { this.learningRateUpdateRate = learningRateUpdateRate; return this; } /** * Sets the optional size of word vectors. * * @param wordVecSize the optional size of word vectors (default 100) * @return this builder */ public Builder optWordVecSize(int wordVecSize) { this.wordVecSize = wordVecSize; return this; } /** * Sets the optional size of the context window. * * @param contextWindow the optional size of the context window (default 5) * @return this builder */ public Builder optContextWindow(int contextWindow) { this.contextWindow = contextWindow; return this; } /** * Sets the optional number of negatives sampled. * * @param numNegativesSampled the optional number of negatives sampled (default 5) * @return this builder */ public Builder optNumNegativesSampled(int numNegativesSampled) { this.numNegativesSampled = numNegativesSampled; return this; } /** * Sets the optional number training threads. * * @param threads the optional number training threads (default 12) * @return this builder */ public Builder optThreads(int threads) { this.threads = threads; return this; } /** * Sets the optional loss function. * * @param loss the optional loss function (default {@link FtLoss#SOFTMAX} * @return this builder */ public Builder optLoss(FtLoss loss) { this.loss = loss.name().toLowerCase(); return this; } /** * Builds a new {@code FtTrainingConfig}. * * @return the new {@code FtTrainingConfig} */ public FtTrainingConfig build() { return new FtTrainingConfig(this); } } /** Loss functions that fastText supports. */ public enum FtLoss { NS, HS, SOFTMAX, OVA } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/FtTrainingMode.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext; /** Training modes that fastText supported. */ public enum FtTrainingMode { SUPERVISED, SKIPGRAM, CBOW }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/TrainFastText.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext; import ai.djl.fasttext.zoo.nlp.textclassification.FtTextClassification; import ai.djl.training.dataset.RawDataset; import java.io.IOException; import java.nio.file.Path; /** A utility to aggregate options for training with fasttext. */ public final class TrainFastText { private TrainFastText() {} /** * Trains a fastText {@link ai.djl.Application.NLP#TEXT_CLASSIFICATION} model. * * @param config the training configuration to use * @param dataset the training dataset * @return the result of the training * @throws IOException when IO operation fails in loading a resource * @see FtTextClassification#fit(FtTrainingConfig, RawDataset) */ public static FtTextClassification textClassification( FtTrainingConfig config, RawDataset<Path> dataset) throws IOException { return FtTextClassification.fit(config, dataset); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains the main fastText implementation of the DJL API. */ package ai.djl.fasttext;
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/jni/FastTextLibrary.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.jni; import java.util.ArrayList; /** A class containing utilities to interact with the SentencePiece Engine's JNI layer. */ @SuppressWarnings("MissingJavadocMethod") final class FastTextLibrary { static final FastTextLibrary LIB = new FastTextLibrary(); private FastTextLibrary() {} native long createFastText(); native void freeFastText(long handle); native void loadModel(long handle, String filePath); native boolean checkModel(String filePath); native void unloadModel(long handle); native String getModelType(long handle); @SuppressWarnings("PMD.LooseCoupling") native int predictProba( long handle, String text, int topK, ArrayList<String> classes, ArrayList<Float> probabilities); native float[] getWordVector(long handle, String word); native int runCmd(String[] args); }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/jni/FtWrapper.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.jni; import ai.djl.modality.Classifications; import ai.djl.util.NativeResource; import java.util.ArrayList; import java.util.List; /** A class containing utilities to interact with the fastText JNI layer. */ @SuppressWarnings("MissingJavadocMethod") public final class FtWrapper extends NativeResource<Long> { private static RuntimeException libraryStatus; static { try { LibUtils.loadLibrary(); } catch (RuntimeException e) { libraryStatus = e; } } private FtWrapper() { super(FastTextLibrary.LIB.createFastText()); } public static FtWrapper newInstance() { if (libraryStatus != null) { throw libraryStatus; } return new FtWrapper(); } public void loadModel(String modelFilePath) { FastTextLibrary.LIB.loadModel(getHandle(), modelFilePath); } public boolean checkModel(String modelFilePath) { return FastTextLibrary.LIB.checkModel(modelFilePath); } public void unloadModel() { FastTextLibrary.LIB.unloadModel(getHandle()); } public String getModelType() { return FastTextLibrary.LIB.getModelType(getHandle()); } public Classifications predictProba(String text, int topK, String labelPrefix) { int cap = topK != -1 ? topK : 10; ArrayList<String> labels = new ArrayList<>(cap); ArrayList<Float> probs = new ArrayList<>(cap); int size = FastTextLibrary.LIB.predictProba(getHandle(), text, topK, labels, probs); List<String> classes = new ArrayList<>(size); List<Double> probabilities = new ArrayList<>(size); for (int i = 0; i < size; ++i) { String label = labels.get(i); if (label.startsWith(labelPrefix)) { label = label.substring(labelPrefix.length()); } classes.add(label); probabilities.add((double) probs.get(i)); } return new Classifications(classes, probabilities); } public float[] getWordVector(String word) { return FastTextLibrary.LIB.getWordVector(getHandle(), word); } public void runCmd(String[] args) { FastTextLibrary.LIB.runCmd(args); } /** {@inheritDoc} */ @Override public void close() { Long pointer = handle.getAndSet(null); if (pointer != null) { FastTextLibrary.LIB.freeFastText(pointer); } } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/jni/LibUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.jni; import ai.djl.util.ClassLoaderUtils; import ai.djl.util.Ec2Utils; import ai.djl.util.Platform; import ai.djl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; /** * Utilities for finding the SentencePiece binary on the System. * * <p>The binary will be searched for in a variety of locations in the following order: * * <ol> * <li>In the path specified by the SENTENCEPIECE_LIBRARY_PATH environment variable * <li>In a jar file location in the classpath. These jars can be created with the pytorch-native * module. * </ol> */ @SuppressWarnings("MissingJavadocMethod") public final class LibUtils { private static final Logger logger = LoggerFactory.getLogger(LibUtils.class); private static final String LIB_NAME = "jni_fasttext"; private LibUtils() {} public static void loadLibrary() { Ec2Utils.callHome("fastText"); if (System.getProperty("os.name").startsWith("Win")) { throw new UnsupportedOperationException("Windows is not supported."); } String libName = copyJniLibraryFromClasspath(); logger.debug("Loading fasttext library from: {}", libName); System.load(libName); // NOPMD } private static String copyJniLibraryFromClasspath() { String name = System.mapLibraryName(LIB_NAME); Path nativeDir = Utils.getEngineCacheDir("fasttext"); Platform platform = Platform.detectPlatform("fasttext"); String classifier = platform.getClassifier(); String version = platform.getVersion(); Path path = nativeDir.resolve(version).resolve(name); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } Path tmp = null; String libPath = "native/lib/" + classifier + "/" + name; try (InputStream is = ClassLoaderUtils.getResourceAsStream(libPath)) { Files.createDirectories(nativeDir.resolve(version)); tmp = Files.createTempFile(nativeDir, "jni", "tmp"); Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING); Utils.moveQuietly(tmp, path); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Cannot copy jni files", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/jni/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains classes to interface with the underlying fastText. */ package ai.djl.fasttext.jni;
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/FtModelZoo.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo; import ai.djl.engine.Engine; import ai.djl.fasttext.zoo.nlp.textclassification.TextClassificationModelLoader; import ai.djl.repository.RemoteRepository; import ai.djl.repository.Repository; import ai.djl.repository.zoo.ModelZoo; import java.util.Collections; import java.util.Set; /** FtModelZoo is a repository that contains all fastText models for DJL. */ public class FtModelZoo extends ModelZoo { private static final Repository REPOSITORY = new RemoteRepository("Fasttext", DJL_REPO_URL); public static final String GROUP_ID = "ai.djl.fasttext"; FtModelZoo() { addModel(new TextClassificationModelLoader(REPOSITORY)); } /** {@inheritDoc} */ @Override public String getGroupId() { return GROUP_ID; } /** {@inheritDoc} */ @Override public Set<String> getSupportedEngines() { return Collections.singleton(Engine.getDefaultEngineName()); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/FtZooProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooProvider; /** * An fastText model zoo provider implements the {@link ai.djl.repository.zoo.ZooProvider} * interface. */ public class FtZooProvider implements ZooProvider { /** {@inheritDoc} */ @Override public ModelZoo getModelZoo() { return new FtModelZoo(); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains the built-in {@link ai.djl.fasttext.zoo.FtModelZoo}. */ package ai.djl.fasttext.zoo;
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/textclassification/FtTextClassification.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo.nlp.textclassification; import ai.djl.fasttext.FtAbstractBlock; import ai.djl.fasttext.FtTrainingConfig; import ai.djl.fasttext.jni.FtWrapper; import ai.djl.fasttext.zoo.nlp.word_embedding.FtWordEmbeddingBlock; import ai.djl.modality.Classifications; import ai.djl.ndarray.NDList; import ai.djl.training.ParameterStore; import ai.djl.training.TrainingResult; import ai.djl.training.dataset.RawDataset; import ai.djl.util.PairList; import ai.djl.util.passthrough.PassthroughNDArray; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** A {@link FtAbstractBlock} for {@link ai.djl.Application.NLP#TEXT_CLASSIFICATION}. */ public class FtTextClassification extends FtAbstractBlock { public static final String DEFAULT_LABEL_PREFIX = "__label__"; private String labelPrefix; private TrainingResult trainingResult; /** * Constructs a {@link FtTextClassification}. * * @param fta the {@link FtWrapper} containing the "fasttext model" * @param labelPrefix the prefix to use for labels */ public FtTextClassification(FtWrapper fta, String labelPrefix) { super(fta); this.labelPrefix = labelPrefix; } /** * Trains the fastText model. * * @param config the training configuration to use * @param dataset the training dataset * @return the result of the training * @throws IOException when IO operation fails in loading a resource */ public static FtTextClassification fit(FtTrainingConfig config, RawDataset<Path> dataset) throws IOException { Path outputDir = config.getOutputDir(); if (Files.notExists(outputDir)) { Files.createDirectory(outputDir); } String fitModelName = config.getModelName(); FtWrapper fta = FtWrapper.newInstance(); Path modelFile = outputDir.resolve(fitModelName).toAbsolutePath(); String[] args = config.toCommand(dataset.getData().toString()); fta.runCmd(args); TrainingResult result = new TrainingResult(); int epoch = config.getEpoch(); if (epoch <= 0) { epoch = 5; } result.setEpoch(epoch); FtTextClassification block = new FtTextClassification(fta, config.getLabelPrefix()); block.modelFile = modelFile; block.trainingResult = result; return block; } /** * Returns the fasttext label prefix. * * @return the fasttext label prefix */ public String getLabelPrefix() { return labelPrefix; } /** * Returns the results of training, or null if not trained. * * @return the results of training, or null if not trained */ public TrainingResult getTrainingResult() { return trainingResult; } @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { PassthroughNDArray inputWrapper = (PassthroughNDArray) inputs.singletonOrThrow(); String input = (String) inputWrapper.getObject(); Classifications result = fta.predictProba(input, -1, labelPrefix); return new NDList(new PassthroughNDArray(result)); } /** * Converts the block into the equivalent {@link FtWordEmbeddingBlock}. * * @return the equivalent {@link FtWordEmbeddingBlock} */ public FtWordEmbeddingBlock toWordEmbedding() { return new FtWordEmbeddingBlock(fta); } /** * Returns the classifications of the input text. * * @param text the input text to be classified * @return classifications of the input text */ public Classifications classify(String text) { return classify(text, -1); } /** * Returns top K classifications of the input text. * * @param text the input text to be classified * @param topK the value of K * @return classifications of the input text */ public Classifications classify(String text, int topK) { return fta.predictProba(text, topK, labelPrefix); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/textclassification/TextClassificationModelLoader.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo.nlp.textclassification; import ai.djl.Application; import ai.djl.MalformedModelException; import ai.djl.Model; import ai.djl.fasttext.FtModel; import ai.djl.fasttext.zoo.FtModelZoo; import ai.djl.repository.Artifact; import ai.djl.repository.Repository; import ai.djl.repository.zoo.BaseModelLoader; import ai.djl.repository.zoo.Criteria; import ai.djl.repository.zoo.ModelNotFoundException; import ai.djl.repository.zoo.ZooModel; import ai.djl.util.Progress; import ai.djl.util.passthrough.PassthroughTranslator; import java.io.IOException; import java.nio.file.Path; /** Model loader for fastText cooking stackexchange models. */ public class TextClassificationModelLoader extends BaseModelLoader { private static final Application APPLICATION = Application.NLP.TEXT_CLASSIFICATION; private static final String GROUP_ID = FtModelZoo.GROUP_ID; private static final String ARTIFACT_ID = "cooking_stackexchange"; private static final String VERSION = "0.0.1"; /** * Creates the Model loader from the given repository. * * @param repository the repository to load the model from */ public TextClassificationModelLoader(Repository repository) { super(repository.model(APPLICATION, GROUP_ID, ARTIFACT_ID, VERSION)); } /** {@inheritDoc} */ @Override public <I, O> ZooModel<I, O> loadModel(Criteria<I, O> criteria) throws ModelNotFoundException, IOException, MalformedModelException { Artifact artifact = mrl.match(criteria.getFilters()); if (artifact == null) { throw new ModelNotFoundException("No matching filter found"); } Progress progress = criteria.getProgress(); mrl.prepare(artifact, progress); if (progress != null) { progress.reset("Loading", 2); progress.update(1); } String modelName = criteria.getModelName(); if (modelName == null) { modelName = artifact.getName(); } Model model = new FtModel(modelName); Path modelPath = mrl.getRepository().getResourceDirectory(artifact); model.load(modelPath, modelName, criteria.getOptions()); return new ZooModel<>(model, new PassthroughTranslator<>()); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/textclassification/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** * Contains classes for the {@link ai.djl.Application.NLP#TEXT_CLASSIFICATION} models in the {@link * ai.djl.fasttext.zoo.FtModelZoo}. */ package ai.djl.fasttext.zoo.nlp.textclassification;
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/word_embedding/FtWord2VecWordEmbedding.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo.nlp.word_embedding; import ai.djl.Model; import ai.djl.fasttext.FtAbstractBlock; import ai.djl.fasttext.FtModel; import ai.djl.modality.nlp.Vocabulary; import ai.djl.modality.nlp.embedding.WordEmbedding; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.repository.zoo.ZooModel; /** An implementation of {@link WordEmbedding} for FastText word embeddings. */ public class FtWord2VecWordEmbedding implements WordEmbedding { private FtAbstractBlock embedding; private Vocabulary vocabulary; /** * Constructs a {@link FtWord2VecWordEmbedding}. * * @param model a loaded FastText wordEmbedding model or a ZooModel containing one * @param vocabulary the {@link Vocabulary} to get indices from */ public FtWord2VecWordEmbedding(Model model, Vocabulary vocabulary) { if (model instanceof ZooModel) { model = ((ZooModel<?, ?>) model).getWrappedModel(); } if (!(model instanceof FtModel)) { throw new IllegalArgumentException("The FtWord2VecWordEmbedding requires an FtModel"); } this.embedding = ((FtModel) model).getBlock(); this.vocabulary = vocabulary; } /** * Constructs a {@link FtWord2VecWordEmbedding}. * * @param embedding the word embedding * @param vocabulary the {@link Vocabulary} to get indices from */ public FtWord2VecWordEmbedding(FtAbstractBlock embedding, Vocabulary vocabulary) { this.embedding = embedding; this.vocabulary = vocabulary; } /** {@inheritDoc} */ @Override public boolean vocabularyContains(String word) { return true; } /** {@inheritDoc} */ @Override public long preprocessWordToEmbed(String word) { return vocabulary.getIndex(word); } /** {@inheritDoc} */ @Override public NDArray embedWord(NDArray index) { return embedWord(index.getManager(), index.toLongArray()[0]); } /** {@inheritDoc} */ @Override public NDArray embedWord(NDManager manager, long index) { String word = vocabulary.getToken(index); float[] buf = embedding.embedWord(word); return manager.create(buf); } /** {@inheritDoc} */ @Override public String unembedWord(NDArray word) { if (!word.isScalar()) { throw new IllegalArgumentException("NDArray word must be scalar index"); } return vocabulary.getToken(word.toLongArray()[0]); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/word_embedding/FtWordEmbeddingBlock.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.fasttext.zoo.nlp.word_embedding; import ai.djl.fasttext.FtAbstractBlock; import ai.djl.fasttext.jni.FtWrapper; import ai.djl.ndarray.NDList; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import ai.djl.util.passthrough.PassthroughNDArray; /** A {@link FtAbstractBlock} for {@link ai.djl.Application.NLP#WORD_EMBEDDING}. */ public class FtWordEmbeddingBlock extends FtAbstractBlock { /** * Constructs a {@link FtWordEmbeddingBlock}. * * @param fta the {@link FtWrapper} for the "fasttext model". */ public FtWordEmbeddingBlock(FtWrapper fta) { super(fta); } @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { PassthroughNDArray inputWrapper = (PassthroughNDArray) inputs.singletonOrThrow(); String input = (String) inputWrapper.getObject(); float[] result = embedWord(input); return new NDList(new PassthroughNDArray(result)); } }
0
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp
java-sources/ai/djl/fasttext/fasttext-engine/0.34.0/ai/djl/fasttext/zoo/nlp/word_embedding/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** * Contains classes for the {@link ai.djl.Application.NLP#WORD_EMBEDDING} models in the {@link * ai.djl.fasttext.zoo.FtModelZoo}. */ package ai.djl.fasttext.zoo.nlp.word_embedding;
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/FunctionUtils.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai; import ai.djl.util.JsonUtils; import ai.djl.util.Pair; import ai.djl.util.PairList; import com.google.gson.reflect.TypeToken; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** A utility class for function calling. */ public final class FunctionUtils { private static final Map<String, String> TYPE_MAPPING = new ConcurrentHashMap<>(); private static final Type GENERIC_MAP = new TypeToken<Map<String, String>>() {}.getType(); static { TYPE_MAPPING.put("java.lang.String", "string"); TYPE_MAPPING.put("boolean", "boolean"); TYPE_MAPPING.put("Boolean", "boolean"); TYPE_MAPPING.put("int", "integer"); TYPE_MAPPING.put("long", "integer"); TYPE_MAPPING.put("java.lang.Integer", "integer"); TYPE_MAPPING.put("java.lang.Long", "integer"); TYPE_MAPPING.put("float", "number"); TYPE_MAPPING.put("java.lang.Float", "number"); TYPE_MAPPING.put("double", "number"); TYPE_MAPPING.put("java.lang.Double", "number"); } private FunctionUtils() {} /** * Returns the LLM model's function call data type. * * @param type the java type * @return the LLM model's function call data type */ public static String toModelType(Class<?> type) { if (type.isArray()) { return "array"; } String modelType = TYPE_MAPPING.get(type.getName()); if (modelType != null) { return modelType; } return "object"; } /** * Invokes the underlying method represented by the {@code Method} object. * * @param method the method object * @param obj the object the underlying method is invoked from * @param arguments the arguments used for the method call * @return the object returned by the method * @throws IllegalAccessException if this {@code Method} object is enforcing Java language * access control and the underlying method is inaccessible. * @throws IllegalArgumentException if the method is not accessible */ public static Object invoke(Method method, Object obj, String arguments) throws InvocationTargetException, IllegalAccessException { Map<String, Object> args = JsonUtils.GSON.fromJson(arguments, GENERIC_MAP); return invoke(method, obj, args); } /** * Invokes the underlying method represented by the {@code Method} object. * * @param method the method object * @param obj the object the underlying method is invoked from * @param args the arguments used for the method call * @return the object returned by the method * @throws IllegalAccessException if this {@code Method} object is enforcing Java language * access control and the underlying method is inaccessible. * @throws IllegalArgumentException if the method is not accessible */ public static Object invoke(Method method, Object obj, Map<String, Object> args) throws InvocationTargetException, IllegalAccessException { PairList<String, String> types = FunctionUtils.getParameters(method, false); List<Object> values = new ArrayList<>(); for (Pair<String, String> pair : types) { String name = pair.getKey(); String type = pair.getValue(); Object value = args.get(name); if (value == null) { throw new IllegalArgumentException("Missing argument: " + name); } addArgument(values, type, value.toString()); } return method.invoke(obj, values.toArray()); } /** * Returns the method's parameter names and types. * * @param method the method * @return the method's parameter names and types */ public static PairList<String, String> getParameters(Method method) { return getParameters(method, true); } private static PairList<String, String> getParameters(Method method, boolean mapping) { PairList<String, String> list = new PairList<>(); Parameter[] parameters = method.getParameters(); for (Parameter parameter : parameters) { if (!parameter.isNamePresent()) { throw new IllegalArgumentException( "Failed to retrieve the parameter name from reflection. Please compile your" + " code with the \"-parameters\" flag or provide parameter names" + " manually."); } String parameterName = parameter.getName(); Class<?> type = parameter.getType(); String typeName = mapping ? toModelType(type) : type.getName(); list.add(parameterName, typeName); } return list; } private static void addArgument(List<Object> values, String type, String value) { if ("java.lang.String".equals(type)) { values.add(value); } else if ("boolean".equals(type) || "java.lang.Boolean".equals(type)) { values.add(Boolean.valueOf(value)); } else if ("int".equals(type) || "java.lang.Integer".equals(type)) { values.add(Integer.valueOf(value)); } else if ("long".equals(type) || "java.lang.Long".equals(type)) { values.add(Long.valueOf(value)); } else if ("float".equals(type) || "java.lang.Float".equals(type)) { values.add(Float.valueOf(value)); } else if ("double".equals(type) || "java.lang.Double".equals(type)) { values.add(Double.valueOf(value)); } else { throw new IllegalArgumentException("Unsupported parameter type " + type); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/package-info.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains classes for genai extension. */ package ai.djl.genai;
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Anthropic.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import ai.djl.util.Utils; /** Utility class to hold the Gemini models url. */ public final class Anthropic { public static final Anthropic OPUS_4_1 = new Anthropic("claude-opus-4-1@20250805"); public static final Anthropic OPUS_4 = new Anthropic("claude-opus-4@20250514"); public static final Anthropic SONNET_4 = new Anthropic("claude-sonnet-4@20250514"); public static final Anthropic SONNET_3_7 = new Anthropic("claude-3-7-sonnet@20250219"); public static final Anthropic SONNET_3_5 = new Anthropic("claude-3-5-sonnet@20240620"); public static final Anthropic HAIKU_3_5 = new Anthropic("claude-3-5-haiku@20241022"); public static final Anthropic HAIKU_3 = new Anthropic("claude-3-haiku@20240307"); private String model; Anthropic(String model) { this.model = model; } /** * Returns the model's endpoint URL. * * @return the model's endpoint URL */ public String getUrl() { return getUrl(false, false, null, null, null); } String getUrl(String baseUrl) { return getUrl(baseUrl, false); } String getUrl(String baseUrl, boolean stream) { return getUrl(stream, true, null, null, baseUrl); } /** * Returns the model's endpoint URL on Vertex. * * @return the model's endpoint URL on Vertex */ public String getUrl(boolean stream) { return getUrl(stream, true, null, null, null); } /** * Returns the model's endpoint URL on Vertex with specified project and location. * * @return the model's endpoint URL on Vertex with specified project and location */ String getUrl(boolean stream, String project, String location) { return getUrl(stream, true, project, location, null); } String getUrl( boolean stream, boolean useVertex, String project, String location, String baseUrl) { if (!useVertex) { if (baseUrl == null) { return "https://api.anthropic.com/v1/messages"; } return baseUrl; } if (location == null) { location = Utils.getEnvOrSystemProperty("REGION", "global"); } if (project == null) { project = Utils.getEnvOrSystemProperty("PROJECT"); } if (baseUrl == null) { if ("global".equals(location)) { baseUrl = "https://aiplatform.googleapis.com"; } else { baseUrl = "https://" + location + "-aiplatform.googleapis.com"; } } StringBuilder sb = new StringBuilder(baseUrl); if (project == null) { throw new IllegalArgumentException("project is required."); } sb.append("/v1/projects/") .append(project) .append("/locations/") .append(location) .append("/publishers/anthropic/models/") .append(model) .append(':'); if (stream) { sb.append("streamRawPredict"); } else { sb.append("rawPredict"); } return sb.toString(); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/AnthropicInput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** The Anthropic style input. */ public class AnthropicInput { @SerializedName("anthropic_version") private String anthropicVersion; private String model; @SerializedName("max_tokens") private Integer maxTokens; private List<Message> messages; private String container; @SerializedName("mcp_servers") private List<McpServer> mcpServers; private Metadata metadata; @SerializedName("service_tier") private String serviceTier; @SerializedName("stop_sequences") private List<String> stopSequences; private Boolean stream; @SerializedName("system") private String systemInstructions; private Float temperature; private Thinking thinking; @SerializedName("tool_choice") private ToolChoice toolChoice; private List<Tool> tools; @SerializedName("top_k") private Integer topK; @SerializedName("top_p") private Float topP; AnthropicInput(Builder builder) { this.anthropicVersion = builder.anthropicVersion; this.model = builder.model; this.maxTokens = builder.maxTokens; this.messages = builder.messages; this.container = builder.container; this.mcpServers = builder.mcpServers; this.metadata = builder.metadata; this.serviceTier = builder.serviceTier; this.stopSequences = builder.stopSequences; this.stream = builder.stream; this.systemInstructions = builder.systemInstructions; this.temperature = builder.temperature; this.thinking = builder.thinking; this.toolChoice = builder.toolChoice; this.tools = builder.tools; this.topK = builder.topK; this.topP = builder.topP; } /** * Returns the Anthropic version. * * @return the Anthropic version */ public String getAnthropicVersion() { return anthropicVersion; } /** * Returns the model. * * @return the model */ public String getModel() { return model; } /** * Returns the maxTokens. * * @return the maxTokens */ public Integer getMaxTokens() { return maxTokens; } /** * Returns the messages. * * @return the messages */ public List<Message> getMessages() { return messages; } /** * Returns the container. * * @return the container */ public String getContainer() { return container; } /** * Returns the mcpServers. * * @return the mcpServers */ public List<McpServer> getMcpServers() { return mcpServers; } /** * Returns the metadata. * * @return the metadata */ public Metadata getMetadata() { return metadata; } /** * Returns the serviceTier. * * @return the serviceTier */ public String getServiceTier() { return serviceTier; } /** * Returns the stopSequences. * * @return the stopSequences */ public List<String> getStopSequences() { return stopSequences; } /** * Returns the stream. * * @return the stream */ public Boolean getStream() { return stream; } /** * Returns the systemInstructions. * * @return the systemInstructions */ public String getSystemInstructions() { return systemInstructions; } /** * Returns the temperature. * * @return the temperature */ public Float getTemperature() { return temperature; } /** * Returns the thinking. * * @return the thinking */ public Thinking getThinking() { return thinking; } /** * Returns the toolChoice. * * @return the toolChoice */ public ToolChoice getToolChoice() { return toolChoice; } /** * Returns the tools. * * @return the tools */ public List<Tool> getTools() { return tools; } /** * Returns the topK. * * @return the topK */ public Integer getTopK() { return topK; } /** * Returns the topP. * * @return the topP */ public Float getTopP() { return topP; } /** * Creates a builder to build a {@code AnthropicInput}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code AnthropicInput}. */ public static final class Builder { String anthropicVersion; String model; Integer maxTokens = 512; List<Message> messages = new ArrayList<>(); String container; List<McpServer> mcpServers; Metadata metadata; String serviceTier; List<String> stopSequences; Boolean stream; String systemInstructions; Float temperature; Thinking thinking; ToolChoice toolChoice; List<Tool> tools; Integer topK; Float topP; /** * Sets the anthropicVersion. * * @param anthropicVersion the anthropicVersion * @return the builder */ public Builder anthropicVersion(String anthropicVersion) { this.anthropicVersion = anthropicVersion; return this; } /** * Sets the model. * * @param model the model * @return the builder */ public Builder model(String model) { this.model = model; return this; } /** * Sets the maxTokens. * * @param maxTokens the maxTokens * @return the builder */ public Builder maxTokens(Integer maxTokens) { this.maxTokens = maxTokens; return this; } /** * Sets the messages. * * @param messages the messages * @return the builder */ public Builder messages(List<Message> messages) { this.messages = messages; return this; } /** * Adds the message. * * @param message the message * @return the builder */ public Builder addMessage(Message.Builder message) { return addMessage(message.build()); } /** * Adds the message. * * @param message the message * @return the builder */ public Builder addMessage(Message message) { this.messages.add(message); return this; } /** * Sets the container. * * @param container the container * @return the builder */ public Builder container(String container) { this.container = container; return this; } /** * Sets the mcpServers. * * @param mcpServers the mcpServers * @return the builder */ public Builder mcpServers(List<McpServer> mcpServers) { this.mcpServers = mcpServers; return this; } /** * Sets the metadata. * * @param metadata the metadata * @return the builder */ public Builder metadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Sets the serviceTier. * * @param serviceTier the serviceTier * @return the builder */ public Builder serviceTier(String serviceTier) { this.serviceTier = serviceTier; return this; } /** * Sets the stopSequences. * * @param stopSequences the stopSequences * @return the builder */ public Builder stopSequences(List<String> stopSequences) { this.stopSequences = stopSequences; return this; } /** * Sets the stream. * * @param stream the stream * @return the builder */ public Builder stream(Boolean stream) { this.stream = stream; return this; } /** * Sets the system instructions. * * @param systemInstructions the system instructions * @return the builder */ public Builder systemInstructions(String systemInstructions) { this.systemInstructions = systemInstructions; return this; } /** * Sets the temperature. * * @param temperature the temperature * @return the builder */ public Builder temperature(Float temperature) { this.temperature = temperature; return this; } /** * Sets the thinking. * * @param thinking the thinking * @return the builder */ public Builder thinking(Thinking thinking) { this.thinking = thinking; return this; } /** * Sets the tool choice. * * @param toolChoice the tool choice * @return the builder */ public Builder toolChoice(ToolChoice toolChoice) { this.toolChoice = toolChoice; return this; } /** * Sets the tools. * * @param tools the tools * @return the builder */ public Builder tools(List<Tool> tools) { this.tools = tools; return this; } /** * Adds the tool. * * @param tool the tool * @return the builder */ public Builder addTool(Tool tool) { if (tools == null) { tools = new ArrayList<>(); } tools.add(tool); return this; } /** * Sets the topK. * * @param topK the topK * @return the builder */ public Builder topK(Integer topK) { this.topK = topK; return this; } /** * Sets the topP. * * @param topP the topP * @return the builder */ public Builder topP(Float topP) { this.topP = topP; return this; } /** * Returns the {@code AnthropicInput} instance. * * @return the {@code AnthropicInput} instance */ public AnthropicInput build() { return new AnthropicInput(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/AnthropicOutput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; import java.util.List; /** The Anthropic style output. */ public class AnthropicOutput { private String id; private String type; private String role; private List<Content> content; private String model; @SerializedName("stop_reason") private String stopReason; @SerializedName("stop_sequence") private String stopSequence; private Usage usage; private Container container; AnthropicOutput(Builder builder) { this.id = builder.id; this.type = builder.type; this.role = builder.role; this.content = builder.content; this.model = builder.model; this.stopReason = builder.stopReason; this.stopSequence = builder.stopSequence; this.usage = builder.usage; this.container = builder.container; } /** * Returns the model. * * @return the model */ public String getId() { return id; } /** * Returns the model. * * @return the model */ public String getType() { return type; } /** * Returns the model. * * @return the model */ public String getRole() { return role; } /** * Returns the model. * * @return the model */ public List<Content> getContent() { return content; } /** * Returns the model. * * @return the model */ public String getModel() { return model; } /** * Returns the stopReason. * * @return the stopReason */ public String getStopReason() { return stopReason; } /** * Returns the stopSequence. * * @return the stopSequence */ public String getStopSequence() { return stopSequence; } /** * Returns the usage. * * @return the usage */ public Usage getUsage() { return usage; } /** * Returns the container. * * @return the container */ public Container getContainer() { return container; } /** * Creates a builder to build a {@code AnthropicOutput}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code AnthropicOutput}. */ public static final class Builder { String id; String type; String role; List<Content> content; String model; String stopReason; String stopSequence; Usage usage; Container container; /** * Sets the id. * * @param id the id * @return the builder */ public Builder id(String id) { this.id = id; return this; } /** * Sets the type. * * @param type the type * @return the builder */ public Builder type(String type) { this.type = type; return this; } /** * Sets the role. * * @param role the role * @return the builder */ public Builder role(String role) { this.role = role; return this; } /** * Sets the content. * * @param content the content * @return the builder */ public Builder content(List<Content> content) { this.content = content; return this; } /** * Sets the model. * * @param model the model * @return the builder */ public Builder model(String model) { this.model = model; return this; } /** * Sets the stopReason. * * @param stopReason the stopReason * @return the builder */ public Builder stopReason(String stopReason) { this.stopReason = stopReason; return this; } /** * Sets the stopSequence. * * @param stopSequence the stopSequence * @return the builder */ public Builder stopSequence(String stopSequence) { this.stopSequence = stopSequence; return this; } /** * Sets the usage. * * @param usage the usage * @return the builder */ public Builder usage(Usage usage) { this.usage = usage; return this; } /** * Sets the container. * * @param container the container * @return the builder */ public Builder container(Container container) { this.container = container; return this; } /** * Returns the {@code AnthropicOutput} instance. * * @return the {@code AnthropicOutput} instance */ public AnthropicOutput build() { return new AnthropicOutput(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/CacheControl.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class CacheControl { private String type; private String ttl; CacheControl(Builder builder) { this.type = builder.type; this.ttl = builder.ttl; } public String getType() { return type; } public String getTtl() { return ttl; } /** * Creates a builder to build a {@code CacheControl}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code CacheControl}. */ public static final class Builder { String type; String ttl; public Builder type(String type) { this.type = type; return this; } public Builder ttl(String ttl) { this.ttl = ttl; return this; } public CacheControl build() { return new CacheControl(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/CacheCreation.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class CacheCreation { @SerializedName("ephemeral_1h_input_tokens") private int ephemeral1hInputTokens; @SerializedName("ephemeral_5m_input_tokens") private int ephemeral5mInputTokens; CacheCreation(Builder builder) { this.ephemeral1hInputTokens = builder.ephemeral1hInputTokens; this.ephemeral5mInputTokens = builder.ephemeral5mInputTokens; } public int getEphemeral1hInputTokens() { return ephemeral1hInputTokens; } public int getEphemeral5mInputTokens() { return ephemeral5mInputTokens; } /** * Creates a builder to build a {@code CacheCreation}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code CacheCreation}. */ public static final class Builder { int ephemeral1hInputTokens; int ephemeral5mInputTokens; public Builder ephemeral1hInputTokens(int ephemeral1hInputTokens) { this.ephemeral1hInputTokens = ephemeral1hInputTokens; return this; } public Builder ephemeral5mInputTokens(int ephemeral5mInputTokens) { this.ephemeral5mInputTokens = ephemeral5mInputTokens; return this; } public CacheCreation build() { return new CacheCreation(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Container.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Container { @SerializedName("expires_at") private String expiresAt; private String id; Container(Builder builder) { this.expiresAt = builder.expiresAt; this.id = builder.id; } public String getExpiresAt() { return expiresAt; } public String getId() { return id; } /** * Creates a builder to build a {@code Container}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Container}. */ public static final class Builder { String expiresAt; String id; public Builder expiresAt(String expiresAt) { this.expiresAt = expiresAt; return this; } public Builder id(String id) { this.id = id; return this; } public Container build() { return new Container(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Content.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; import java.util.Base64; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Content { private String type; private String text; private Source source; private String signature; private String thinking; private String id; private String name; private Object input; @SerializedName("tool_use_id") private String toolUseId; private WebSearchContent content; private Integer index; Content(Builder builder) { this.type = builder.type; this.text = builder.text; this.source = builder.source; this.signature = builder.signature; this.thinking = builder.thinking; this.id = builder.id; this.name = builder.name; this.input = builder.input; this.toolUseId = builder.toolUseId; this.content = builder.content; this.index = builder.index; } public String getType() { return type; } public String getText() { return text; } public Source getSource() { return source; } public String getSignature() { return signature; } public String getThinking() { return thinking; } public String getId() { return id; } public String getName() { return name; } public Object getInput() { return input; } public String getToolUseId() { return toolUseId; } public WebSearchContent getContent() { return content; } public Integer getIndex() { return index; } /** * Creates a builder to build a {@code Content}. * * @return a new builder */ public static Builder builder() { return new Builder(); } public static Builder text(String text) { return builder().type("text").text(text); } public static Builder image(String imageUrl) { Source.Builder sb = Source.builder().type("url").url(imageUrl); return builder().type("image").source(sb.build()); } public static Builder image(byte[] image, String mimeType) { String data = Base64.getEncoder().encodeToString(image); Source.Builder sb = Source.builder().type("base64").mediaType(mimeType).data(data); return builder().type("image").source(sb.build()); } /** The builder for {@code Content}. */ public static final class Builder { String type; String text; Source source; String signature; String thinking; String id; String name; Object input; String toolUseId; WebSearchContent content; Integer index; public Builder type(String type) { this.type = type; return this; } public Builder text(String text) { this.text = text; return this; } public Builder source(Source source) { this.source = source; return this; } public Builder source(Source.Builder source) { return source(source.build()); } public Builder signature(String signature) { this.signature = signature; return this; } public Builder thinking(String thinking) { this.thinking = thinking; return this; } public Builder id(String id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder input(Object input) { this.input = input; return this; } public Builder toolUseId(String toolUseId) { this.toolUseId = toolUseId; return this; } public Builder content(WebSearchContent content) { this.content = content; return this; } public Builder index(Integer index) { this.index = index; return this; } public Content build() { return new Content(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/ContentBlockDelta.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class ContentBlockDelta { private String type; private String text; public ContentBlockDelta(String type, String text) { this.type = type; this.text = text; } public String getType() { return type; } public String getText() { return text; } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/McpServer.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class McpServer { private String type; private String name; private String url; @SerializedName("authorization_token") private String authorizationToken; @SerializedName("tool_configuration") private ToolConfiguration toolConfiguration; McpServer(Builder builder) { this.type = builder.type; this.name = builder.name; this.url = builder.url; this.authorizationToken = builder.authorizationToken; this.toolConfiguration = builder.toolConfiguration; } public String getType() { return type; } public String getName() { return name; } public String getUrl() { return url; } public String getAuthorizationToken() { return authorizationToken; } public ToolConfiguration getToolConfiguration() { return toolConfiguration; } /** * Creates a builder to build a {@code McpServer}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code McpServer}. */ public static final class Builder { String type; String name; String url; String authorizationToken; ToolConfiguration toolConfiguration; public Builder type(String type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder url(String url) { this.url = url; return this; } public Builder authorizationToken(String authorizationToken) { this.authorizationToken = authorizationToken; return this; } public Builder toolConfiguration(ToolConfiguration toolConfiguration) { this.toolConfiguration = toolConfiguration; return this; } public McpServer build() { return new McpServer(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Message.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import java.util.ArrayList; import java.util.List; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Message { private String role; private List<Content> content; Message(Builder builder) { this.role = builder.role; this.content = builder.content; } public String getRole() { return role; } public List<Content> getContent() { return content; } /** * Creates a builder to build a {@code Message}. * * @return a new builder */ public static Builder builder() { return new Builder(); } public static Builder text(String text) { return builder().addContent(Content.text(text)); } public static Builder image(byte[] image, String mimeType) { return builder().addContent(Content.image(image, mimeType)); } public static Builder image(String imageUrl) { return builder().addContent(Content.image(imageUrl)); } /** The builder for {@code Message}. */ public static final class Builder { String role = "user"; List<Content> content; public Builder role(String role) { this.role = role; return this; } public Builder content(List<Content> content) { this.content = content; return this; } public Builder addContent(Content.Builder content) { return addContent(content.build()); } public Builder addContent(Content content) { if (this.content == null) { this.content = new ArrayList<>(); } this.content.add(content); return this; } public Builder text(String text) { return addContent(Content.text(text)); } public Builder image(String imageUrl) { return addContent(Content.image(imageUrl)); } public Builder image(byte[] image, String mimeType) { return addContent(Content.image(image, mimeType)); } public Message build() { return new Message(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/MessageStart.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class MessageStart { private String id; private String model; @SerializedName("stop_reason") private String stopReason; @SerializedName("stop_sequence") private String stopSequence; private Usage usage; public MessageStart( String id, String model, String stopReason, String stopSequence, Usage usage) { this.id = id; this.model = model; this.stopReason = stopReason; this.stopSequence = stopSequence; this.usage = usage; } public String getId() { return id; } public String getModel() { return model; } public String getStopReason() { return stopReason; } public String getStopSequence() { return stopSequence; } public Usage getUsage() { return usage; } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Metadata.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Metadata { @SerializedName("user_id") private String userId; Metadata(Builder builder) { this.userId = builder.userId; } public String getUserId() { return userId; } /** * Creates a builder to build a {@code Metadata}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Metadata}. */ public static final class Builder { String userId; public Builder userId(String userId) { this.userId = userId; return this; } public Metadata build() { return new Metadata(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/ServerToolUse.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class ServerToolUse { @SerializedName("web_search_requests") private int webSearchRequests; ServerToolUse(Builder builder) { this.webSearchRequests = builder.webSearchRequests; } public int getWebSearchRequests() { return webSearchRequests; } /** * Creates a builder to build a {@code ServerToolUse}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code ServerToolUse}. */ public static final class Builder { int webSearchRequests; public Builder webSearchRequests(int webSearchRequests) { this.webSearchRequests = webSearchRequests; return this; } public ServerToolUse build() { return new ServerToolUse(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Source.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Source { private String type; @SerializedName("media_type") private String mediaType; private String data; private String url; Source(Builder builder) { this.type = builder.type; this.mediaType = builder.mediaType; this.data = builder.data; this.url = builder.url; } public String getType() { return type; } public String getMediaType() { return mediaType; } public String getData() { return data; } public String getUrl() { return url; } /** * Creates a builder to build a {@code Source}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Source}. */ public static final class Builder { String type; String mediaType; String data; String url; public Builder type(String type) { this.type = type; return this; } public Builder mediaType(String mediaType) { this.mediaType = mediaType; return this; } public Builder data(String data) { this.data = data; return this; } public Builder url(String url) { this.url = url; return this; } public Source build() { return new Source(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/StreamAnthropicOutput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import ai.djl.util.JsonUtils; import com.google.gson.JsonObject; import java.util.Collections; import java.util.Iterator; /** A stream version of {@link AnthropicOutput}. */ public class StreamAnthropicOutput implements Iterable<AnthropicOutput> { private transient Iterator<String> output; StreamAnthropicOutput(Iterator<String> output) { this.output = output; } /** {@inheritDoc} */ @Override public Iterator<AnthropicOutput> iterator() { return new Iterator<AnthropicOutput>() { /** {@inheritDoc} */ @Override public boolean hasNext() { return output.hasNext(); } /** {@inheritDoc} */ @Override public AnthropicOutput next() { AnthropicOutput.Builder builder = AnthropicOutput.builder(); StreamAnthropicOutput.next(builder, output.next(), output); return builder.build(); } }; } static void next(AnthropicOutput.Builder builder, String json, Iterator<String> output) { if (json.isEmpty()) { next(builder, output.next(), output); return; } JsonObject element = JsonUtils.GSON.fromJson(json, JsonObject.class); next(builder, element, output); } /** * Processes streaming output. * * @param builder the builder * @param element the json stream chunk * @param output the iterator */ public static void next( AnthropicOutput.Builder builder, JsonObject element, Iterator<String> output) { String type = element.get("type").getAsString(); if ("ping".equals(type) || "content_block_start".equals(type) || "content_block_stop".equals(type)) { next(builder, output.next(), output); } else if ("message_start".equals(type)) { MessageStart message = JsonUtils.GSON.fromJson(element.get("message"), MessageStart.class); builder.id(message.getId()) .model(message.getModel()) .usage(message.getUsage()) .stopReason(message.getStopReason()) .stopSequence(message.getStopSequence()); next(builder, output.next(), output); } else if ("content_block_delta".equals(type)) { int index = element.get("index").getAsInt(); ContentBlockDelta delta = JsonUtils.GSON.fromJson(element.get("delta"), ContentBlockDelta.class); builder.content( Collections.singletonList(Content.text(delta.getText()).index(index).build())); } else if ("message_delta".equals(type)) { MessageStart message = JsonUtils.GSON.fromJson(element.get("delta"), MessageStart.class); builder.usage(message.getUsage()) .stopReason(message.getStopReason()) .stopSequence(message.getStopSequence()); next(builder, output.next(), output); } else if ("message_stop".equals(type)) { builder.content(Collections.singletonList(Content.text("").build())); } else { throw new IllegalArgumentException("Unexpected event: " + type); } } /** * Customizes schema deserialization. * * @param output the output iterator * @return the deserialized {@code StreamAnthropicOutput} instance */ public static StreamAnthropicOutput fromJson(Iterator<String> output) { return new StreamAnthropicOutput(output); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Thinking.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Thinking { private String type; @SerializedName("budget_tokens") private int budgetTokens; Thinking(Builder builder) { this.type = builder.type; this.budgetTokens = builder.budgetTokens; } public String getType() { return type; } public int getBudgetTokens() { return budgetTokens; } /** * Creates a builder to build a {@code Thinking}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Thinking}. */ public static final class Builder { String type; int budgetTokens; public Builder type(String type) { this.type = type; return this; } public Builder budgetTokens(int budgetTokens) { this.budgetTokens = budgetTokens; return this; } public Thinking build() { return new Thinking(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Tool.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Tool { private String type; private String name; private String description; @SerializedName("input_schema") private Object inputSchema; @SerializedName("cache_control") private CacheControl cacheControl; Tool(Builder builder) { this.type = builder.type; this.name = builder.name; this.description = builder.description; this.inputSchema = builder.inputSchema; this.cacheControl = builder.cacheControl; } public String getType() { return type; } public String getName() { return name; } public String getDescription() { return description; } public Object getInputSchema() { return inputSchema; } public CacheControl getCacheControl() { return cacheControl; } /** * Creates a builder to build a {@code Tool}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Tool}. */ public static final class Builder { String type; String name; String description; Object inputSchema; CacheControl cacheControl; public Builder type(String type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder description(String description) { this.description = description; return this; } public Builder inputSchema(Object inputSchema) { this.inputSchema = inputSchema; return this; } public Builder cacheControl(CacheControl cacheControl) { this.cacheControl = cacheControl; return this; } public Tool build() { return new Tool(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/ToolChoice.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class ToolChoice { private String type; private String name; @SerializedName("disable_parallel_tool_use") private boolean disableParallelToolUse; ToolChoice(Builder builder) { this.type = builder.type; this.name = builder.name; this.disableParallelToolUse = builder.disableParallelToolUse; } public String getType() { return type; } public String getName() { return name; } public boolean isDisableParallelToolUse() { return disableParallelToolUse; } /** * Creates a builder to build a {@code ToolChoice}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code ToolChoice}. */ public static final class Builder { String type; String name; boolean disableParallelToolUse; public Builder type(String type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder disableParallelToolUse(boolean disableParallelToolUse) { this.disableParallelToolUse = disableParallelToolUse; return this; } public ToolChoice build() { return new ToolChoice(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/ToolConfiguration.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; import java.util.List; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class ToolConfiguration { @SerializedName("allowed_tools") private List<String> allowedTools; private Boolean enabled; ToolConfiguration(Builder builder) { this.allowedTools = builder.allowedTools; this.enabled = builder.enabled; } public List<String> getAllowedTools() { return allowedTools; } public Boolean getEnabled() { return enabled; } /** * Creates a builder to build a {@code ToolConfiguration}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code ToolConfiguration}. */ public static final class Builder { List<String> allowedTools; Boolean enabled; public Builder allowedTools(List<String> allowedTools) { this.allowedTools = allowedTools; return this; } public Builder enabled(Boolean enabled) { this.enabled = enabled; return this; } public ToolConfiguration build() { return new ToolConfiguration(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/Usage.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class Usage { @SerializedName("cache_creation") private CacheCreation cacheCreation; @SerializedName("cache_creation_input_tokens") private int cacheCreationInputTokens; @SerializedName("cache_read_input_tokens") private int cacheReadInputTokens; @SerializedName("input_tokens") private int inputTokens; @SerializedName("output_tokens") private int outputTokens; @SerializedName("server_tool_use") private ServerToolUse serverToolUse; @SerializedName("service_tier") private String serviceTier; Usage(Builder builder) { this.cacheCreation = builder.cacheCreation; this.cacheCreationInputTokens = builder.cacheCreationInputTokens; this.cacheReadInputTokens = builder.cacheReadInputTokens; this.inputTokens = builder.inputTokens; this.outputTokens = builder.outputTokens; this.serverToolUse = builder.serverToolUse; this.serviceTier = builder.serviceTier; } public CacheCreation getCacheCreation() { return cacheCreation; } public int getCacheCreationInputTokens() { return cacheCreationInputTokens; } public int getCacheReadInputTokens() { return cacheReadInputTokens; } public int getInputTokens() { return inputTokens; } public int getOutputTokens() { return outputTokens; } public ServerToolUse getServerToolUse() { return serverToolUse; } public String getServiceTier() { return serviceTier; } /** * Creates a builder to build a {@code Usage}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code Usage}. */ public static final class Builder { CacheCreation cacheCreation; int cacheCreationInputTokens; int cacheReadInputTokens; int inputTokens; int outputTokens; ServerToolUse serverToolUse; String serviceTier; public Builder cacheCreation(CacheCreation cacheCreation) { this.cacheCreation = cacheCreation; return this; } public Builder cacheCreationInputTokens(int cacheCreationInputTokens) { this.cacheCreationInputTokens = cacheCreationInputTokens; return this; } public Builder cacheReadInputTokens(int cacheReadInputTokens) { this.cacheReadInputTokens = cacheReadInputTokens; return this; } public Builder inputTokens(int inputTokens) { this.inputTokens = inputTokens; return this; } public Builder outputTokens(int outputTokens) { this.outputTokens = outputTokens; return this; } public Builder serverToolUse(ServerToolUse serverToolUse) { this.serverToolUse = serverToolUse; return this; } public Builder serviceTier(String serviceTier) { this.serviceTier = serviceTier; return this; } public Usage build() { return new Usage(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/WebSearchContent.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.anthropic; import com.google.gson.annotations.SerializedName; /** A data class represents Anthropic schema. */ @SuppressWarnings("MissingJavadocMethod") public class WebSearchContent { @SerializedName("error_code") private String errorCode; private String type; WebSearchContent(Builder builder) { this.errorCode = builder.errorCode; this.type = builder.type; } public String getErrorCode() { return errorCode; } public String getType() { return type; } /** * Creates a builder to build a {@code WebSearchContent}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The builder for {@code WebSearchContent}. */ public static final class Builder { String errorCode; String type; public Builder errorCode(String errorCode) { this.errorCode = errorCode; return this; } public Builder type(String type) { this.type = type; return this; } public WebSearchContent build() { return new WebSearchContent(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/anthropic/package-info.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains classes for Anthropic. */ package ai.djl.genai.anthropic;
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/Gemini.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini; import ai.djl.util.Utils; /** Utility class to hold the Gemini models url. */ public final class Gemini { public static final Gemini GEMINI_2_5_PRO = new Gemini("gemini-2.5-pro"); public static final Gemini GEMINI_2_5_FLASH = new Gemini("gemini-2.5-flash"); public static final Gemini GEMINI_2_0_FLASH = new Gemini("gemini-2.0-flash"); public static final Gemini GEMINI_2_0_FLASH_LITE = new Gemini("gemini-2.0-flash-lite"); private String model; Gemini(String model) { this.model = model; } /** * Returns the model name. * * @return the model name. */ public String name() { return model; } /** * Returns the chatcompletions compatible endpoint URL. * * @return the chatcompletions compatible endpoint URL */ public String getChatCompletionsUrl() { return getUrl(false, true, false, null, null, null, null); } /** * Returns the chatcompletions compatible endpoint URL with override base URL. * * @return the chatcompletions compatible endpoint URL with override base URL */ public String getChatCompletionsUrl(String baseUrl) { return getUrl(false, true, false, null, null, null, baseUrl); } /** * Returns the model's endpoint URL. * * @return the model's endpoint URL */ public String getUrl() { return getUrl(null); } /** * Returns the model's streaming endpoint URL. * * @return the model's streaming endpoint URL */ public String getUrl(boolean stream) { return getUrl(stream, false); } /** * Returns the model's streaming endpoint URL on Vertex. * * @return the model's streaming endpoint URL on Vertex */ public String getUrl(boolean stream, boolean useVertex) { return getUrl(stream, false, useVertex, null, null, null, null); } /** * Returns the endpoint URL with override base URL. * * @return the endpoint URL with override base URL */ public String getUrl(String baseUrl) { return getUrl(false, false, false, null, null, null, baseUrl); } /** * Returns the endpoint URL with override base URL. * * @return the endpoint URL with override base URL */ public String getUrl(String baseUrl, boolean stream) { return getUrl(stream, false, true, null, null, null, baseUrl); } /** * Returns the model's endpoint URL with specified project and location. * * @return the model's endpoint URL with specified project and location */ public String getUrl(boolean stream, String project, String location) { return getUrl(stream, project, location, null); } /** * Returns the vertex model's endpoint URL with specified project, location and api version. * * @return the vertex model's endpoint URL with specified project, location and api version */ public String getUrl(boolean stream, String project, String location, String apiVersion) { return getUrl(stream, false, true, project, location, apiVersion, null); } String getUrl( boolean stream, boolean chatCompletions, boolean useVertex, String project, String location, String apiVersion, String baseUrl) { if (location == null) { location = Utils.getEnvOrSystemProperty("REGION", "global"); } if (project == null) { project = Utils.getEnvOrSystemProperty("PROJECT"); } if (baseUrl == null) { if (useVertex && !"global".equals(location)) { baseUrl = "https://" + location + "-generativelanguage.googleapis.com"; } else { baseUrl = "https://generativelanguage.googleapis.com"; } } StringBuilder sb = new StringBuilder(baseUrl); sb.append('/'); if (chatCompletions) { if (apiVersion == null) { apiVersion = "v1beta"; } sb.append(apiVersion).append("/openai/chat/completions"); return sb.toString(); } else if (useVertex) { if (project == null) { throw new IllegalArgumentException("project is required."); } if (apiVersion == null) { apiVersion = "v1"; } sb.append(apiVersion) .append("/projects/") .append(project) .append("/locations/") .append(location) .append("/publishers/google/models/") .append(model) .append(':'); } else { if (apiVersion == null) { apiVersion = "v1beta"; } sb.append(apiVersion).append("/models/").append(model).append(':'); } if (stream) { sb.append("streamGenerateContent?alt=sse"); } else { sb.append("generateContent"); } return sb.toString(); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/GeminiInput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini; import ai.djl.genai.gemini.types.Blob; import ai.djl.genai.gemini.types.Content; import ai.djl.genai.gemini.types.FileData; import ai.djl.genai.gemini.types.GenerationConfig; import ai.djl.genai.gemini.types.Part; import ai.djl.genai.gemini.types.SafetySetting; import ai.djl.genai.gemini.types.Tool; import ai.djl.genai.gemini.types.ToolConfig; import java.util.ArrayList; import java.util.List; /** A class presents the Gemini input. */ public class GeminiInput { private List<Content> contents; private GenerationConfig generationConfig; private Content systemInstruction; private List<SafetySetting> safetySettings; private List<Tool> tools; private ToolConfig toolConfig; private String cachedContent; GeminiInput(Builder builder) { this.contents = builder.contents; this.generationConfig = builder.generationConfig; this.systemInstruction = builder.systemInstruction; this.safetySettings = builder.safetySettings; this.tools = builder.tools; this.toolConfig = builder.toolConfig; this.cachedContent = builder.cachedContent; } /** * Returns the contents. * * @return the contents */ public List<Content> getContents() { return contents; } /** * Returns the generation config. * * @return the generation config */ public GenerationConfig getGenerationConfig() { return generationConfig; } /** * Returns the system instruction. * * @return the system instruction */ public Content getSystemInstruction() { return systemInstruction; } /** * Returns the safety settings. * * @return the safety settings */ public List<SafetySetting> getSafetySettings() { return safetySettings; } /** * Returns the tools. * * @return the tools */ public List<Tool> getTools() { return tools; } /** * Returns the toolConfig. * * @return the toolConfig */ public ToolConfig getToolConfig() { return toolConfig; } /** * Returns the cachedContent. * * @return the cachedContent */ public String getCachedContent() { return cachedContent; } /** * Creates a builder to build a {@code GeminiInput}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder with text content. * * @param text the text content * @return a new builder */ public static Builder text(String text) { return text(text, null); } /** * Creates a builder with text content and configuration. * * @param text the text content * @param config the generation config * @return a new builder */ public static Builder text(String text, GenerationConfig config) { return builder().addText(text).generationConfig(config); } /** * Creates a builder with the file uri content. * * @param text the file uri * @param mimeType the mime type * @return a new builder */ public static Builder fileUri(String text, String mimeType) { return builder().addUri(text, mimeType); } /** * Creates a builder with the inline data content. * * @param bytes the bytes of the inline data * @param mimeType the mime type * @return a new builder */ public static Builder bytes(byte[] bytes, String mimeType) { return builder().addBytes(bytes, mimeType); } /** The builder for {@code GeminiInput}. */ public static final class Builder { List<Content> contents = new ArrayList<>(); GenerationConfig generationConfig; Content systemInstruction; List<SafetySetting> safetySettings; List<Tool> tools; ToolConfig toolConfig; String cachedContent; /** * Sets the contents. * * @param contents the contents * @return the builder */ public Builder contents(List<Content> contents) { this.contents.clear(); this.contents.addAll(contents); return this; } /** * Adds the content. * * @param content the content * @return the builder */ public Builder addContent(Content content) { contents.add(content); return this; } /** * Adds the content. * * @param content the content builder * @return the builder */ public Builder addContent(Content.Builder content) { return addContent(content.build()); } /** * Adds the text content. * * @param text the text * @return the builder */ public Builder addText(String text) { return addText(text, "user"); } /** * Sets the text content with the role. * * @param text the text * @param role the role * @return the builder */ public Builder addText(String text, String role) { return addContent(Content.text(text).role(role)); } /** * Sets the model. * * @param fileUri the fileUri * @param mimeType the mimeType * @return the builder */ public Builder addUri(String fileUri, String mimeType) { FileData.Builder file = FileData.builder().fileUri(fileUri).mimeType(mimeType); Part.Builder part = Part.builder().fileData(file); return addContent(Content.builder().addPart(part).role("user")); } /** * Sets the inline data. * * @param bytes the bytes * @param mimeType the mimeType * @return the builder */ public Builder addBytes(byte[] bytes, String mimeType) { Blob.Builder file = Blob.builder().data(bytes).mimeType(mimeType); Part.Builder part = Part.builder().inlineData(file); return addContent(Content.builder().addPart(part).role("user")); } /** * Sets the generation config. * * @param generationConfig the generationConfig * @return the builder */ public Builder generationConfig(GenerationConfig generationConfig) { this.generationConfig = generationConfig; if (generationConfig != null) { this.cachedContent = generationConfig.getCachedContent(); this.safetySettings = generationConfig.getSafetySettings(); this.systemInstruction = generationConfig.getSystemInstruction(); this.toolConfig = generationConfig.getToolConfig(); this.tools = generationConfig.getTools(); } return this; } /** * Returns the {@code GeminiInput} instance. * * @return the {@code GeminiInput} instance */ public GeminiInput build() { return new GeminiInput(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/GeminiOutput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini; import ai.djl.genai.gemini.types.Candidate; import ai.djl.genai.gemini.types.FunctionCall; import ai.djl.genai.gemini.types.LogprobsResult; import ai.djl.genai.gemini.types.LogprobsResultCandidate; import ai.djl.genai.gemini.types.LogprobsResultTopCandidates; import ai.djl.genai.gemini.types.Part; import ai.djl.genai.gemini.types.UsageMetadata; import ai.djl.util.PairList; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** A class presents the Gemini input. */ public class GeminiOutput { private List<Candidate> candidates; private UsageMetadata usageMetadata; private String modelVersion; private String createTime; private String responseId; GeminiOutput( List<Candidate> candidates, UsageMetadata usageMetadata, String modelVersion, String createTime, String responseId) { this.candidates = candidates; this.usageMetadata = usageMetadata; this.modelVersion = modelVersion; this.createTime = createTime; this.responseId = responseId; } /** * Returns the candidates. * * @return the candidates */ public List<Candidate> getCandidates() { if (candidates == null) { return Collections.emptyList(); } return candidates; } /** * Returns the first candidate if there is any. * * @return the candidate */ public Candidate getCandidate() { if (candidates == null || candidates.isEmpty()) { return null; } return candidates.get(0); } /** * Returns the per token log probability and the alternative tokens. * * @return the per token log probability and the alternative tokens. */ public PairList<LogprobsResultCandidate, List<LogprobsResultCandidate>> getLogprobsResult() { Candidate candidate = getCandidate(); if (candidate == null) { return null; } LogprobsResult result = candidate.getLogprobsResult(); if (result == null) { return null; } PairList<LogprobsResultCandidate, List<LogprobsResultCandidate>> pairs = new PairList<>(); List<LogprobsResultTopCandidates> top = result.getTopCandidates(); int i = 0; for (LogprobsResultCandidate lr : result.getChosenCandidates()) { List<LogprobsResultCandidate> alternatives = new ArrayList<>(); if (top != null && i < top.size()) { String token = lr.getToken(); for (LogprobsResultCandidate alt : top.get(i).getCandidates()) { if (!alt.getToken().equals(token)) { alternatives.add(alt); } } } pairs.add(lr, alternatives); ++i; } return pairs; } /** * Returns the content parts. * * @return the content parts */ public List<Part> getParts() { Candidate candidate = getCandidate(); if (candidate == null) { return Collections.emptyList(); } List<Part> parts = candidate.getContent().getParts(); if (parts == null) { return Collections.emptyList(); } return parts; } /** * Returns the usage metadata. * * @return the usage metadata */ public UsageMetadata getUsageMetadata() { return usageMetadata; } /** * Returns the model version. * * @return the model version */ public String getModelVersion() { return modelVersion; } /** * Returns the creation time. * * @return the creation time */ public String getCreateTime() { return createTime; } /** * Returns the response id. * * @return the response id */ public String getResponseId() { return responseId; } /** * Returns the aggregated text output. * * @return the aggregated text output */ public String getTextOutput() { StringBuilder sb = new StringBuilder(); for (Part part : getParts()) { if (part.getText() != null) { sb.append(part.getText()); } } return sb.toString(); } /** * Returns the {@link FunctionCall}s in the response. * * @return the {@link FunctionCall}s in the response */ public List<FunctionCall> getFunctionCalls() { List<FunctionCall> list = new ArrayList<>(); for (Part part : getParts()) { FunctionCall call = part.getFunctionCall(); if (call != null) { list.add(call); } } return list; } /** * Returns the first {@link FunctionCall} in the response. * * @return the first {@link FunctionCall} in the response */ public FunctionCall getFunctionCall() { List<FunctionCall> list = getFunctionCalls(); if (list.isEmpty()) { return null; } return list.get(0); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/StreamGeminiOutput.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini; import ai.djl.util.JsonUtils; import java.util.Iterator; /** A stream version of {@link GeminiOutput}. */ public class StreamGeminiOutput implements Iterable<GeminiOutput> { private transient Iterator<String> output; StreamGeminiOutput(Iterator<String> output) { this.output = output; } /** {@inheritDoc} */ @Override public Iterator<GeminiOutput> iterator() { return new Iterator<GeminiOutput>() { /** {@inheritDoc} */ @Override public boolean hasNext() { return output.hasNext(); } /** {@inheritDoc} */ @Override public GeminiOutput next() { String json = output.next(); if (json.isEmpty()) { return new GeminiOutput(null, null, null, null, null); } return JsonUtils.GSON.fromJson(json, GeminiOutput.class); } }; } /** * Customizes schema deserialization. * * @param output the output iterator * @return the deserialized {@code StreamGeminiOutput} instance */ public static StreamGeminiOutput fromJson(Iterator<String> output) { return new StreamGeminiOutput(output); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/package-info.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ /** Contains classes for Gemini. */ package ai.djl.genai.gemini;
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Behavior.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum Behavior { UNSPECIFIED, BLOCKING, NON_BLOCKING, BEHAVIOR_UNSPECIFIED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Blob.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.Base64; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Blob { private String data; private String displayName; private String mimeType; Blob(Builder builder) { data = builder.data; displayName = builder.displayName; mimeType = builder.mimeType; } public String getData() { return data; } public String getDisplayName() { return displayName; } public String getMimeType() { return mimeType; } public static Builder builder() { return new Builder(); } /** Builder class for {@code Blob}. */ public static final class Builder { String data; String displayName; String mimeType; public Builder data(byte[] data) { return data(Base64.getEncoder().encodeToString(data)); } public Builder data(String data) { this.data = data; return this; } public Builder displayName(String displayName) { this.displayName = displayName; return this; } public Builder mimeType(String mimeType) { this.mimeType = mimeType; return this; } public Blob build() { return new Blob(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/BlockedReason.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum BlockedReason { BLOCKED_REASON_UNSPECIFIED, SAFETY, OTHER, BLOCKLIST, PROHIBITED_CONTENT, IMAGE_SAFETY }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Candidate.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Candidate { private Double avgLogprobs; private CitationMetadata citationMetadata; private Content content; private String finishMessage; private FinishReason finishReason; private GroundingMetadata groundingMetadata; private Integer index; private LogprobsResult logprobsResult; private List<SafetyRating> safetyRatings; private Integer tokenCount; private UrlContextMetadata urlContextMetadata; Candidate(Builder builder) { avgLogprobs = builder.avgLogprobs; citationMetadata = builder.citationMetadata; content = builder.content; finishMessage = builder.finishMessage; finishReason = builder.finishReason; groundingMetadata = builder.groundingMetadata; index = builder.index; logprobsResult = builder.logprobsResult; safetyRatings = builder.safetyRatings; tokenCount = builder.tokenCount; urlContextMetadata = builder.urlContextMetadata; } public Double getAvgLogprobs() { return avgLogprobs; } public CitationMetadata getCitationMetadata() { return citationMetadata; } public Content getContent() { return content; } public String getFinishMessage() { return finishMessage; } public FinishReason getFinishReason() { return finishReason; } public GroundingMetadata getGroundingMetadata() { return groundingMetadata; } public Integer getIndex() { return index; } public LogprobsResult getLogprobsResult() { return logprobsResult; } public List<SafetyRating> getSafetyRatings() { return safetyRatings; } public Integer getTokenCount() { return tokenCount; } public UrlContextMetadata getUrlContextMetadata() { return urlContextMetadata; } public static Builder builder() { return new Builder(); } /** Builder class for {@code Candidate}. */ public static final class Builder { Double avgLogprobs; CitationMetadata citationMetadata; Content content; String finishMessage; FinishReason finishReason; GroundingMetadata groundingMetadata; Integer index; LogprobsResult logprobsResult; List<SafetyRating> safetyRatings = new ArrayList<>(); Integer tokenCount; UrlContextMetadata urlContextMetadata; public Builder avgLogprobs(Double avgLogprobs) { this.avgLogprobs = avgLogprobs; return this; } public Builder citationMetadata(CitationMetadata citationMetadata) { this.citationMetadata = citationMetadata; return this; } public Builder citationMetadata(CitationMetadata.Builder citationMetadata) { this.citationMetadata = citationMetadata.build(); return this; } public Builder content(Content content) { this.content = content; return this; } public Builder content(Content.Builder content) { this.content = content.build(); return this; } public Builder finishMessage(String finishMessage) { this.finishMessage = finishMessage; return this; } public Builder finishReason(FinishReason finishReason) { this.finishReason = finishReason; return this; } public Builder groundingMetadata(GroundingMetadata groundingMetadata) { this.groundingMetadata = groundingMetadata; return this; } public Builder groundingMetadata(GroundingMetadata.Builder groundingMetadata) { this.groundingMetadata = groundingMetadata.build(); return this; } public Builder index(Integer index) { this.index = index; return this; } public Builder logprobsResult(LogprobsResult logprobsResult) { this.logprobsResult = logprobsResult; return this; } public Builder logprobsResult(LogprobsResult.Builder logprobsResult) { this.logprobsResult = logprobsResult.build(); return this; } public Builder safetyRatings(List<SafetyRating> safetyRatings) { this.safetyRatings.clear(); this.safetyRatings.addAll(safetyRatings); return this; } public Builder addSafetyRating(SafetyRating safetyRating) { this.safetyRatings.add(safetyRating); return this; } public Builder addSafetyRating(SafetyRating.Builder safetyRating) { this.safetyRatings.add(safetyRating.build()); return this; } public Builder tokenCount(Integer tokenCount) { this.tokenCount = tokenCount; return this; } public Builder urlContextMetadata(UrlContextMetadata urlContextMetadata) { this.urlContextMetadata = urlContextMetadata; return this; } public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadata) { this.urlContextMetadata = urlContextMetadata.build(); return this; } public Candidate build() { return new Candidate(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Citation.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Citation { private Integer endIndex; private String license; private GoogleTypeDate publicationDate; private Integer startIndex; private String title; private String uri; Citation(Builder builder) { endIndex = builder.endIndex; license = builder.license; publicationDate = builder.publicationDate; startIndex = builder.startIndex; title = builder.title; uri = builder.uri; } public Integer getEndIndex() { return endIndex; } public String getLicense() { return license; } public GoogleTypeDate getPublicationDate() { return publicationDate; } public Integer getStartIndex() { return startIndex; } public String getTitle() { return title; } public String getUri() { return uri; } public static Builder builder() { return new Builder(); } /** Builder class for {@code Citation}. */ public static final class Builder { Integer endIndex; String license; GoogleTypeDate publicationDate; Integer startIndex; String title; String uri; public Builder endIndex(Integer endIndex) { this.endIndex = endIndex; return this; } public Builder license(String license) { this.license = license; return this; } public Builder publicationDate(GoogleTypeDate publicationDate) { this.publicationDate = publicationDate; return this; } public Builder publicationDate(GoogleTypeDate.Builder publicationDate) { this.publicationDate = publicationDate.build(); return this; } public Builder startIndex(Integer startIndex) { this.startIndex = startIndex; return this; } public Builder title(String title) { this.title = title; return this; } public Builder uri(String uri) { this.uri = uri; return this; } public Citation build() { return new Citation(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/CitationMetadata.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class CitationMetadata { private List<Citation> citations; CitationMetadata(Builder builder) { citations = builder.citations; } public List<Citation> getCitations() { return citations; } public static Builder builder() { return new Builder(); } /** Builder class for {@code CitationMetadata}. */ public static final class Builder { List<Citation> citations = new ArrayList<>(); public Builder citations(List<Citation> citations) { this.citations.clear(); this.citations.addAll(citations); return this; } public Builder addCitation(Citation citation) { this.citations.add(citation); return this; } public Builder addCitation(Citation.Builder citation) { this.citations.add(citation.build()); return this; } public CitationMetadata build() { return new CitationMetadata(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/CodeExecutionResult.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class CodeExecutionResult { private Outcome outcome; private String output; CodeExecutionResult(Builder builder) { outcome = builder.outcome; output = builder.output; } public Outcome getOutcome() { return outcome; } public String getOutput() { return output; } public static Builder builder() { return new Builder(); } /** Builder class for {@code CodeExecutionResult}. */ public static final class Builder { Outcome outcome; String output; public Builder outcome(Outcome outcome) { this.outcome = outcome; return this; } public Builder output(String output) { this.output = output; return this; } public CodeExecutionResult build() { return new CodeExecutionResult(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Content.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Content { private List<Part> parts; private String role; Content(Builder builder) { parts = builder.parts; role = builder.role; } public List<Part> getParts() { return parts; } public String getRole() { return role; } public static Builder builder() { return new Builder(); } public static Builder text(String text) { return builder().addPart(Part.text(text)).role("user"); } public static Builder fileData(String fileUri, String mimeType) { return builder().addPart(Part.fileData(fileUri, mimeType)).role("user"); } public static Builder inlineData(byte[] bytes, String mimeType) { return builder().addPart(Part.inlineData(bytes, mimeType)).role("user"); } /** Builder class for {@code Content}. */ public static final class Builder { List<Part> parts = new ArrayList<>(); String role; public Builder parts(List<Part> parts) { this.parts.clear(); this.parts.addAll(parts); return this; } public Builder addPart(Part part) { this.parts.add(part); return this; } public Builder addPart(Part.Builder part) { this.parts.add(part.build()); return this; } public Builder role(String role) { this.role = role; return this; } public Content build() { return new Content(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/DynamicRetrievalConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class DynamicRetrievalConfig { private Float dynamicThreshold; private DynamicRetrievalConfigMode mode; DynamicRetrievalConfig(Builder builder) { dynamicThreshold = builder.dynamicThreshold; mode = builder.mode; } public Float getDynamicThreshold() { return dynamicThreshold; } public DynamicRetrievalConfigMode getMode() { return mode; } public static Builder builder() { return new Builder(); } /** Builder class for {@code DynamicRetrievalConfig}. */ public static final class Builder { Float dynamicThreshold; DynamicRetrievalConfigMode mode; public Builder dynamicThreshold(Float dynamicThreshold) { this.dynamicThreshold = dynamicThreshold; return this; } public Builder mode(DynamicRetrievalConfigMode mode) { this.mode = mode; return this; } public DynamicRetrievalConfig build() { return new DynamicRetrievalConfig(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/DynamicRetrievalConfigMode.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum DynamicRetrievalConfigMode { MODE_UNSPECIFIED, MODE_DYNAMIC, DYNAMIC_RETRIEVAL_CONFIG_MODE_UNSPECIFIED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/ExecutableCode.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class ExecutableCode { private String code; private Language language; ExecutableCode(Builder builder) { code = builder.code; language = builder.language; } public String getCode() { return code; } public Language getLanguage() { return language; } public static Builder builder() { return new Builder(); } /** Builder class for {@code ExecutableCode}. */ public static final class Builder { String code; Language language; public Builder code(String code) { this.code = code; return this; } public Builder language(Language language) { this.language = language; return this; } public ExecutableCode build() { return new ExecutableCode(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FeatureSelectionPreference.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum FeatureSelectionPreference { FEATURE_SELECTION_PREFERENCE_UNSPECIFIED, PRIORITIZE_QUALITY, BALANCED, PRIORITIZE_COST }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FileData.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class FileData { private String displayName; private String fileUri; private String mimeType; FileData(Builder builder) { displayName = builder.displayName; fileUri = builder.fileUri; mimeType = builder.mimeType; } public String getDisplayName() { return displayName; } public String getFileUri() { return fileUri; } public String getMimeType() { return mimeType; } public static Builder builder() { return new Builder(); } /** Builder class for {@code FileData}. */ public static final class Builder { String displayName; String fileUri; String mimeType; public Builder displayName(String displayName) { this.displayName = displayName; return this; } public Builder fileUri(String fileUri) { this.fileUri = fileUri; return this; } public Builder mimeType(String mimeType) { this.mimeType = mimeType; return this; } public FileData build() { return new FileData(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FinishReason.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum FinishReason { FINISH_REASON_UNSPECIFIED, STOP, MAX_TOKENS, SAFETY, RECITATION, LANGUAGE, OTHER, BLOCKLIST, PROHIBITED_CONTENT, SPII, MALFORMED_FUNCTION_CALL, IMAGE_SAFETY, UNEXPECTED_TOOL_CALL }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionCall.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.Map; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class FunctionCall { private Map<String, Object> args; private String id; private String name; FunctionCall(Builder builder) { args = builder.args; id = builder.id; name = builder.name; } public Map<String, Object> getArgs() { return args; } public String getId() { return id; } public String getName() { return name; } public static Builder builder() { return new Builder(); } /** Builder class for {@code FunctionCall}. */ public static final class Builder { Map<String, Object> args; String id; String name; public Builder args(Map<String, Object> args) { this.args = args; return this; } public Builder id(String id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public FunctionCall build() { return new FunctionCall(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionCallingConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class FunctionCallingConfig { private List<String> allowedFunctionNames; private FunctionCallingConfigMode mode; FunctionCallingConfig(Builder builder) { allowedFunctionNames = builder.allowedFunctionNames; mode = builder.mode; } public List<String> getAllowedFunctionNames() { return allowedFunctionNames; } public FunctionCallingConfigMode getMode() { return mode; } public static Builder builder() { return new Builder(); } /** Builder class for {@code FunctionCallingConfig}. */ public static final class Builder { List<String> allowedFunctionNames; FunctionCallingConfigMode mode; public Builder allowedFunctionNames(List<String> allowedFunctionNames) { this.allowedFunctionNames = allowedFunctionNames; return this; } public Builder mode(FunctionCallingConfigMode mode) { this.mode = mode; return this; } public FunctionCallingConfig build() { return new FunctionCallingConfig(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionCallingConfigMode.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum FunctionCallingConfigMode { MODE_UNSPECIFIED, AUTO, ANY, NONE, FUNCTION_CALLING_CONFIG_MODE_UNSPECIFIED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionDeclaration.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import ai.djl.genai.FunctionUtils; import ai.djl.util.Pair; import ai.djl.util.PairList; import java.lang.reflect.Method; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class FunctionDeclaration { private Behavior behavior; private String description; private String name; private Schema parameters; private Object parametersJsonSchema; private Schema response; private Object responseJsonSchema; FunctionDeclaration(Builder builder) { behavior = builder.behavior; description = builder.description; name = builder.name; parameters = builder.parameters; parametersJsonSchema = builder.parametersJsonSchema; response = builder.response; responseJsonSchema = builder.responseJsonSchema; } public Behavior getBehavior() { return behavior; } public String getDescription() { return description; } public String getName() { return name; } public Schema getParameters() { return parameters; } public Object getParametersJsonSchema() { return parametersJsonSchema; } public Schema getResponse() { return response; } public Object getResponseJsonSchema() { return responseJsonSchema; } public static Builder builder() { return new Builder(); } public static Builder function(Method method) { Map<String, Schema> properties = new ConcurrentHashMap<>(); PairList<String, String> pairs = FunctionUtils.getParameters(method); for (Pair<String, String> pair : pairs) { Schema schema = Schema.builder() .type(Type.valueOf(pair.getValue().toUpperCase(Locale.ROOT))) .build(); properties.put(pair.getKey(), schema); } Schema parameters = Schema.builder() .type(Type.OBJECT) .required(pairs.keys()) .properties(properties) .build(); return builder().name(method.getName()).parameters(parameters); } /** Builder class for {@code FunctionDeclaration}. */ public static final class Builder { Behavior behavior; String description; String name; Schema parameters; Object parametersJsonSchema; Schema response; Object responseJsonSchema; public Builder behavior(Behavior behavior) { this.behavior = behavior; return this; } public Builder description(String description) { this.description = description; return this; } public Builder name(String name) { this.name = name; return this; } public Builder parameters(Schema parameters) { this.parameters = parameters; return this; } public Builder parameters(Schema.Builder parameters) { this.parameters = parameters.build(); return this; } public Builder parametersJsonSchema(Object parametersJsonSchema) { this.parametersJsonSchema = parametersJsonSchema; return this; } public Builder response(Schema response) { this.response = response; return this; } public Builder response(Schema.Builder response) { this.response = response.build(); return this; } public Builder responseJsonSchema(Object responseJsonSchema) { this.responseJsonSchema = responseJsonSchema; return this; } public FunctionDeclaration build() { return new FunctionDeclaration(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionResponse.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.Map; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class FunctionResponse { private String id; private String name; private Map<String, Object> response; private FunctionResponseScheduling scheduling; private Boolean willContinue; FunctionResponse(Builder builder) { id = builder.id; name = builder.name; response = builder.response; scheduling = builder.scheduling; willContinue = builder.willContinue; } public String getId() { return id; } public String getName() { return name; } public Map<String, Object> getResponse() { return response; } public FunctionResponseScheduling getScheduling() { return scheduling; } public Boolean getWillContinue() { return willContinue; } public static Builder builder() { return new Builder(); } /** Builder class for {@code FunctionResponse}. */ public static final class Builder { String id; String name; Map<String, Object> response; FunctionResponseScheduling scheduling; Boolean willContinue; public Builder id(String id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder response(Map<String, Object> response) { this.response = response; return this; } public Builder scheduling(FunctionResponseScheduling scheduling) { this.scheduling = scheduling; return this; } public Builder willContinue(Boolean willContinue) { this.willContinue = willContinue; return this; } public FunctionResponse build() { return new FunctionResponse(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/FunctionResponseScheduling.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum FunctionResponseScheduling { SCHEDULING_UNSPECIFIED, SILENT, WHEN_IDLE, INTERRUPT, FUNCTION_RESPONSE_SCHEDULING_UNSPECIFIED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GenerateContentResponse.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GenerateContentResponse { private List<Content> automaticFunctionCallingHistory; private List<Candidate> candidates; private String createTime; private String modelVersion; private PromptFeedback promptFeedback; private String responseId; private UsageMetadata usageMetadata; GenerateContentResponse(Builder builder) { automaticFunctionCallingHistory = builder.automaticFunctionCallingHistory; candidates = builder.candidates; createTime = builder.createTime; modelVersion = builder.modelVersion; promptFeedback = builder.promptFeedback; responseId = builder.responseId; usageMetadata = builder.usageMetadata; } public List<Content> getAutomaticFunctionCallingHistory() { return automaticFunctionCallingHistory; } public List<Candidate> getCandidates() { return candidates; } public String getCreateTime() { return createTime; } public String getModelVersion() { return modelVersion; } public PromptFeedback getPromptFeedback() { return promptFeedback; } public String getResponseId() { return responseId; } public UsageMetadata getUsageMetadata() { return usageMetadata; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GenerateContentResponse}. */ public static final class Builder { List<Content> automaticFunctionCallingHistory = new ArrayList<>(); List<Candidate> candidates = new ArrayList<>(); String createTime; String modelVersion; PromptFeedback promptFeedback; String responseId; UsageMetadata usageMetadata; public Builder automaticFunctionCallingHistory( List<Content> automaticFunctionCallingHistory) { this.automaticFunctionCallingHistory.clear(); this.automaticFunctionCallingHistory.addAll(automaticFunctionCallingHistory); return this; } public Builder addAutomaticFunctionCallingHistory(Content automaticFunctionCallingHistory) { this.automaticFunctionCallingHistory.add(automaticFunctionCallingHistory); return this; } public Builder addAutomaticFunctionCallingHistory( Content.Builder automaticFunctionCallingHistory) { this.automaticFunctionCallingHistory.add(automaticFunctionCallingHistory.build()); return this; } public Builder candidates(List<Candidate> candidates) { this.candidates.clear(); this.candidates.addAll(candidates); return this; } public Builder addCandidate(Candidate candidate) { this.candidates.add(candidate); return this; } public Builder addCandidate(Candidate.Builder candidate) { this.candidates.add(candidate.build()); return this; } public Builder createTime(String createTime) { this.createTime = createTime; return this; } public Builder modelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; } public Builder promptFeedback(PromptFeedback promptFeedback) { this.promptFeedback = promptFeedback; return this; } public Builder promptFeedback(PromptFeedback.Builder promptFeedback) { this.promptFeedback = promptFeedback.build(); return this; } public Builder responseId(String responseId) { this.responseId = responseId; return this; } public Builder usageMetadata(UsageMetadata usageMetadata) { this.usageMetadata = usageMetadata; return this; } public Builder usageMetadata(UsageMetadata.Builder usageMetadata) { this.usageMetadata = usageMetadata.build(); return this; } public GenerateContentResponse build() { return new GenerateContentResponse(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GenerationConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; import java.util.Map; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GenerationConfig { private Boolean audioTimestamp; private transient String cachedContent; private Integer candidateCount; private Float frequencyPenalty; private Map<String, String> labels; private Integer logprobs; private Integer maxOutputTokens; private MediaResolution mediaResolution; private ModelSelectionConfig modelSelectionConfig; private Float presencePenalty; private Object responseJsonSchema; private Boolean responseLogprobs; private String responseMimeType; private List<String> responseModalities; private Schema responseSchema; private transient List<SafetySetting> safetySettings; private Integer seed; private SpeechConfig speechConfig; private List<String> stopSequences; private transient Content systemInstruction; private Float temperature; private ThinkingConfig thinkingConfig; private transient ToolConfig toolConfig; private transient List<Tool> tools; private Float topK; private Float topP; GenerationConfig(Builder builder) { audioTimestamp = builder.audioTimestamp; cachedContent = builder.cachedContent; candidateCount = builder.candidateCount; frequencyPenalty = builder.frequencyPenalty; labels = builder.labels; logprobs = builder.logprobs; maxOutputTokens = builder.maxOutputTokens; mediaResolution = builder.mediaResolution; modelSelectionConfig = builder.modelSelectionConfig; presencePenalty = builder.presencePenalty; responseJsonSchema = builder.responseJsonSchema; responseLogprobs = builder.responseLogprobs; responseMimeType = builder.responseMimeType; responseModalities = builder.responseModalities; responseSchema = builder.responseSchema; safetySettings = builder.safetySettings; seed = builder.seed; speechConfig = builder.speechConfig; stopSequences = builder.stopSequences; systemInstruction = builder.systemInstruction; temperature = builder.temperature; thinkingConfig = builder.thinkingConfig; toolConfig = builder.toolConfig; tools = builder.tools; topK = builder.topK; topP = builder.topP; } public Boolean getAudioTimestamp() { return audioTimestamp; } public String getCachedContent() { return cachedContent; } public Integer getCandidateCount() { return candidateCount; } public Float getFrequencyPenalty() { return frequencyPenalty; } public Map<String, String> getLabels() { return labels; } public Integer getLogprobs() { return logprobs; } public Integer getMaxOutputTokens() { return maxOutputTokens; } public MediaResolution getMediaResolution() { return mediaResolution; } public ModelSelectionConfig getModelSelectionConfig() { return modelSelectionConfig; } public Float getPresencePenalty() { return presencePenalty; } public Object getResponseJsonSchema() { return responseJsonSchema; } public Boolean getResponseLogprobs() { return responseLogprobs; } public String getResponseMimeType() { return responseMimeType; } public List<String> getResponseModalities() { return responseModalities; } public Schema getResponseSchema() { return responseSchema; } public List<SafetySetting> getSafetySettings() { return safetySettings; } public Integer getSeed() { return seed; } public SpeechConfig getSpeechConfig() { return speechConfig; } public List<String> getStopSequences() { return stopSequences; } public Content getSystemInstruction() { return systemInstruction; } public Float getTemperature() { return temperature; } public ThinkingConfig getThinkingConfig() { return thinkingConfig; } public ToolConfig getToolConfig() { return toolConfig; } public List<Tool> getTools() { return tools; } public Float getTopK() { return topK; } public Float getTopP() { return topP; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GenerationConfig}. */ public static final class Builder { Boolean audioTimestamp; String cachedContent; Integer candidateCount; Float frequencyPenalty; Map<String, String> labels; Integer logprobs; Integer maxOutputTokens; MediaResolution mediaResolution; ModelSelectionConfig modelSelectionConfig; Float presencePenalty; Object responseJsonSchema; Boolean responseLogprobs; String responseMimeType; List<String> responseModalities; Schema responseSchema; List<SafetySetting> safetySettings = new ArrayList<>(); Integer seed; SpeechConfig speechConfig; List<String> stopSequences; Content systemInstruction; Float temperature; ThinkingConfig thinkingConfig; ToolConfig toolConfig; List<Tool> tools = new ArrayList<>(); Float topK; Float topP; public Builder audioTimestamp(Boolean audioTimestamp) { this.audioTimestamp = audioTimestamp; return this; } public Builder cachedContent(String cachedContent) { this.cachedContent = cachedContent; return this; } public Builder candidateCount(Integer candidateCount) { this.candidateCount = candidateCount; return this; } public Builder frequencyPenalty(Float frequencyPenalty) { this.frequencyPenalty = frequencyPenalty; return this; } public Builder labels(Map<String, String> labels) { this.labels = labels; return this; } public Builder logprobs(Integer logprobs) { this.logprobs = logprobs; return this; } public Builder maxOutputTokens(Integer maxOutputTokens) { this.maxOutputTokens = maxOutputTokens; return this; } public Builder mediaResolution(MediaResolution mediaResolution) { this.mediaResolution = mediaResolution; return this; } public Builder modelSelectionConfig(ModelSelectionConfig modelSelectionConfig) { this.modelSelectionConfig = modelSelectionConfig; return this; } public Builder modelSelectionConfig(ModelSelectionConfig.Builder modelSelectionConfig) { this.modelSelectionConfig = modelSelectionConfig.build(); return this; } public Builder presencePenalty(Float presencePenalty) { this.presencePenalty = presencePenalty; return this; } public Builder responseJsonSchema(Object responseJsonSchema) { this.responseJsonSchema = responseJsonSchema; return this; } public Builder responseLogprobs(Boolean responseLogprobs) { this.responseLogprobs = responseLogprobs; return this; } public Builder responseMimeType(String responseMimeType) { this.responseMimeType = responseMimeType; return this; } public Builder responseModalities(List<String> responseModalities) { this.responseModalities = responseModalities; return this; } public Builder responseSchema(Schema responseSchema) { this.responseSchema = responseSchema; return this; } public Builder responseSchema(Schema.Builder responseSchema) { this.responseSchema = responseSchema.build(); return this; } public Builder safetySettings(List<SafetySetting> safetySettings) { this.safetySettings.clear(); this.safetySettings.addAll(safetySettings); return this; } public Builder addSafetySetting(SafetySetting safetySetting) { this.safetySettings.add(safetySetting); return this; } public Builder addSafetySetting(SafetySetting.Builder safetySetting) { this.safetySettings.add(safetySetting.build()); return this; } public Builder seed(Integer seed) { this.seed = seed; return this; } public Builder speechConfig(SpeechConfig speechConfig) { this.speechConfig = speechConfig; return this; } public Builder speechConfig(SpeechConfig.Builder speechConfig) { this.speechConfig = speechConfig.build(); return this; } public Builder stopSequences(List<String> stopSequences) { this.stopSequences = stopSequences; return this; } public Builder systemInstruction(Content systemInstruction) { this.systemInstruction = systemInstruction; return this; } public Builder systemInstruction(Content.Builder systemInstruction) { this.systemInstruction = systemInstruction.build(); return this; } public Builder systemInstruction(String systemInstruction) { return this.systemInstruction(Content.text(systemInstruction)); } public Builder temperature(Float temperature) { this.temperature = temperature; return this; } public Builder thinkingConfig(ThinkingConfig thinkingConfig) { this.thinkingConfig = thinkingConfig; return this; } public Builder thinkingConfig(ThinkingConfig.Builder thinkingConfig) { this.thinkingConfig = thinkingConfig.build(); return this; } public Builder toolConfig(ToolConfig toolConfig) { this.toolConfig = toolConfig; return this; } public Builder toolConfig(ToolConfig.Builder toolConfig) { this.toolConfig = toolConfig.build(); return this; } public Builder tools(List<Tool> tools) { this.tools.clear(); this.tools.addAll(tools); return this; } public Builder addTool(Tool tool) { this.tools.add(tool); return this; } public Builder addTool(Tool.Builder tool) { this.tools.add(tool.build()); return this; } public Builder topK(Float topK) { this.topK = topK; return this; } public Builder topP(Float topP) { this.topP = topP; return this; } public GenerationConfig build() { return new GenerationConfig(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GoogleSearch.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GoogleSearch { private Interval timeRangeFilter; GoogleSearch(Builder builder) { timeRangeFilter = builder.timeRangeFilter; } public Interval getTimeRangeFilter() { return timeRangeFilter; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GoogleSearch}. */ public static final class Builder { Interval timeRangeFilter; public Builder timeRangeFilter(Interval timeRangeFilter) { this.timeRangeFilter = timeRangeFilter; return this; } public Builder timeRangeFilter(Interval.Builder timeRangeFilter) { this.timeRangeFilter = timeRangeFilter.build(); return this; } public GoogleSearch build() { return new GoogleSearch(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GoogleSearchRetrieval.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GoogleSearchRetrieval { private DynamicRetrievalConfig dynamicRetrievalConfig; GoogleSearchRetrieval(Builder builder) { dynamicRetrievalConfig = builder.dynamicRetrievalConfig; } public DynamicRetrievalConfig getDynamicRetrievalConfig() { return dynamicRetrievalConfig; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GoogleSearchRetrieval}. */ public static final class Builder { DynamicRetrievalConfig dynamicRetrievalConfig; public Builder dynamicRetrievalConfig(DynamicRetrievalConfig dynamicRetrievalConfig) { this.dynamicRetrievalConfig = dynamicRetrievalConfig; return this; } public Builder dynamicRetrievalConfig( DynamicRetrievalConfig.Builder dynamicRetrievalConfig) { this.dynamicRetrievalConfig = dynamicRetrievalConfig.build(); return this; } public GoogleSearchRetrieval build() { return new GoogleSearchRetrieval(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GoogleTypeDate.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GoogleTypeDate { private Integer day; private Integer month; private Integer year; GoogleTypeDate(Builder builder) { day = builder.day; month = builder.month; year = builder.year; } public Integer getDay() { return day; } public Integer getMonth() { return month; } public Integer getYear() { return year; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GoogleTypeDate}. */ public static final class Builder { Integer day; Integer month; Integer year; public Builder day(Integer day) { this.day = day; return this; } public Builder month(Integer month) { this.month = month; return this; } public Builder year(Integer year) { this.year = year; return this; } public GoogleTypeDate build() { return new GoogleTypeDate(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GroundingChunk.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GroundingChunk { private GroundingChunkRetrievedContext retrievedContext; private GroundingChunkWeb web; GroundingChunk(Builder builder) { retrievedContext = builder.retrievedContext; web = builder.web; } public GroundingChunkRetrievedContext getRetrievedContext() { return retrievedContext; } public GroundingChunkWeb getWeb() { return web; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GroundingChunk}. */ public static final class Builder { GroundingChunkRetrievedContext retrievedContext; GroundingChunkWeb web; public Builder retrievedContext(GroundingChunkRetrievedContext retrievedContext) { this.retrievedContext = retrievedContext; return this; } public Builder retrievedContext(GroundingChunkRetrievedContext.Builder retrievedContext) { this.retrievedContext = retrievedContext.build(); return this; } public Builder web(GroundingChunkWeb web) { this.web = web; return this; } public Builder web(GroundingChunkWeb.Builder web) { this.web = web.build(); return this; } public GroundingChunk build() { return new GroundingChunk(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GroundingChunkRetrievedContext.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GroundingChunkRetrievedContext { private RagChunk ragChunk; private String text; private String title; private String uri; GroundingChunkRetrievedContext(Builder builder) { ragChunk = builder.ragChunk; text = builder.text; title = builder.title; uri = builder.uri; } public RagChunk getRagChunk() { return ragChunk; } public String getText() { return text; } public String getTitle() { return title; } public String getUri() { return uri; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GroundingChunkRetrievedContext}. */ public static final class Builder { RagChunk ragChunk; String text; String title; String uri; public Builder ragChunk(RagChunk ragChunk) { this.ragChunk = ragChunk; return this; } public Builder ragChunk(RagChunk.Builder ragChunk) { this.ragChunk = ragChunk.build(); return this; } public Builder text(String text) { this.text = text; return this; } public Builder title(String title) { this.title = title; return this; } public Builder uri(String uri) { this.uri = uri; return this; } public GroundingChunkRetrievedContext build() { return new GroundingChunkRetrievedContext(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GroundingChunkWeb.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GroundingChunkWeb { private String domain; private String title; private String uri; GroundingChunkWeb(Builder builder) { domain = builder.domain; title = builder.title; uri = builder.uri; } public String getDomain() { return domain; } public String getTitle() { return title; } public String getUri() { return uri; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GroundingChunkWeb}. */ public static final class Builder { String domain; String title; String uri; public Builder domain(String domain) { this.domain = domain; return this; } public Builder title(String title) { this.title = title; return this; } public Builder uri(String uri) { this.uri = uri; return this; } public GroundingChunkWeb build() { return new GroundingChunkWeb(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GroundingMetadata.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GroundingMetadata { private List<GroundingChunk> groundingChunks; private List<GroundingSupport> groundingSupports; private RetrievalMetadata retrievalMetadata; private List<String> retrievalQueries; private SearchEntryPoint searchEntryPoint; private List<String> webSearchQueries; GroundingMetadata(Builder builder) { groundingChunks = builder.groundingChunks; groundingSupports = builder.groundingSupports; retrievalMetadata = builder.retrievalMetadata; retrievalQueries = builder.retrievalQueries; searchEntryPoint = builder.searchEntryPoint; webSearchQueries = builder.webSearchQueries; } public List<GroundingChunk> getGroundingChunks() { return groundingChunks; } public List<GroundingSupport> getGroundingSupports() { return groundingSupports; } public RetrievalMetadata getRetrievalMetadata() { return retrievalMetadata; } public List<String> getRetrievalQueries() { return retrievalQueries; } public SearchEntryPoint getSearchEntryPoint() { return searchEntryPoint; } public List<String> getWebSearchQueries() { return webSearchQueries; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GroundingMetadata}. */ public static final class Builder { List<GroundingChunk> groundingChunks = new ArrayList<>(); List<GroundingSupport> groundingSupports = new ArrayList<>(); RetrievalMetadata retrievalMetadata; List<String> retrievalQueries; SearchEntryPoint searchEntryPoint; List<String> webSearchQueries; public Builder groundingChunks(List<GroundingChunk> groundingChunks) { this.groundingChunks.clear(); this.groundingChunks.addAll(groundingChunks); return this; } public Builder addGroundingChunk(GroundingChunk groundingChunk) { this.groundingChunks.add(groundingChunk); return this; } public Builder addGroundingChunk(GroundingChunk.Builder groundingChunk) { this.groundingChunks.add(groundingChunk.build()); return this; } public Builder groundingSupports(List<GroundingSupport> groundingSupports) { this.groundingSupports.clear(); this.groundingSupports.addAll(groundingSupports); return this; } public Builder addGroundingSupport(GroundingSupport groundingSupport) { this.groundingSupports.add(groundingSupport); return this; } public Builder addGroundingSupport(GroundingSupport.Builder groundingSupport) { this.groundingSupports.add(groundingSupport.build()); return this; } public Builder retrievalMetadata(RetrievalMetadata retrievalMetadata) { this.retrievalMetadata = retrievalMetadata; return this; } public Builder retrievalMetadata(RetrievalMetadata.Builder retrievalMetadata) { this.retrievalMetadata = retrievalMetadata.build(); return this; } public Builder retrievalQueries(List<String> retrievalQueries) { this.retrievalQueries = retrievalQueries; return this; } public Builder searchEntryPoint(SearchEntryPoint searchEntryPoint) { this.searchEntryPoint = searchEntryPoint; return this; } public Builder searchEntryPoint(SearchEntryPoint.Builder searchEntryPoint) { this.searchEntryPoint = searchEntryPoint.build(); return this; } public Builder webSearchQueries(List<String> webSearchQueries) { this.webSearchQueries = webSearchQueries; return this; } public GroundingMetadata build() { return new GroundingMetadata(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/GroundingSupport.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class GroundingSupport { private List<Float> confidenceScores; private List<Integer> groundingChunkIndices; private Segment segment; GroundingSupport(Builder builder) { confidenceScores = builder.confidenceScores; groundingChunkIndices = builder.groundingChunkIndices; segment = builder.segment; } public List<Float> getConfidenceScores() { return confidenceScores; } public List<Integer> getGroundingChunkIndices() { return groundingChunkIndices; } public Segment getSegment() { return segment; } public static Builder builder() { return new Builder(); } /** Builder class for {@code GroundingSupport}. */ public static final class Builder { List<Float> confidenceScores; List<Integer> groundingChunkIndices; Segment segment; public Builder confidenceScores(List<Float> confidenceScores) { this.confidenceScores = confidenceScores; return this; } public Builder groundingChunkIndices(List<Integer> groundingChunkIndices) { this.groundingChunkIndices = groundingChunkIndices; return this; } public Builder segment(Segment segment) { this.segment = segment; return this; } public Builder segment(Segment.Builder segment) { this.segment = segment.build(); return this; } public GroundingSupport build() { return new GroundingSupport(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/HarmBlockMethod.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum HarmBlockMethod { HARM_BLOCK_METHOD_UNSPECIFIED, SEVERITY, PROBABILITY }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/HarmBlockThreshold.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum HarmBlockThreshold { HARM_BLOCK_THRESHOLD_UNSPECIFIED, BLOCK_LOW_AND_ABOVE, BLOCK_MEDIUM_AND_ABOVE, BLOCK_ONLY_HIGH, BLOCK_NONE, OFF }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/HarmCategory.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum HarmCategory { HARM_CATEGORY_UNSPECIFIED, HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_CIVIC_INTEGRITY, HARM_CATEGORY_IMAGE_HATE, HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT, HARM_CATEGORY_IMAGE_HARASSMENT, HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/HarmProbability.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum HarmProbability { HARM_PROBABILITY_UNSPECIFIED, NEGLIGIBLE, LOW, MEDIUM, HIGH }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/HarmSeverity.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum HarmSeverity { HARM_SEVERITY_UNSPECIFIED, HARM_SEVERITY_NEGLIGIBLE, HARM_SEVERITY_LOW, HARM_SEVERITY_MEDIUM, HARM_SEVERITY_HIGH }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Interval.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Interval { private String endTime; private String startTime; Interval(Builder builder) { endTime = builder.endTime; startTime = builder.startTime; } public String getEndTime() { return endTime; } public String getStartTime() { return startTime; } public static Builder builder() { return new Builder(); } /** Builder class for {@code Interval}. */ public static final class Builder { String endTime; String startTime; public Builder endTime(String endTime) { this.endTime = endTime; return this; } public Builder startTime(String startTime) { this.startTime = startTime; return this; } public Interval build() { return new Interval(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Language.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum Language { LANGUAGE_UNSPECIFIED, PYTHON }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/LatLng.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class LatLng { private Double latitude; private Double longitude; LatLng(Double latitude, Double longitude) { this.latitude = latitude; this.longitude = longitude; } public Double getLatitude() { return latitude; } public Double getLongitude() { return longitude; } public static LatLng of(Double latitude, Double longitude) { return new LatLng(latitude, longitude); } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/LogprobsResult.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class LogprobsResult { private List<LogprobsResultCandidate> chosenCandidates; private List<LogprobsResultTopCandidates> topCandidates; LogprobsResult(Builder builder) { chosenCandidates = builder.chosenCandidates; topCandidates = builder.topCandidates; } public List<LogprobsResultCandidate> getChosenCandidates() { return chosenCandidates; } public List<LogprobsResultTopCandidates> getTopCandidates() { return topCandidates; } public static Builder builder() { return new Builder(); } /** Builder class for {@code LogprobsResult}. */ public static final class Builder { List<LogprobsResultCandidate> chosenCandidates = new ArrayList<>(); List<LogprobsResultTopCandidates> topCandidates = new ArrayList<>(); public Builder chosenCandidates(List<LogprobsResultCandidate> chosenCandidates) { this.chosenCandidates.clear(); this.chosenCandidates.addAll(chosenCandidates); return this; } public Builder addChosenCandidate(LogprobsResultCandidate chosenCandidate) { this.chosenCandidates.add(chosenCandidate); return this; } public Builder addChosenCandidate(LogprobsResultCandidate.Builder chosenCandidate) { this.chosenCandidates.add(chosenCandidate.build()); return this; } public Builder topCandidates(List<LogprobsResultTopCandidates> topCandidates) { this.topCandidates.clear(); this.topCandidates.addAll(topCandidates); return this; } public Builder addTopCandidate(LogprobsResultTopCandidates topCandidate) { this.topCandidates.add(topCandidate); return this; } public Builder addTopCandidate(LogprobsResultTopCandidates.Builder topCandidate) { this.topCandidates.add(topCandidate.build()); return this; } public LogprobsResult build() { return new LogprobsResult(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/LogprobsResultCandidate.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class LogprobsResultCandidate { private Float logProbability; private String token; private Integer tokenId; LogprobsResultCandidate(Builder builder) { logProbability = builder.logProbability; token = builder.token; tokenId = builder.tokenId; } public Float getLogProbability() { return logProbability; } public String getToken() { return token; } public Integer getTokenId() { return tokenId; } public static Builder builder() { return new Builder(); } /** Builder class for {@code LogprobsResultCandidate}. */ public static final class Builder { Float logProbability; String token; Integer tokenId; public Builder logProbability(Float logProbability) { this.logProbability = logProbability; return this; } public Builder token(String token) { this.token = token; return this; } public Builder tokenId(Integer tokenId) { this.tokenId = tokenId; return this; } public LogprobsResultCandidate build() { return new LogprobsResultCandidate(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/LogprobsResultTopCandidates.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class LogprobsResultTopCandidates { private List<LogprobsResultCandidate> candidates; LogprobsResultTopCandidates(Builder builder) { candidates = builder.candidates; } public List<LogprobsResultCandidate> getCandidates() { return candidates; } public static Builder builder() { return new Builder(); } /** Builder class for {@code LogprobsResultTopCandidates}. */ public static final class Builder { List<LogprobsResultCandidate> candidates = new ArrayList<>(); public Builder candidates(List<LogprobsResultCandidate> candidates) { this.candidates.clear(); this.candidates.addAll(candidates); return this; } public Builder addCandidate(LogprobsResultCandidate candidate) { this.candidates.add(candidate); return this; } public Builder addCandidate(LogprobsResultCandidate.Builder candidate) { this.candidates.add(candidate.build()); return this; } public LogprobsResultTopCandidates build() { return new LogprobsResultTopCandidates(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/MediaModality.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum MediaModality { MODALITY_UNSPECIFIED, TEXT, IMAGE, VIDEO, AUDIO, DOCUMENT, MEDIA_MODALITY_UNSPECIFIED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/MediaResolution.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum MediaResolution { MEDIA_RESOLUTION_UNSPECIFIED, MEDIA_RESOLUTION_LOW, MEDIA_RESOLUTION_MEDIUM, MEDIA_RESOLUTION_HIGH }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/ModalityTokenCount.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class ModalityTokenCount { private MediaModality modality; private Integer tokenCount; ModalityTokenCount(Builder builder) { modality = builder.modality; tokenCount = builder.tokenCount; } public MediaModality getModality() { return modality; } public Integer getTokenCount() { return tokenCount; } public static Builder builder() { return new Builder(); } /** Builder class for {@code ModalityTokenCount}. */ public static final class Builder { MediaModality modality; Integer tokenCount; public Builder modality(MediaModality modality) { this.modality = modality; return this; } public Builder tokenCount(Integer tokenCount) { this.tokenCount = tokenCount; return this; } public ModalityTokenCount build() { return new ModalityTokenCount(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/ModelSelectionConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class ModelSelectionConfig { private FeatureSelectionPreference featureSelectionPreference; ModelSelectionConfig(Builder builder) { featureSelectionPreference = builder.featureSelectionPreference; } public FeatureSelectionPreference getFeatureSelectionPreference() { return featureSelectionPreference; } public static Builder builder() { return new Builder(); } /** Builder class for {@code ModelSelectionConfig}. */ public static final class Builder { FeatureSelectionPreference featureSelectionPreference; public Builder featureSelectionPreference( FeatureSelectionPreference featureSelectionPreference) { this.featureSelectionPreference = featureSelectionPreference; return this; } public ModelSelectionConfig build() { return new ModelSelectionConfig(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/MultiSpeakerVoiceConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.ArrayList; import java.util.List; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class MultiSpeakerVoiceConfig { private List<SpeakerVoiceConfig> speakerVoiceConfigs; MultiSpeakerVoiceConfig(Builder builder) { speakerVoiceConfigs = builder.speakerVoiceConfigs; } public List<SpeakerVoiceConfig> getSpeakerVoiceConfigs() { return speakerVoiceConfigs; } public static Builder builder() { return new Builder(); } /** Builder class for {@code MultiSpeakerVoiceConfig}. */ public static final class Builder { List<SpeakerVoiceConfig> speakerVoiceConfigs = new ArrayList<>(); public Builder speakerVoiceConfigs(List<SpeakerVoiceConfig> speakerVoiceConfigs) { this.speakerVoiceConfigs.clear(); this.speakerVoiceConfigs.addAll(speakerVoiceConfigs); return this; } public Builder addSpeakerVoiceConfig(SpeakerVoiceConfig speakerVoiceConfig) { this.speakerVoiceConfigs.add(speakerVoiceConfig); return this; } public Builder addSpeakerVoiceConfig(SpeakerVoiceConfig.Builder speakerVoiceConfig) { this.speakerVoiceConfigs.add(speakerVoiceConfig.build()); return this; } public MultiSpeakerVoiceConfig build() { return new MultiSpeakerVoiceConfig(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Outcome.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** An enum represent Gemini schema. */ public enum Outcome { OUTCOME_UNSPECIFIED, OUTCOME_OK, OUTCOME_FAILED, OUTCOME_DEADLINE_EXCEEDED }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/Part.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; import java.util.Base64; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class Part { private CodeExecutionResult codeExecutionResult; private ExecutableCode executableCode; private FileData fileData; private FunctionCall functionCall; private FunctionResponse functionResponse; private Blob inlineData; private String text; private Boolean thought; private String thoughtSignature; private VideoMetadata videoMetadata; Part(Builder builder) { codeExecutionResult = builder.codeExecutionResult; executableCode = builder.executableCode; fileData = builder.fileData; functionCall = builder.functionCall; functionResponse = builder.functionResponse; inlineData = builder.inlineData; text = builder.text; thought = builder.thought; thoughtSignature = builder.thoughtSignature; videoMetadata = builder.videoMetadata; } public CodeExecutionResult getCodeExecutionResult() { return codeExecutionResult; } public ExecutableCode getExecutableCode() { return executableCode; } public FileData getFileData() { return fileData; } public FunctionCall getFunctionCall() { return functionCall; } public FunctionResponse getFunctionResponse() { return functionResponse; } public Blob getInlineData() { return inlineData; } public String getText() { return text; } public Boolean getThought() { return thought; } public String getThoughtSignature() { return thoughtSignature; } public VideoMetadata getVideoMetadata() { return videoMetadata; } public static Builder builder() { return new Builder(); } public static Builder text(String text) { return builder().text(text); } public static Builder fileData(String fileUri, String mimeType) { return builder().fileData(FileData.builder().fileUri(fileUri).mimeType(mimeType)); } public static Builder inlineData(byte[] bytes, String mimeType) { return builder().inlineData(Blob.builder().data(bytes).mimeType(mimeType)); } /** Builder class for {@code Part}. */ public static final class Builder { CodeExecutionResult codeExecutionResult; ExecutableCode executableCode; FileData fileData; FunctionCall functionCall; FunctionResponse functionResponse; Blob inlineData; String text; Boolean thought; String thoughtSignature; VideoMetadata videoMetadata; public Builder codeExecutionResult(CodeExecutionResult codeExecutionResult) { this.codeExecutionResult = codeExecutionResult; return this; } public Builder codeExecutionResult(CodeExecutionResult.Builder codeExecutionResult) { this.codeExecutionResult = codeExecutionResult.build(); return this; } public Builder executableCode(ExecutableCode executableCode) { this.executableCode = executableCode; return this; } public Builder executableCode(ExecutableCode.Builder executableCode) { this.executableCode = executableCode.build(); return this; } public Builder fileData(FileData fileData) { this.fileData = fileData; return this; } public Builder fileData(FileData.Builder fileData) { this.fileData = fileData.build(); return this; } public Builder functionCall(FunctionCall functionCall) { this.functionCall = functionCall; return this; } public Builder functionCall(FunctionCall.Builder functionCall) { this.functionCall = functionCall.build(); return this; } public Builder functionResponse(FunctionResponse functionResponse) { this.functionResponse = functionResponse; return this; } public Builder functionResponse(FunctionResponse.Builder functionResponse) { this.functionResponse = functionResponse.build(); return this; } public Builder inlineData(Blob inlineData) { this.inlineData = inlineData; return this; } public Builder inlineData(Blob.Builder inlineData) { this.inlineData = inlineData.build(); return this; } public Builder text(String text) { this.text = text; return this; } public Builder thought(Boolean thought) { this.thought = thought; return this; } public Builder thoughtSignature(byte[] thoughtSignature) { this.thoughtSignature = Base64.getEncoder().encodeToString(thoughtSignature); return this; } public Builder videoMetadata(VideoMetadata videoMetadata) { this.videoMetadata = videoMetadata; return this; } public Builder videoMetadata(VideoMetadata.Builder videoMetadata) { this.videoMetadata = videoMetadata.build(); return this; } public Part build() { return new Part(this); } } }
0
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini
java-sources/ai/djl/genai/genai/0.34.0/ai/djl/genai/gemini/types/PrebuiltVoiceConfig.java
/* * Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 ai.djl.genai.gemini.types; /** A data class represents Gemini schema. */ @SuppressWarnings("MissingJavadocMethod") public class PrebuiltVoiceConfig { private String voiceName; PrebuiltVoiceConfig(Builder builder) { voiceName = builder.voiceName; } public String getVoiceName() { return voiceName; } public static Builder builder() { return new Builder(); } /** Builder class for {@code PrebuiltVoiceConfig}. */ public static final class Builder { String voiceName; public Builder voiceName(String voiceName) { this.voiceName = voiceName; return this; } public PrebuiltVoiceConfig build() { return new PrebuiltVoiceConfig(this); } } }