Java library for Gemini API. See the documentation here: https://ai.google.dev/gemini-api
- Generate an API key: https://aistudio.google.com/app/apikey
Add the gemini-api
dependency. Maven example (replace ${gemini.version} with the latest version):
<dependency>
<groupId>swiss.ameri</groupId>
<artifactId>gemini-api</artifactId>
<version>${gemini.version}</version>
</dependency>
In order for this library to stay free of dependencies, the user must provide an implementation of
the swiss.ameri.gemini.spi.JsonParser
interface.
Alternatively, an example Gson implementation can be used with the following dependency (which includes a Gson
dependency)
<dependency>
<groupId>swiss.ameri</groupId>
<artifactId>gemini-gson</artifactId>
<version>${gemini.version}</version>
</dependency>
See gemini-tester for some examples.
JsonParser parser = new GsonJsonParser(); // or some custom implementation
String apiKey = ...;
GenAi genAi = new GenAi(
apiKey,
parser
);
// list available models
genAi.listModels().forEach(System.out::println);
// create a prompt
var model = GenerativeModel.builder()
.modelName(ModelVariant.GEMINI_1_0_PRO)
.addContent(new Content.TextContent(
Content.Role.USER.roleName(),
"Write a 300 word story about a magic backpack."
))
.build();
// execute the prompt, wait for the full response
genAi.generateContent(model)
.thenAccept(System.out::println)
.get(20, TimeUnit.SECONDS); // block here until the response arrives. Probably not a good idea in production code.
// execute the prompt, process the chunks of responses as they arrive
genAi.generateContentStream(model)
.forEach(System.out::println)
The library versioning follows the scheme:
<gemini-api-version>.<major>.<minor>.<patch>
Example:
1beta.0.0.1
- >= Java 17
The project is composed of the following maven modules, which are deployed to maven central.
<dependency>
<groupId>swiss.ameri</groupId>
<artifactId>gemini-api</artifactId>
<version>${gemini.version}</version>
</dependency>
Main module to be used. Must not contain any dependencies to other modules.
<dependency>
<groupId>swiss.ameri</groupId>
<artifactId>gemini-gson</artifactId>
<version>${gemini.version}</version>
</dependency>
Provides an example implementation of the swiss.ameri.gemini.spi.JsonParser
class using Gson
.
Contains a maven dependency to Gson
<dependency>
<groupId>swiss.ameri</groupId>
<artifactId>gemini-tester</artifactId>
<version>${gemini.version}</version>
</dependency>
Contains some example code of how the API can be used.