Skip to content

Commit 9ba6123

Browse files
committed
Added a Gemini API completions example
1 parent f62e123 commit 9ba6123

5 files changed

Lines changed: 169 additions & 0 deletions

File tree

gemini-llm-client/Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
run:
2+
mvn test -q # run test in quiet mode
3+

gemini-llm-client/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# OpenAI API Example
2+
3+
run test using default Makefile target:
4+
5+
make

gemini-llm-client/pom.xml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.markwatson.gemini</groupId>
5+
<artifactId>gemini-client-example</artifactId>
6+
<packaging>jar</packaging>
7+
<version>1.0-SNAPSHOT</version>
8+
<name>gemini-client-example</name>
9+
<url>http://maven.apache.org</url>
10+
<dependencies>
11+
<dependency>
12+
<groupId>junit</groupId>
13+
<artifactId>junit</artifactId>
14+
<version>3.8.1</version>
15+
<scope>test</scope>
16+
</dependency>
17+
<dependency>
18+
<groupId>org.json</groupId>
19+
<artifactId>json</artifactId>
20+
<version>20240303</version>
21+
</dependency>
22+
</dependencies>
23+
</project>
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.markwatson.gemini;
2+
3+
import org.json.JSONObject;
4+
5+
import java.io.BufferedReader;
6+
import java.io.IOException;
7+
import java.io.InputStreamReader;
8+
import java.io.OutputStream;
9+
import java.net.HttpURLConnection;
10+
import java.net.URI;
11+
import java.net.URL;
12+
import java.net.URLConnection;
13+
import java.nio.file.Files;
14+
import java.nio.file.Path;
15+
import java.nio.file.Paths;
16+
17+
public class GeminiCompletions {
18+
19+
public static void main(String[] args) throws Exception {
20+
String prompt = "How much is 11 + 22?";
21+
String completion = getCompletion(prompt);
22+
System.out.println("completion: " + completion);
23+
}
24+
25+
public static String getCompletion(String prompt) throws Exception {
26+
String apiKey = System.getenv("GOOGLE_API_KEY");
27+
if (apiKey == null || apiKey.isEmpty()) {
28+
throw new IOException("GOOGLE_API_KEY environment variable not set.");
29+
}
30+
String model = "gemini-2.5-flash";
31+
URI uri = new URI("https://generativelanguage.googleapis.com/v1beta/models/" + model + ":generateContent?key=" + apiKey);
32+
URL url = uri.toURL();
33+
System.out.println("\n\nurl:\n\n" + url + "\n\n");
34+
35+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
36+
connection.setRequestMethod("POST");
37+
connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); String jsonBody = "{\"contents\":[{\"parts\":[{\"text\":\"" + prompt + "\"}]}]}"; try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonBody.getBytes("utf-8");
38+
os.write(input, 0, input.length);
39+
}
40+
41+
StringBuilder response = new StringBuilder();
42+
try (BufferedReader br = new BufferedReader(
43+
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
44+
String responseLine = null;
45+
while ((responseLine = br.readLine()) != null) {
46+
response.append(responseLine.trim());
47+
}
48+
}
49+
50+
connection.disconnect();
51+
JSONObject jsonObject = new JSONObject(response.toString());
52+
return jsonObject.getJSONArray("candidates").getJSONObject(0).getJSONObject("content").getJSONArray("parts").getJSONObject(0).getString("text");
53+
}
54+
55+
56+
/***
57+
* Utilities for using the Gemini API
58+
*/
59+
60+
// read the contents of a file path into a Java string
61+
public static String readFileToString(String filePath) throws IOException {
62+
Path path = Paths.get(filePath);
63+
return new String(Files.readAllBytes(path)).replace("\"", "\\\"");
64+
}
65+
66+
public static String replaceSubstring(String originalString, String substringToReplace, String replacementString) {
67+
return originalString.replace(substringToReplace, replacementString);
68+
}
69+
public static String promptVar(String prompt0, String varName, String varValue) {
70+
String prompt = replaceSubstring(prompt0, varName, varValue);
71+
return replaceSubstring(prompt, varName, varValue);
72+
}
73+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.markwatson.gemini;
2+
3+
import junit.framework.Test;
4+
import junit.framework.TestCase;
5+
import junit.framework.TestSuite;
6+
7+
/**
8+
* Unit test for simple App.
9+
*/
10+
public class GeminiCompletionsTest
11+
extends TestCase
12+
{
13+
/**
14+
* Create the test case
15+
*
16+
* @param testName name of the test case
17+
*/
18+
public GeminiCompletionsTest( String testName )
19+
{
20+
super( testName );
21+
}
22+
23+
/**
24+
* @return the suite of tests being tested
25+
*/
26+
public static Test suite()
27+
{
28+
return new TestSuite( GeminiCompletionsTest.class );
29+
}
30+
31+
/**
32+
* Rigourous Test :-)
33+
* @throws Exception
34+
*/
35+
public void testCompletion() throws Exception
36+
{
37+
String r = GeminiCompletions.getCompletion("Translate the following English text to French: 'Hello, how are you?'");
38+
System.out.println("completion: " + r);
39+
assertTrue( true );
40+
}
41+
42+
public void testTwoShotTemplate() throws Exception {
43+
String input_text = "Mark Johnson enjoys living in Berkeley California at 102 Dunston Street and use mjess@foobar.com for contacting him.";
44+
String prompt0 = GeminiCompletions.readFileToString("../prompts/two-shot-2-var.txt");
45+
System.out.println("prompt0: " + prompt0);
46+
String prompt = GeminiCompletions.promptVar(prompt0, "{input_text}", input_text);
47+
System.out.println("prompt: " + prompt);
48+
String r =
49+
GeminiCompletions.getCompletion(prompt);
50+
System.out.println("two shot extraction completion: " + r);
51+
assertTrue( true );
52+
}
53+
54+
public void testSummarization() throws Exception {
55+
String input_text = "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[ and is on average the third-brightest natural object in the night sky after the Moon and Venus.";
56+
String prompt0 = GeminiCompletions.readFileToString("../prompts/summarization_prompt.txt");
57+
System.out.println("prompt0: " + prompt0);
58+
String prompt = GeminiCompletions.promptVar(prompt0, "{input_text}", input_text);
59+
System.out.println("prompt: " + prompt);
60+
String r =
61+
GeminiCompletions.getCompletion(prompt);
62+
System.out.println("summarization completion: " + r);
63+
assertTrue( true );
64+
}
65+
}

0 commit comments

Comments
 (0)