Ollama4j
A Java library (wrapper/binding) for Ollama server.
Loading...
Searching...
No Matches
OllamaEndpointCaller.java
Go to the documentation of this file.
1package io.github.ollama4j.models.request;
2
3import io.github.ollama4j.OllamaAPI;
4import io.github.ollama4j.exceptions.OllamaBaseException;
5import io.github.ollama4j.models.response.OllamaErrorResponse;
6import io.github.ollama4j.models.response.OllamaResult;
7import io.github.ollama4j.utils.OllamaRequestBody;
8import io.github.ollama4j.utils.Utils;
9import org.slf4j.Logger;
10import org.slf4j.LoggerFactory;
11
12import java.io.BufferedReader;
13import java.io.IOException;
14import java.io.InputStream;
15import java.io.InputStreamReader;
16import java.net.URI;
17import java.net.http.HttpClient;
18import java.net.http.HttpRequest;
19import java.net.http.HttpResponse;
20import java.nio.charset.StandardCharsets;
21import java.time.Duration;
22import java.util.Base64;
23
27public abstract class OllamaEndpointCaller {
28
29 private static final Logger LOG = LoggerFactory.getLogger(OllamaAPI.class);
30
31 private String host;
32 private BasicAuth basicAuth;
33 private long requestTimeoutSeconds;
34 private boolean verbose;
35
36 public OllamaEndpointCaller(String host, BasicAuth basicAuth, long requestTimeoutSeconds, boolean verbose) {
37 this.host = host;
38 this.basicAuth = basicAuth;
39 this.requestTimeoutSeconds = requestTimeoutSeconds;
40 this.verbose = verbose;
41 }
42
43 protected abstract String getEndpointSuffix();
44
45 protected abstract boolean parseResponseAndAddToBuffer(String line, StringBuilder responseBuffer);
46
47
57 public OllamaResult callSync(OllamaRequestBody body) throws OllamaBaseException, IOException, InterruptedException {
58 // Create Request
59 long startTime = System.currentTimeMillis();
60 HttpClient httpClient = HttpClient.newHttpClient();
61 URI uri = URI.create(this.host + getEndpointSuffix());
62 HttpRequest.Builder requestBuilder =
63 getRequestBuilderDefault(uri)
64 .POST(
65 body.getBodyPublisher());
66 HttpRequest request = requestBuilder.build();
67 if (this.verbose) LOG.info("Asking model: " + body.toString());
68 HttpResponse<InputStream> response =
69 httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
70
71 int statusCode = response.statusCode();
72 InputStream responseBodyStream = response.body();
73 StringBuilder responseBuffer = new StringBuilder();
74 try (BufferedReader reader =
75 new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8))) {
76 String line;
77 while ((line = reader.readLine()) != null) {
78 if (statusCode == 404) {
79 LOG.warn("Status code: 404 (Not Found)");
80 OllamaErrorResponse ollamaResponseModel =
81 Utils.getObjectMapper().readValue(line, OllamaErrorResponse.class);
82 responseBuffer.append(ollamaResponseModel.getError());
83 } else if (statusCode == 401) {
84 LOG.warn("Status code: 401 (Unauthorized)");
85 OllamaErrorResponse ollamaResponseModel =
87 .readValue("{\"error\":\"Unauthorized\"}", OllamaErrorResponse.class);
88 responseBuffer.append(ollamaResponseModel.getError());
89 } else if (statusCode == 400) {
90 LOG.warn("Status code: 400 (Bad Request)");
91 OllamaErrorResponse ollamaResponseModel = Utils.getObjectMapper().readValue(line,
93 responseBuffer.append(ollamaResponseModel.getError());
94 } else {
95 boolean finished = parseResponseAndAddToBuffer(line, responseBuffer);
96 if (finished) {
97 break;
98 }
99 }
100 }
101 }
102
103 if (statusCode != 200) {
104 LOG.error("Status code " + statusCode);
105 throw new OllamaBaseException(responseBuffer.toString());
106 } else {
107 long endTime = System.currentTimeMillis();
108 OllamaResult ollamaResult =
109 new OllamaResult(responseBuffer.toString().trim(), endTime - startTime, statusCode);
110 if (verbose) LOG.info("Model response: " + ollamaResult);
111 return ollamaResult;
112 }
113 }
114
121 private HttpRequest.Builder getRequestBuilderDefault(URI uri) {
122 HttpRequest.Builder requestBuilder =
123 HttpRequest.newBuilder(uri)
124 .header("Content-Type", "application/json")
125 .timeout(Duration.ofSeconds(this.requestTimeoutSeconds));
126 if (isBasicAuthCredentialsSet()) {
127 requestBuilder.header("Authorization", getBasicAuthHeaderValue());
128 }
129 return requestBuilder;
130 }
131
137 private String getBasicAuthHeaderValue() {
138 String credentialsToEncode = this.basicAuth.getUsername() + ":" + this.basicAuth.getPassword();
139 return "Basic " + Base64.getEncoder().encodeToString(credentialsToEncode.getBytes());
140 }
141
147 private boolean isBasicAuthCredentialsSet() {
148 return this.basicAuth != null;
149 }
150
151}
OllamaEndpointCaller(String host, BasicAuth basicAuth, long requestTimeoutSeconds, boolean verbose)
abstract boolean parseResponseAndAddToBuffer(String line, StringBuilder responseBuffer)
static ObjectMapper getObjectMapper()
Definition Utils.java:17