forked from Mirror/ollama4j
Add Spotless plugin and update copyright headers
Introduced the Spotless Maven plugin for code formatting in pom.xml. Updated copyright headers to include 'and contributors' and changed the year to 2025 in all main source files. Minor formatting and import order improvements applied throughout the codebase.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,28 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.integrationtests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.OllamaAPI;
|
||||
import io.github.ollama4j.exceptions.OllamaBaseException;
|
||||
import io.github.ollama4j.models.response.OllamaResult;
|
||||
import io.github.ollama4j.samples.AnnotatedTool;
|
||||
import io.github.ollama4j.tools.annotations.OllamaToolService;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -19,20 +37,14 @@ import org.testcontainers.ollama.OllamaContainer;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
import org.testcontainers.utility.MountableFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@OllamaToolService(providers = {AnnotatedTool.class})
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@SuppressWarnings({"HttpUrlsUsage", "SpellCheckingInspection", "resource", "ResultOfMethodCallIgnored"})
|
||||
@SuppressWarnings({
|
||||
"HttpUrlsUsage",
|
||||
"SpellCheckingInspection",
|
||||
"resource",
|
||||
"ResultOfMethodCallIgnored"
|
||||
})
|
||||
public class WithAuth {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WithAuth.class);
|
||||
@@ -42,8 +54,7 @@ public class WithAuth {
|
||||
private static final String NGINX_VERSION = "nginx:1.23.4-alpine";
|
||||
private static final String BEARER_AUTH_TOKEN = "secret-token";
|
||||
private static final String GENERAL_PURPOSE_MODEL = "gemma3:270m";
|
||||
// private static final String THINKING_MODEL = "gpt-oss:20b";
|
||||
|
||||
// private static final String THINKING_MODEL = "gpt-oss:20b";
|
||||
|
||||
private static OllamaContainer ollama;
|
||||
private static GenericContainer<?> nginx;
|
||||
@@ -63,43 +74,48 @@ public class WithAuth {
|
||||
api.setRequestTimeoutSeconds(120);
|
||||
api.setNumberOfRetriesForModelPull(3);
|
||||
|
||||
String ollamaUrl = "http://" + ollama.getHost() + ":" + ollama.getMappedPort(OLLAMA_INTERNAL_PORT);
|
||||
String ollamaUrl =
|
||||
"http://" + ollama.getHost() + ":" + ollama.getMappedPort(OLLAMA_INTERNAL_PORT);
|
||||
String nginxUrl = "http://" + nginx.getHost() + ":" + nginx.getMappedPort(NGINX_PORT);
|
||||
LOG.info(
|
||||
"The Ollama service is now accessible via the Nginx proxy with bearer-auth authentication mode.\n" +
|
||||
"→ Ollama URL: {}\n" +
|
||||
"→ Proxy URL: {}",
|
||||
ollamaUrl, nginxUrl
|
||||
);
|
||||
"The Ollama service is now accessible via the Nginx proxy with bearer-auth"
|
||||
+ " authentication mode.\n"
|
||||
+ "→ Ollama URL: {}\n"
|
||||
+ "→ Proxy URL: {}",
|
||||
ollamaUrl,
|
||||
nginxUrl);
|
||||
LOG.info("OllamaAPI initialized with bearer auth token: {}", BEARER_AUTH_TOKEN);
|
||||
}
|
||||
|
||||
private static OllamaContainer createOllamaContainer() {
|
||||
return new OllamaContainer("ollama/ollama:" + OLLAMA_VERSION).withExposedPorts(OLLAMA_INTERNAL_PORT);
|
||||
return new OllamaContainer("ollama/ollama:" + OLLAMA_VERSION)
|
||||
.withExposedPorts(OLLAMA_INTERNAL_PORT);
|
||||
}
|
||||
|
||||
private static String generateNginxConfig(int ollamaPort) {
|
||||
return String.format("events {}\n" +
|
||||
"\n" +
|
||||
"http {\n" +
|
||||
" server {\n" +
|
||||
" listen 80;\n" +
|
||||
"\n" +
|
||||
" location / {\n" +
|
||||
" set $auth_header $http_authorization;\n" +
|
||||
"\n" +
|
||||
" if ($auth_header != \"Bearer secret-token\") {\n" +
|
||||
" return 401;\n" +
|
||||
" }\n" +
|
||||
"\n" +
|
||||
" proxy_pass http://host.docker.internal:%s/;\n" +
|
||||
" proxy_set_header Host $host;\n" +
|
||||
" proxy_set_header X-Real-IP $remote_addr;\n" +
|
||||
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
|
||||
" proxy_set_header X-Forwarded-Proto $scheme;\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}\n", ollamaPort);
|
||||
return String.format(
|
||||
"events {}\n"
|
||||
+ "\n"
|
||||
+ "http {\n"
|
||||
+ " server {\n"
|
||||
+ " listen 80;\n"
|
||||
+ "\n"
|
||||
+ " location / {\n"
|
||||
+ " set $auth_header $http_authorization;\n"
|
||||
+ "\n"
|
||||
+ " if ($auth_header != \"Bearer secret-token\") {\n"
|
||||
+ " return 401;\n"
|
||||
+ " }\n"
|
||||
+ "\n"
|
||||
+ " proxy_pass http://host.docker.internal:%s/;\n"
|
||||
+ " proxy_set_header Host $host;\n"
|
||||
+ " proxy_set_header X-Real-IP $remote_addr;\n"
|
||||
+ " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n"
|
||||
+ " proxy_set_header X-Forwarded-Proto $scheme;\n"
|
||||
+ " }\n"
|
||||
+ " }\n"
|
||||
+ "}\n",
|
||||
ollamaPort);
|
||||
}
|
||||
|
||||
public static GenericContainer<?> createNginxContainer(int ollamaPort) {
|
||||
@@ -117,14 +133,12 @@ public class WithAuth {
|
||||
.withExposedPorts(NGINX_PORT)
|
||||
.withCopyFileToContainer(
|
||||
MountableFile.forHostPath(nginxConf.getAbsolutePath()),
|
||||
"/etc/nginx/nginx.conf"
|
||||
)
|
||||
"/etc/nginx/nginx.conf")
|
||||
.withExtraHost("host.docker.internal", "host-gateway")
|
||||
.waitingFor(
|
||||
Wait.forHttp("/")
|
||||
.forStatusCode(401)
|
||||
.withStartupTimeout(Duration.ofSeconds(30))
|
||||
);
|
||||
.withStartupTimeout(Duration.ofSeconds(30)));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to create nginx.conf", e);
|
||||
}
|
||||
@@ -134,14 +148,18 @@ public class WithAuth {
|
||||
@Order(1)
|
||||
void testOllamaBehindProxy() {
|
||||
api.setBearerAuth(BEARER_AUTH_TOKEN);
|
||||
assertTrue(api.ping(), "Expected OllamaAPI to successfully ping through NGINX with valid auth token.");
|
||||
assertTrue(
|
||||
api.ping(),
|
||||
"Expected OllamaAPI to successfully ping through NGINX with valid auth token.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void testWithWrongToken() {
|
||||
api.setBearerAuth("wrong-token");
|
||||
assertFalse(api.ping(), "Expected OllamaAPI ping to fail through NGINX with an invalid auth token.");
|
||||
assertFalse(
|
||||
api.ping(),
|
||||
"Expected OllamaAPI ping to fail through NGINX with an invalid auth token.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -152,19 +170,25 @@ public class WithAuth {
|
||||
String model = GENERAL_PURPOSE_MODEL;
|
||||
api.pullModel(model);
|
||||
|
||||
String prompt = "The sun is shining brightly and is directly overhead at the zenith, casting my shadow over my foot, so it must be noon.";
|
||||
String prompt =
|
||||
"The sun is shining brightly and is directly overhead at the zenith, casting my"
|
||||
+ " shadow over my foot, so it must be noon.";
|
||||
|
||||
Map<String, Object> format = new HashMap<>();
|
||||
format.put("type", "object");
|
||||
format.put("properties", new HashMap<String, Object>() {
|
||||
{
|
||||
put("isNoon", new HashMap<String, Object>() {
|
||||
format.put(
|
||||
"properties",
|
||||
new HashMap<String, Object>() {
|
||||
{
|
||||
put("type", "boolean");
|
||||
put(
|
||||
"isNoon",
|
||||
new HashMap<String, Object>() {
|
||||
{
|
||||
put("type", "boolean");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
format.put("required", List.of("isNoon"));
|
||||
|
||||
OllamaResult result = api.generate(model, prompt, format);
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.samples;
|
||||
|
||||
import io.github.ollama4j.tools.annotations.ToolProperty;
|
||||
import io.github.ollama4j.tools.annotations.ToolSpec;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class AnnotatedTool {
|
||||
|
||||
@ToolSpec(desc = "Computes the most important constant all around the globe!")
|
||||
public String computeImportantConstant(@ToolProperty(name = "noOfDigits", desc = "Number of digits that shall be returned") Integer noOfDigits) {
|
||||
public String computeImportantConstant(
|
||||
@ToolProperty(name = "noOfDigits", desc = "Number of digits that shall be returned")
|
||||
Integer noOfDigits) {
|
||||
return BigDecimal.valueOf((long) (Math.random() * 1000000L), noOfDigits).toString();
|
||||
}
|
||||
|
||||
@ToolSpec(desc = "Says hello to a friend!")
|
||||
public String sayHello(@ToolProperty(name = "name", desc = "Name of the friend") String name, @ToolProperty(name = "numberOfHearts", desc = "number of heart emojis that should be used", required = false) Integer numberOfHearts) {
|
||||
public String sayHello(
|
||||
@ToolProperty(name = "name", desc = "Name of the friend") String name,
|
||||
@ToolProperty(
|
||||
name = "numberOfHearts",
|
||||
desc = "number of heart emojis that should be used",
|
||||
required = false)
|
||||
Integer numberOfHearts) {
|
||||
String hearts = numberOfHearts != null ? "♡".repeat(numberOfHearts) : "";
|
||||
return "Hello, " + name + "! " + hearts;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.tools.annotations.OllamaToolService;
|
||||
import io.github.ollama4j.tools.annotations.ToolProperty;
|
||||
import io.github.ollama4j.tools.annotations.ToolSpec;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestAnnotations {
|
||||
|
||||
@OllamaToolService(providers = {SampleProvider.class})
|
||||
static class SampleToolService {
|
||||
}
|
||||
static class SampleToolService {}
|
||||
|
||||
static class SampleProvider {
|
||||
@ToolSpec(name = "sum", desc = "adds two numbers")
|
||||
public int sum(@ToolProperty(name = "a", desc = "first addend") int a,
|
||||
@ToolProperty(name = "b", desc = "second addend", required = false) int b) {
|
||||
public int sum(
|
||||
@ToolProperty(name = "a", desc = "first addend") int a,
|
||||
@ToolProperty(name = "b", desc = "second addend", required = false) int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
||||
@@ -28,7 +35,7 @@ class TestAnnotations {
|
||||
void testOllamaToolServiceProvidersPresent() throws Exception {
|
||||
OllamaToolService ann = SampleToolService.class.getAnnotation(OllamaToolService.class);
|
||||
assertNotNull(ann);
|
||||
assertArrayEquals(new Class<?>[]{SampleProvider.class}, ann.providers());
|
||||
assertArrayEquals(new Class<?>[] {SampleProvider.class}, ann.providers());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.github.ollama4j.models.request.BasicAuth;
|
||||
import io.github.ollama4j.models.request.BearerAuth;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TestAuth {
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -8,8 +18,6 @@ import io.github.ollama4j.utils.BooleanToJsonFormatFlagSerializer;
|
||||
import io.github.ollama4j.utils.Utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class TestBooleanToJsonFormatFlagSerializer {
|
||||
|
||||
static class Holder {
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.github.ollama4j.utils.FileToBase64Serializer;
|
||||
import io.github.ollama4j.utils.Utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestFileToBase64Serializer {
|
||||
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import io.github.ollama4j.OllamaAPI;
|
||||
import io.github.ollama4j.exceptions.OllamaBaseException;
|
||||
import io.github.ollama4j.exceptions.RoleNotFoundException;
|
||||
@@ -12,18 +24,13 @@ import io.github.ollama4j.models.response.OllamaAsyncResultStreamer;
|
||||
import io.github.ollama4j.models.response.OllamaResult;
|
||||
import io.github.ollama4j.types.OllamaModelType;
|
||||
import io.github.ollama4j.utils.OptionsBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
class TestMockedAPIs {
|
||||
@Test
|
||||
@@ -54,7 +61,12 @@ class TestMockedAPIs {
|
||||
@Test
|
||||
void testCreateModel() {
|
||||
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
|
||||
CustomModelRequest customModelRequest = CustomModelRequest.builder().model("mario").from("llama3.2:latest").system("You are Mario from Super Mario Bros.").build();
|
||||
CustomModelRequest customModelRequest =
|
||||
CustomModelRequest.builder()
|
||||
.model("mario")
|
||||
.from("llama3.2:latest")
|
||||
.system("You are Mario from Super Mario Bros.")
|
||||
.build();
|
||||
try {
|
||||
doNothing().when(ollamaAPI).createModel(customModelRequest);
|
||||
ollamaAPI.createModel(customModelRequest);
|
||||
@@ -128,7 +140,8 @@ class TestMockedAPIs {
|
||||
String model = OllamaModelType.LLAMA2;
|
||||
List<String> inputs = List.of("some prompt text");
|
||||
try {
|
||||
when(ollamaAPI.embed(new OllamaEmbedRequestModel(model, inputs))).thenReturn(new OllamaEmbedResponseModel());
|
||||
when(ollamaAPI.embed(new OllamaEmbedRequestModel(model, inputs)))
|
||||
.thenReturn(new OllamaEmbedResponseModel());
|
||||
ollamaAPI.embed(new OllamaEmbedRequestModel(model, inputs));
|
||||
verify(ollamaAPI, times(1)).embed(new OllamaEmbedRequestModel(model, inputs));
|
||||
} catch (IOException | OllamaBaseException | InterruptedException e) {
|
||||
@@ -146,7 +159,8 @@ class TestMockedAPIs {
|
||||
when(ollamaAPI.generate(model, prompt, false, false, optionsBuilder.build()))
|
||||
.thenReturn(new OllamaResult("", "", 0, 200));
|
||||
ollamaAPI.generate(model, prompt, false, false, optionsBuilder.build());
|
||||
verify(ollamaAPI, times(1)).generate(model, prompt, false, false, optionsBuilder.build());
|
||||
verify(ollamaAPI, times(1))
|
||||
.generate(model, prompt, false, false, optionsBuilder.build());
|
||||
} catch (IOException | OllamaBaseException | InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -159,13 +173,28 @@ class TestMockedAPIs {
|
||||
String prompt = "some prompt text";
|
||||
try {
|
||||
when(ollamaAPI.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null))
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null))
|
||||
.thenReturn(new OllamaResult("", "", 0, 200));
|
||||
ollamaAPI.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null);
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null);
|
||||
verify(ollamaAPI, times(1))
|
||||
.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null);
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -178,13 +207,28 @@ class TestMockedAPIs {
|
||||
String prompt = "some prompt text";
|
||||
try {
|
||||
when(ollamaAPI.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null))
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null))
|
||||
.thenReturn(new OllamaResult("", "", 0, 200));
|
||||
ollamaAPI.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null);
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null);
|
||||
verify(ollamaAPI, times(1))
|
||||
.generateWithImages(
|
||||
model, prompt, Collections.emptyList(), new OptionsBuilder().build(), null, null);
|
||||
model,
|
||||
prompt,
|
||||
Collections.emptyList(),
|
||||
new OptionsBuilder().build(),
|
||||
null,
|
||||
null);
|
||||
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -229,7 +273,8 @@ class TestMockedAPIs {
|
||||
OllamaAPI ollamaAPI = mock(OllamaAPI.class);
|
||||
String roleName = "non-existing-role";
|
||||
try {
|
||||
when(ollamaAPI.getRole(roleName)).thenThrow(new RoleNotFoundException("Role not found"));
|
||||
when(ollamaAPI.getRole(roleName))
|
||||
.thenThrow(new RoleNotFoundException("Role not found"));
|
||||
} catch (RoleNotFoundException exception) {
|
||||
throw new RuntimeException("Failed to run test: testGetRoleNotFound");
|
||||
}
|
||||
|
||||
@@ -1,23 +1,33 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessage;
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TestOllamaChatMessage {
|
||||
|
||||
@Test
|
||||
void testToStringProducesJson() {
|
||||
OllamaChatMessage msg = new OllamaChatMessage(OllamaChatMessageRole.USER, "hello", null, null, null);
|
||||
OllamaChatMessage msg =
|
||||
new OllamaChatMessage(OllamaChatMessageRole.USER, "hello", null, null, null);
|
||||
String json = msg.toString();
|
||||
JSONObject obj = new JSONObject(json);
|
||||
assertEquals("user", obj.getString("role"));
|
||||
assertEquals("hello", obj.getString("content"));
|
||||
assertTrue(obj.has("tool_calls"));
|
||||
// thinking and images may or may not be present depending on null handling, just ensure no exception
|
||||
// thinking and images may or may not be present depending on null handling, just ensure no
|
||||
// exception
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.exceptions.RoleNotFoundException;
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestOllamaChatMessageRole {
|
||||
|
||||
@@ -33,12 +40,14 @@ class TestOllamaChatMessageRole {
|
||||
void testCustomRoleCreationAndLookup() throws Exception {
|
||||
OllamaChatMessageRole custom = OllamaChatMessageRole.newCustomRole("myrole");
|
||||
assertEquals("myrole", custom.toString());
|
||||
// custom roles are registered globally (per current implementation), so lookup should succeed
|
||||
// custom roles are registered globally (per current implementation), so lookup should
|
||||
// succeed
|
||||
assertSame(custom, OllamaChatMessageRole.getRole("myrole"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRoleThrowsOnUnknown() {
|
||||
assertThrows(RoleNotFoundException.class, () -> OllamaChatMessageRole.getRole("does-not-exist"));
|
||||
assertThrows(
|
||||
RoleNotFoundException.class, () -> OllamaChatMessageRole.getRole("does-not-exist"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessage;
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
|
||||
import io.github.ollama4j.models.chat.OllamaChatRequest;
|
||||
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestOllamaChatRequestBuilder {
|
||||
|
||||
@Test
|
||||
void testResetClearsMessagesButKeepsModelAndThink() {
|
||||
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance("my-model")
|
||||
.withThinking(true)
|
||||
.withMessage(OllamaChatMessageRole.USER, "first");
|
||||
OllamaChatRequestBuilder builder =
|
||||
OllamaChatRequestBuilder.getInstance("my-model")
|
||||
.withThinking(true)
|
||||
.withMessage(OllamaChatMessageRole.USER, "first");
|
||||
|
||||
OllamaChatRequest beforeReset = builder.build();
|
||||
assertEquals("my-model", beforeReset.getModel());
|
||||
@@ -33,18 +41,23 @@ class TestOllamaChatRequestBuilder {
|
||||
|
||||
@Test
|
||||
void testImageUrlFailuresAreIgnoredAndDoNotBreakBuild() {
|
||||
// Provide a syntactically invalid URL, but catch the expected exception to verify builder robustness
|
||||
// Provide a syntactically invalid URL, but catch the expected exception to verify builder
|
||||
// robustness
|
||||
OllamaChatRequestBuilder builder = OllamaChatRequestBuilder.getInstance("m");
|
||||
try {
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "hi", Collections.emptyList(),
|
||||
builder.withMessage(
|
||||
OllamaChatMessageRole.USER,
|
||||
"hi",
|
||||
Collections.emptyList(),
|
||||
"ht!tp://invalid url \n not a uri");
|
||||
fail("Expected IllegalArgumentException due to malformed URL");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Expected: malformed URL should throw IllegalArgumentException
|
||||
}
|
||||
// The builder should still be usable after the exception
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "hello", Collections.emptyList())
|
||||
.build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "hello", Collections.emptyList())
|
||||
.build();
|
||||
|
||||
assertNotNull(req.getMessages());
|
||||
assertEquals(1, req.getMessages().size());
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.github.ollama4j.utils.OllamaRequestBody;
|
||||
import io.github.ollama4j.utils.Utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.Flow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestOllamaRequestBody {
|
||||
|
||||
@@ -30,29 +37,29 @@ class TestOllamaRequestBody {
|
||||
var publisher = req.getBodyPublisher();
|
||||
|
||||
StringBuilder data = new StringBuilder();
|
||||
publisher.subscribe(new Flow.Subscriber<>() {
|
||||
@Override
|
||||
public void onSubscribe(Flow.Subscription subscription) {
|
||||
subscription.request(Long.MAX_VALUE);
|
||||
}
|
||||
publisher.subscribe(
|
||||
new Flow.Subscriber<>() {
|
||||
@Override
|
||||
public void onSubscribe(Flow.Subscription subscription) {
|
||||
subscription.request(Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(ByteBuffer item) {
|
||||
data.append(StandardCharsets.UTF_8.decode(item));
|
||||
}
|
||||
@Override
|
||||
public void onNext(ByteBuffer item) {
|
||||
data.append(StandardCharsets.UTF_8.decode(item));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
}
|
||||
@Override
|
||||
public void onError(Throwable throwable) {}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
@Override
|
||||
public void onComplete() {}
|
||||
});
|
||||
|
||||
// Trigger the publishing by converting it to a string via the same mapper for determinism
|
||||
String expected = Utils.getObjectMapper().writeValueAsString(req);
|
||||
// Due to asynchronous nature, expected content already delivered synchronously by StringPublisher
|
||||
// Due to asynchronous nature, expected content already delivered synchronously by
|
||||
// StringPublisher
|
||||
assertEquals(expected, data.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.models.response.OllamaResult;
|
||||
import io.github.ollama4j.tools.OllamaToolsResult;
|
||||
import io.github.ollama4j.tools.ToolFunctionCallSpec;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestOllamaToolsResult {
|
||||
|
||||
|
||||
@@ -1,40 +1,48 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.utils.Options;
|
||||
import io.github.ollama4j.utils.OptionsBuilder;
|
||||
import io.github.ollama4j.utils.PromptBuilder;
|
||||
import io.github.ollama4j.utils.Utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestOptionsAndUtils {
|
||||
|
||||
@Test
|
||||
void testOptionsBuilderSetsValues() {
|
||||
Options options = new OptionsBuilder()
|
||||
.setMirostat(1)
|
||||
.setMirostatEta(0.2f)
|
||||
.setMirostatTau(4.5f)
|
||||
.setNumCtx(1024)
|
||||
.setNumGqa(8)
|
||||
.setNumGpu(2)
|
||||
.setNumThread(6)
|
||||
.setRepeatLastN(32)
|
||||
.setRepeatPenalty(1.2f)
|
||||
.setTemperature(0.7f)
|
||||
.setSeed(42)
|
||||
.setStop("STOP")
|
||||
.setTfsZ(1.5f)
|
||||
.setNumPredict(256)
|
||||
.setTopK(50)
|
||||
.setTopP(0.95f)
|
||||
.setMinP(0.05f)
|
||||
.setCustomOption("custom_param", 123)
|
||||
.build();
|
||||
Options options =
|
||||
new OptionsBuilder()
|
||||
.setMirostat(1)
|
||||
.setMirostatEta(0.2f)
|
||||
.setMirostatTau(4.5f)
|
||||
.setNumCtx(1024)
|
||||
.setNumGqa(8)
|
||||
.setNumGpu(2)
|
||||
.setNumThread(6)
|
||||
.setRepeatLastN(32)
|
||||
.setRepeatPenalty(1.2f)
|
||||
.setTemperature(0.7f)
|
||||
.setSeed(42)
|
||||
.setStop("STOP")
|
||||
.setTfsZ(1.5f)
|
||||
.setNumPredict(256)
|
||||
.setTopK(50)
|
||||
.setTopP(0.95f)
|
||||
.setMinP(0.05f)
|
||||
.setCustomOption("custom_param", 123)
|
||||
.build();
|
||||
|
||||
Map<String, Object> map = options.getOptionsMap();
|
||||
assertEquals(1, map.get("mirostat"));
|
||||
@@ -60,19 +68,22 @@ class TestOptionsAndUtils {
|
||||
@Test
|
||||
void testOptionsBuilderRejectsUnsupportedCustomType() {
|
||||
OptionsBuilder builder = new OptionsBuilder();
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.setCustomOption("bad", new Object()));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class, () -> builder.setCustomOption("bad", new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPromptBuilderBuildsExpectedString() {
|
||||
String prompt = new PromptBuilder()
|
||||
.add("Hello")
|
||||
.addLine(", world!")
|
||||
.addSeparator()
|
||||
.add("Continue.")
|
||||
.build();
|
||||
String prompt =
|
||||
new PromptBuilder()
|
||||
.add("Hello")
|
||||
.addLine(", world!")
|
||||
.addSeparator()
|
||||
.add("Continue.")
|
||||
.build();
|
||||
|
||||
String expected = "Hello, world!\n\n--------------------------------------------------\nContinue.";
|
||||
String expected =
|
||||
"Hello, world!\n\n--------------------------------------------------\nContinue.";
|
||||
assertEquals(expected, prompt);
|
||||
}
|
||||
|
||||
@@ -80,7 +91,8 @@ class TestOptionsAndUtils {
|
||||
void testUtilsGetObjectMapperSingletonAndModule() {
|
||||
assertSame(Utils.getObjectMapper(), Utils.getObjectMapper());
|
||||
// Basic serialization sanity check with JavaTimeModule registered
|
||||
assertDoesNotThrow(() -> Utils.getObjectMapper().writeValueAsString(java.time.OffsetDateTime.now()));
|
||||
assertDoesNotThrow(
|
||||
() -> Utils.getObjectMapper().writeValueAsString(java.time.OffsetDateTime.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import io.github.ollama4j.tools.ReflectionalToolFunction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.tools.ReflectionalToolFunction;
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestReflectionalToolFunction {
|
||||
|
||||
@@ -25,7 +32,9 @@ class TestReflectionalToolFunction {
|
||||
@Test
|
||||
void testApplyInvokesMethodWithTypeCasting() throws Exception {
|
||||
SampleToolHolder holder = new SampleToolHolder();
|
||||
Method method = SampleToolHolder.class.getMethod("combine", Integer.class, Boolean.class, BigDecimal.class, String.class);
|
||||
Method method =
|
||||
SampleToolHolder.class.getMethod(
|
||||
"combine", Integer.class, Boolean.class, BigDecimal.class, String.class);
|
||||
|
||||
LinkedHashMap<String, String> propDef = new LinkedHashMap<>();
|
||||
// preserve order to match method parameters
|
||||
@@ -36,12 +45,13 @@ class TestReflectionalToolFunction {
|
||||
|
||||
ReflectionalToolFunction fn = new ReflectionalToolFunction(holder, method, propDef);
|
||||
|
||||
Map<String, Object> args = Map.of(
|
||||
"i", "42",
|
||||
"b", "true",
|
||||
"d", "3.14",
|
||||
"s", 123 // not a string; should be toString()'d by implementation
|
||||
);
|
||||
Map<String, Object> args =
|
||||
Map.of(
|
||||
"i", "42",
|
||||
"b", "true",
|
||||
"d", "3.14",
|
||||
"s", 123 // not a string; should be toString()'d by implementation
|
||||
);
|
||||
|
||||
Object result = fn.apply(args);
|
||||
assertEquals("i=42,b=true,d=3.14,s=123", result);
|
||||
@@ -50,7 +60,9 @@ class TestReflectionalToolFunction {
|
||||
@Test
|
||||
void testTypeCastNullsWhenClassOrValueIsNull() throws Exception {
|
||||
SampleToolHolder holder = new SampleToolHolder();
|
||||
Method method = SampleToolHolder.class.getMethod("combine", Integer.class, Boolean.class, BigDecimal.class, String.class);
|
||||
Method method =
|
||||
SampleToolHolder.class.getMethod(
|
||||
"combine", Integer.class, Boolean.class, BigDecimal.class, String.class);
|
||||
|
||||
LinkedHashMap<String, String> propDef = new LinkedHashMap<>();
|
||||
propDef.put("i", null); // className null -> expect null passed
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.tools.ToolFunction;
|
||||
import io.github.ollama4j.tools.ToolRegistry;
|
||||
import io.github.ollama4j.tools.Tools;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestToolRegistry {
|
||||
|
||||
@@ -16,11 +23,12 @@ class TestToolRegistry {
|
||||
ToolRegistry registry = new ToolRegistry();
|
||||
ToolFunction fn = args -> "ok:" + args.get("x");
|
||||
|
||||
Tools.ToolSpecification spec = Tools.ToolSpecification.builder()
|
||||
.functionName("test")
|
||||
.functionDescription("desc")
|
||||
.toolFunction(fn)
|
||||
.build();
|
||||
Tools.ToolSpecification spec =
|
||||
Tools.ToolSpecification.builder()
|
||||
.functionName("test")
|
||||
.functionDescription("desc")
|
||||
.toolFunction(fn)
|
||||
.build();
|
||||
|
||||
registry.addTool("test", spec);
|
||||
ToolFunction retrieved = registry.getToolFunction("test");
|
||||
|
||||
@@ -1,56 +1,67 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.github.ollama4j.tools.Tools;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TestToolsPromptBuilder {
|
||||
|
||||
@Test
|
||||
void testPromptBuilderIncludesToolsAndPrompt() throws JsonProcessingException {
|
||||
Tools.PromptFuncDefinition.Property cityProp = Tools.PromptFuncDefinition.Property.builder()
|
||||
.type("string")
|
||||
.description("city name")
|
||||
.required(true)
|
||||
.build();
|
||||
Tools.PromptFuncDefinition.Property cityProp =
|
||||
Tools.PromptFuncDefinition.Property.builder()
|
||||
.type("string")
|
||||
.description("city name")
|
||||
.required(true)
|
||||
.build();
|
||||
|
||||
Tools.PromptFuncDefinition.Property unitsProp = Tools.PromptFuncDefinition.Property.builder()
|
||||
.type("string")
|
||||
.description("units")
|
||||
.enumValues(List.of("metric", "imperial"))
|
||||
.required(false)
|
||||
.build();
|
||||
Tools.PromptFuncDefinition.Property unitsProp =
|
||||
Tools.PromptFuncDefinition.Property.builder()
|
||||
.type("string")
|
||||
.description("units")
|
||||
.enumValues(List.of("metric", "imperial"))
|
||||
.required(false)
|
||||
.build();
|
||||
|
||||
Tools.PromptFuncDefinition.Parameters params = Tools.PromptFuncDefinition.Parameters.builder()
|
||||
.type("object")
|
||||
.properties(Map.of("city", cityProp, "units", unitsProp))
|
||||
.build();
|
||||
Tools.PromptFuncDefinition.Parameters params =
|
||||
Tools.PromptFuncDefinition.Parameters.builder()
|
||||
.type("object")
|
||||
.properties(Map.of("city", cityProp, "units", unitsProp))
|
||||
.build();
|
||||
|
||||
Tools.PromptFuncDefinition.PromptFuncSpec spec = Tools.PromptFuncDefinition.PromptFuncSpec.builder()
|
||||
.name("getWeather")
|
||||
.description("Get weather for a city")
|
||||
.parameters(params)
|
||||
.build();
|
||||
Tools.PromptFuncDefinition.PromptFuncSpec spec =
|
||||
Tools.PromptFuncDefinition.PromptFuncSpec.builder()
|
||||
.name("getWeather")
|
||||
.description("Get weather for a city")
|
||||
.parameters(params)
|
||||
.build();
|
||||
|
||||
Tools.PromptFuncDefinition def = Tools.PromptFuncDefinition.builder()
|
||||
.type("function")
|
||||
.function(spec)
|
||||
.build();
|
||||
Tools.PromptFuncDefinition def =
|
||||
Tools.PromptFuncDefinition.builder().type("function").function(spec).build();
|
||||
|
||||
Tools.ToolSpecification toolSpec = Tools.ToolSpecification.builder()
|
||||
.functionName("getWeather")
|
||||
.functionDescription("Get weather for a city")
|
||||
.toolPrompt(def)
|
||||
.build();
|
||||
Tools.ToolSpecification toolSpec =
|
||||
Tools.ToolSpecification.builder()
|
||||
.functionName("getWeather")
|
||||
.functionDescription("Get weather for a city")
|
||||
.toolPrompt(def)
|
||||
.build();
|
||||
|
||||
Tools.PromptBuilder pb = new Tools.PromptBuilder()
|
||||
.withToolSpecification(toolSpec)
|
||||
.withPrompt("Tell me the weather.");
|
||||
Tools.PromptBuilder pb =
|
||||
new Tools.PromptBuilder()
|
||||
.withToolSpecification(toolSpec)
|
||||
.withPrompt("Tell me the weather.");
|
||||
|
||||
String built = pb.build();
|
||||
assertTrue(built.contains("[AVAILABLE_TOOLS]"));
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.ollama4j.utils.Utils;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
public abstract class AbstractSerializationTest<T> {
|
||||
|
||||
protected ObjectMapper mapper = Utils.getObjectMapper();
|
||||
@@ -29,8 +37,7 @@ public abstract class AbstractSerializationTest<T> {
|
||||
}
|
||||
}
|
||||
|
||||
protected void assertEqualsAfterUnmarshalling(T unmarshalledObject,
|
||||
T req) {
|
||||
protected void assertEqualsAfterUnmarshalling(T unmarshalledObject, T req) {
|
||||
assertEquals(req, unmarshalledObject);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
|
||||
|
||||
import io.github.ollama4j.models.chat.OllamaChatMessageRole;
|
||||
import io.github.ollama4j.models.chat.OllamaChatRequest;
|
||||
import io.github.ollama4j.models.chat.OllamaChatRequestBuilder;
|
||||
import io.github.ollama4j.utils.OptionsBuilder;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestChatRequestSerialization extends AbstractSerializationTest<OllamaChatRequest> {
|
||||
|
||||
@@ -26,24 +33,31 @@ public class TestChatRequestSerialization extends AbstractSerializationTest<Olla
|
||||
|
||||
@Test
|
||||
public void testRequestOnlyMandatoryFields() {
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "Some prompt").build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "Some prompt").build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEqualsAfterUnmarshalling(deserialize(jsonRequest, OllamaChatRequest.class), req);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestMultipleMessages() {
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.SYSTEM, "System prompt")
|
||||
.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.SYSTEM, "System prompt")
|
||||
.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEqualsAfterUnmarshalling(deserialize(jsonRequest, OllamaChatRequest.class), req);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestWithMessageAndImage() {
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "Some prompt", Collections.emptyList(),
|
||||
List.of(new File("src/test/resources/dog-on-a-boat.jpg"))).build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(
|
||||
OllamaChatMessageRole.USER,
|
||||
"Some prompt",
|
||||
Collections.emptyList(),
|
||||
List.of(new File("src/test/resources/dog-on-a-boat.jpg")))
|
||||
.build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEqualsAfterUnmarshalling(deserialize(jsonRequest, OllamaChatRequest.class), req);
|
||||
}
|
||||
@@ -51,20 +65,21 @@ public class TestChatRequestSerialization extends AbstractSerializationTest<Olla
|
||||
@Test
|
||||
public void testRequestWithOptions() {
|
||||
OptionsBuilder b = new OptionsBuilder();
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withOptions(b.setMirostat(1).build())
|
||||
.withOptions(b.setTemperature(1L).build())
|
||||
.withOptions(b.setMirostatEta(1L).build())
|
||||
.withOptions(b.setMirostatTau(1L).build())
|
||||
.withOptions(b.setNumGpu(1).build())
|
||||
.withOptions(b.setSeed(1).build())
|
||||
.withOptions(b.setTopK(1).build())
|
||||
.withOptions(b.setTopP(1).build())
|
||||
.withOptions(b.setMinP(1).build())
|
||||
.withOptions(b.setCustomOption("cust_float", 1.0f).build())
|
||||
.withOptions(b.setCustomOption("cust_int", 1).build())
|
||||
.withOptions(b.setCustomOption("cust_str", "custom").build())
|
||||
.build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withOptions(b.setMirostat(1).build())
|
||||
.withOptions(b.setTemperature(1L).build())
|
||||
.withOptions(b.setMirostatEta(1L).build())
|
||||
.withOptions(b.setMirostatTau(1L).build())
|
||||
.withOptions(b.setNumGpu(1).build())
|
||||
.withOptions(b.setSeed(1).build())
|
||||
.withOptions(b.setTopK(1).build())
|
||||
.withOptions(b.setTopP(1).build())
|
||||
.withOptions(b.setMinP(1).build())
|
||||
.withOptions(b.setCustomOption("cust_float", 1.0f).build())
|
||||
.withOptions(b.setCustomOption("cust_int", 1).build())
|
||||
.withOptions(b.setCustomOption("cust_str", "custom").build())
|
||||
.build();
|
||||
|
||||
String jsonRequest = serialize(req);
|
||||
OllamaChatRequest deserializeRequest = deserialize(jsonRequest, OllamaChatRequest.class);
|
||||
@@ -86,17 +101,23 @@ public class TestChatRequestSerialization extends AbstractSerializationTest<Olla
|
||||
@Test
|
||||
public void testRequestWithInvalidCustomOption() {
|
||||
OptionsBuilder b = new OptionsBuilder();
|
||||
assertThrowsExactly(IllegalArgumentException.class, () -> {
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withOptions(b.setCustomOption("cust_obj", new Object()).build())
|
||||
.build();
|
||||
});
|
||||
assertThrowsExactly(
|
||||
IllegalArgumentException.class,
|
||||
() -> {
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withOptions(
|
||||
b.setCustomOption("cust_obj", new Object()).build())
|
||||
.build();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithJsonFormat() {
|
||||
OllamaChatRequest req = builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withGetJsonResponse().build();
|
||||
OllamaChatRequest req =
|
||||
builder.withMessage(OllamaChatMessageRole.USER, "Some prompt")
|
||||
.withGetJsonResponse()
|
||||
.build();
|
||||
|
||||
String jsonRequest = serialize(req);
|
||||
// no jackson deserialization as format property is not boolean ==> omit as deserialization
|
||||
@@ -108,8 +129,7 @@ public class TestChatRequestSerialization extends AbstractSerializationTest<Olla
|
||||
|
||||
@Test
|
||||
public void testWithTemplate() {
|
||||
OllamaChatRequest req = builder.withTemplate("System Template")
|
||||
.build();
|
||||
OllamaChatRequest req = builder.withTemplate("System Template").build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEqualsAfterUnmarshalling(deserialize(jsonRequest, OllamaChatRequest.class), req);
|
||||
}
|
||||
@@ -124,9 +144,10 @@ public class TestChatRequestSerialization extends AbstractSerializationTest<Olla
|
||||
@Test
|
||||
public void testWithKeepAlive() {
|
||||
String expectedKeepAlive = "5m";
|
||||
OllamaChatRequest req = builder.withKeepAlive(expectedKeepAlive)
|
||||
.build();
|
||||
OllamaChatRequest req = builder.withKeepAlive(expectedKeepAlive).build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEquals(deserialize(jsonRequest, OllamaChatRequest.class).getKeepAlive(), expectedKeepAlive);
|
||||
assertEquals(
|
||||
deserialize(jsonRequest, OllamaChatRequest.class).getKeepAlive(),
|
||||
expectedKeepAlive);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.github.ollama4j.models.embeddings.OllamaEmbedRequestBuilder;
|
||||
import io.github.ollama4j.models.embeddings.OllamaEmbedRequestModel;
|
||||
import io.github.ollama4j.utils.OptionsBuilder;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestEmbedRequestSerialization extends AbstractSerializationTest<OllamaEmbedRequestModel> {
|
||||
public class TestEmbedRequestSerialization
|
||||
extends AbstractSerializationTest<OllamaEmbedRequestModel> {
|
||||
|
||||
private OllamaEmbedRequestBuilder builder;
|
||||
|
||||
@@ -21,17 +30,18 @@ public class TestEmbedRequestSerialization extends AbstractSerializationTest<Oll
|
||||
public void testRequestOnlyMandatoryFields() {
|
||||
OllamaEmbedRequestModel req = builder.build();
|
||||
String jsonRequest = serialize(req);
|
||||
assertEqualsAfterUnmarshalling(deserialize(jsonRequest, OllamaEmbedRequestModel.class), req);
|
||||
assertEqualsAfterUnmarshalling(
|
||||
deserialize(jsonRequest, OllamaEmbedRequestModel.class), req);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestWithOptions() {
|
||||
OptionsBuilder b = new OptionsBuilder();
|
||||
OllamaEmbedRequestModel req = builder
|
||||
.withOptions(b.setMirostat(1).build()).build();
|
||||
OllamaEmbedRequestModel req = builder.withOptions(b.setMirostat(1).build()).build();
|
||||
|
||||
String jsonRequest = serialize(req);
|
||||
OllamaEmbedRequestModel deserializeRequest = deserialize(jsonRequest, OllamaEmbedRequestModel.class);
|
||||
OllamaEmbedRequestModel deserializeRequest =
|
||||
deserialize(jsonRequest, OllamaEmbedRequestModel.class);
|
||||
assertEqualsAfterUnmarshalling(deserializeRequest, req);
|
||||
assertEquals(1, deserializeRequest.getOptions().get("mirostat"));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.github.ollama4j.models.generate.OllamaGenerateRequest;
|
||||
import io.github.ollama4j.models.generate.OllamaGenerateRequestBuilder;
|
||||
import io.github.ollama4j.utils.OptionsBuilder;
|
||||
@@ -7,9 +17,8 @@ import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestGenerateRequestSerialization extends AbstractSerializationTest<OllamaGenerateRequest> {
|
||||
public class TestGenerateRequestSerialization
|
||||
extends AbstractSerializationTest<OllamaGenerateRequest> {
|
||||
|
||||
private OllamaGenerateRequestBuilder builder;
|
||||
|
||||
@@ -33,15 +42,15 @@ public class TestGenerateRequestSerialization extends AbstractSerializationTest<
|
||||
builder.withPrompt("Some prompt").withOptions(b.setMirostat(1).build()).build();
|
||||
|
||||
String jsonRequest = serialize(req);
|
||||
OllamaGenerateRequest deserializeRequest = deserialize(jsonRequest, OllamaGenerateRequest.class);
|
||||
OllamaGenerateRequest deserializeRequest =
|
||||
deserialize(jsonRequest, OllamaGenerateRequest.class);
|
||||
assertEqualsAfterUnmarshalling(deserializeRequest, req);
|
||||
assertEquals(1, deserializeRequest.getOptions().get("mirostat"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithJsonFormat() {
|
||||
OllamaGenerateRequest req =
|
||||
builder.withPrompt("Some prompt").withGetJsonResponse().build();
|
||||
OllamaGenerateRequest req = builder.withPrompt("Some prompt").withGetJsonResponse().build();
|
||||
|
||||
String jsonRequest = serialize(req);
|
||||
System.out.printf(jsonRequest);
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.models.response.ModelPullResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test serialization and deserialization of ModelPullResponse,
|
||||
* This test verifies that the ModelPullResponse class can properly parse
|
||||
* error responses from Ollama server that return HTTP 200 with error messages
|
||||
* in the JSON body.
|
||||
*/
|
||||
public class TestModelPullResponseSerialization extends AbstractSerializationTest<ModelPullResponse> {
|
||||
public class TestModelPullResponseSerialization
|
||||
extends AbstractSerializationTest<ModelPullResponse> {
|
||||
|
||||
/**
|
||||
* Test the specific error case reported in GitHub issue #138.
|
||||
@@ -20,7 +29,16 @@ public class TestModelPullResponseSerialization extends AbstractSerializationTes
|
||||
@Test
|
||||
public void testDeserializationWithErrorFromGitHubIssue138() {
|
||||
// This is the exact error JSON from GitHub issue #138
|
||||
String errorJson = "{\"error\":\"pull model manifest: 412: \\n\\nThe model you are attempting to pull requires a newer version of Ollama.\\n\\nPlease download the latest version at:\\n\\n\\thttps://ollama.com/download\\n\\n\"}";
|
||||
String errorJson =
|
||||
"{\"error\":\"pull model manifest: 412: \\n"
|
||||
+ "\\n"
|
||||
+ "The model you are attempting to pull requires a newer version of Ollama.\\n"
|
||||
+ "\\n"
|
||||
+ "Please download the latest version at:\\n"
|
||||
+ "\\n"
|
||||
+ "\\thttps://ollama.com/download\\n"
|
||||
+ "\\n"
|
||||
+ "\"}";
|
||||
|
||||
ModelPullResponse response = deserialize(errorJson, ModelPullResponse.class);
|
||||
|
||||
@@ -59,7 +77,9 @@ public class TestModelPullResponseSerialization extends AbstractSerializationTes
|
||||
*/
|
||||
@Test
|
||||
public void testDeserializationWithProgressFields() {
|
||||
String progressJson = "{\"status\":\"pulling digestname\",\"digest\":\"sha256:abc123\",\"total\":2142590208,\"completed\":241970}";
|
||||
String progressJson =
|
||||
"{\"status\":\"pulling"
|
||||
+ " digestname\",\"digest\":\"sha256:abc123\",\"total\":2142590208,\"completed\":241970}";
|
||||
|
||||
ModelPullResponse response = deserialize(progressJson, ModelPullResponse.class);
|
||||
|
||||
@@ -95,7 +115,8 @@ public class TestModelPullResponseSerialization extends AbstractSerializationTes
|
||||
*/
|
||||
@Test
|
||||
public void testDeserializationWithAllFields() {
|
||||
String completeJson = "{\"status\":\"downloading\",\"digest\":\"sha256:def456\",\"total\":1000000,\"completed\":500000,\"error\":null}";
|
||||
String completeJson =
|
||||
"{\"status\":\"downloading\",\"digest\":\"sha256:def456\",\"total\":1000000,\"completed\":500000,\"error\":null}";
|
||||
|
||||
ModelPullResponse response = deserialize(completeJson, ModelPullResponse.class);
|
||||
|
||||
@@ -115,7 +136,9 @@ public class TestModelPullResponseSerialization extends AbstractSerializationTes
|
||||
@Test
|
||||
public void testDeserializationWithUnknownFields() {
|
||||
// Test that unknown fields are ignored due to @JsonIgnoreProperties(ignoreUnknown = true)
|
||||
String jsonWithUnknownFields = "{\"status\":\"pulling\",\"unknown_field\":\"should_be_ignored\",\"error\":\"test error\",\"another_unknown\":123,\"nested_unknown\":{\"key\":\"value\"}}";
|
||||
String jsonWithUnknownFields =
|
||||
"{\"status\":\"pulling\",\"unknown_field\":\"should_be_ignored\",\"error\":\"test"
|
||||
+ " error\",\"another_unknown\":123,\"nested_unknown\":{\"key\":\"value\"}}";
|
||||
|
||||
ModelPullResponse response = deserialize(jsonWithUnknownFields, ModelPullResponse.class);
|
||||
|
||||
@@ -227,21 +250,25 @@ public class TestModelPullResponseSerialization extends AbstractSerializationTes
|
||||
String errorJson = "{\"error\":\"test error\"}";
|
||||
ModelPullResponse errorResponse = deserialize(errorJson, ModelPullResponse.class);
|
||||
|
||||
assertTrue(errorResponse.getError() != null && !errorResponse.getError().trim().isEmpty(),
|
||||
assertTrue(
|
||||
errorResponse.getError() != null && !errorResponse.getError().trim().isEmpty(),
|
||||
"Error response should trigger error handling logic");
|
||||
|
||||
// Normal case - should not trigger error handling
|
||||
String normalJson = "{\"status\":\"pulling\"}";
|
||||
ModelPullResponse normalResponse = deserialize(normalJson, ModelPullResponse.class);
|
||||
|
||||
assertFalse(normalResponse.getError() != null && !normalResponse.getError().trim().isEmpty(),
|
||||
assertFalse(
|
||||
normalResponse.getError() != null && !normalResponse.getError().trim().isEmpty(),
|
||||
"Normal response should not trigger error handling logic");
|
||||
|
||||
// Empty error case - should not trigger error handling
|
||||
String emptyErrorJson = "{\"error\":\"\",\"status\":\"pulling\"}";
|
||||
ModelPullResponse emptyErrorResponse = deserialize(emptyErrorJson, ModelPullResponse.class);
|
||||
|
||||
assertFalse(emptyErrorResponse.getError() != null && !emptyErrorResponse.getError().trim().isEmpty(),
|
||||
assertFalse(
|
||||
emptyErrorResponse.getError() != null
|
||||
&& !emptyErrorResponse.getError().trim().isEmpty(),
|
||||
"Empty error response should not trigger error handling logic");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,45 @@
|
||||
/*
|
||||
* Ollama4j - Java library for interacting with Ollama server.
|
||||
* Copyright (c) 2025 Amith Koujalgi and contributors.
|
||||
*
|
||||
* Licensed under the MIT License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
*
|
||||
*/
|
||||
package io.github.ollama4j.unittests.jackson;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import io.github.ollama4j.models.response.Model;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestModelRequestSerialization extends AbstractSerializationTest<Model> {
|
||||
|
||||
@Test
|
||||
public void testDeserializationOfModelResponseWithOffsetTime() {
|
||||
String serializedTestStringWithOffsetTime = "{\n" +
|
||||
" \"name\": \"codellama:13b\",\n" +
|
||||
" \"modified_at\": \"2023-11-04T14:56:49.277302595-07:00\",\n" +
|
||||
" \"size\": 7365960935,\n" +
|
||||
" \"digest\": \"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697\",\n" +
|
||||
" \"details\": {\n" +
|
||||
" \"format\": \"gguf\",\n" +
|
||||
" \"family\": \"llama\",\n" +
|
||||
" \"families\": null,\n" +
|
||||
" \"parameter_size\": \"13B\",\n" +
|
||||
" \"quantization_level\": \"Q4_0\"\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
String serializedTestStringWithOffsetTime =
|
||||
"{\n"
|
||||
+ " \"name\": \"codellama:13b\",\n"
|
||||
+ " \"modified_at\": \"2023-11-04T14:56:49.277302595-07:00\",\n"
|
||||
+ " \"size\": 7365960935,\n"
|
||||
+ " \"digest\":"
|
||||
+ " \"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697\",\n"
|
||||
+ " \"details\": {\n"
|
||||
+ " \"format\": \"gguf\",\n"
|
||||
+ " \"family\": \"llama\",\n"
|
||||
+ " \"families\": null,\n"
|
||||
+ " \"parameter_size\": \"13B\",\n"
|
||||
+ " \"quantization_level\": \"Q4_0\"\n"
|
||||
+ " }\n"
|
||||
+ "}";
|
||||
Model model = deserialize(serializedTestStringWithOffsetTime, Model.class);
|
||||
assertNotNull(model);
|
||||
assertEquals("codellama:13b", model.getName());
|
||||
assertEquals("2023-11-04T21:56:49.277302595Z", model.getModifiedAt().toString());
|
||||
assertEquals(7365960935L, model.getSize());
|
||||
assertEquals("9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697", model.getDigest());
|
||||
assertEquals(
|
||||
"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697",
|
||||
model.getDigest());
|
||||
assertNotNull(model.getModelMeta());
|
||||
assertEquals("gguf", model.getModelMeta().getFormat());
|
||||
assertEquals("llama", model.getModelMeta().getFamily());
|
||||
@@ -38,25 +50,29 @@ public class TestModelRequestSerialization extends AbstractSerializationTest<Mod
|
||||
|
||||
@Test
|
||||
public void testDeserializationOfModelResponseWithZuluTime() {
|
||||
String serializedTestStringWithZuluTimezone = "{\n" +
|
||||
" \"name\": \"codellama:13b\",\n" +
|
||||
" \"modified_at\": \"2023-11-04T14:56:49.277302595Z\",\n" +
|
||||
" \"size\": 7365960935,\n" +
|
||||
" \"digest\": \"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697\",\n" +
|
||||
" \"details\": {\n" +
|
||||
" \"format\": \"gguf\",\n" +
|
||||
" \"family\": \"llama\",\n" +
|
||||
" \"families\": null,\n" +
|
||||
" \"parameter_size\": \"13B\",\n" +
|
||||
" \"quantization_level\": \"Q4_0\"\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
String serializedTestStringWithZuluTimezone =
|
||||
"{\n"
|
||||
+ " \"name\": \"codellama:13b\",\n"
|
||||
+ " \"modified_at\": \"2023-11-04T14:56:49.277302595Z\",\n"
|
||||
+ " \"size\": 7365960935,\n"
|
||||
+ " \"digest\":"
|
||||
+ " \"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697\",\n"
|
||||
+ " \"details\": {\n"
|
||||
+ " \"format\": \"gguf\",\n"
|
||||
+ " \"family\": \"llama\",\n"
|
||||
+ " \"families\": null,\n"
|
||||
+ " \"parameter_size\": \"13B\",\n"
|
||||
+ " \"quantization_level\": \"Q4_0\"\n"
|
||||
+ " }\n"
|
||||
+ "}";
|
||||
Model model = deserialize(serializedTestStringWithZuluTimezone, Model.class);
|
||||
assertNotNull(model);
|
||||
assertEquals("codellama:13b", model.getName());
|
||||
assertEquals("2023-11-04T14:56:49.277302595Z", model.getModifiedAt().toString());
|
||||
assertEquals(7365960935L, model.getSize());
|
||||
assertEquals("9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697", model.getDigest());
|
||||
assertEquals(
|
||||
"9f438cb9cd581fc025612d27f7c1a6669ff83a8bb0ed86c94fcf4c5440555697",
|
||||
model.getDigest());
|
||||
assertNotNull(model.getModelMeta());
|
||||
assertEquals("gguf", model.getModelMeta().getFormat());
|
||||
assertEquals("llama", model.getModelMeta().getFamily());
|
||||
@@ -64,5 +80,4 @@ public class TestModelRequestSerialization extends AbstractSerializationTest<Mod
|
||||
assertEquals("13B", model.getModelMeta().getParameterSize());
|
||||
assertEquals("Q4_0", model.getModelMeta().getQuantizationLevel());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user