Refactor logging in OllamaAPI and ConsoleOutputStreamHandler

- Changed logger variable names from 'logger' to 'LOG' for consistency.
- Updated logging statements in OllamaAPI to use the new 'LOG' variable.
- Modified ConsoleOutputStreamHandler to log messages using 'LOG' instead of printing directly to the console.
This commit is contained in:
amithkoujalgi 2025-09-10 18:08:01 +05:30
parent 773cb4af78
commit fdc2e39646
No known key found for this signature in database
GPG Key ID: E29A37746AF94B70
2 changed files with 23 additions and 19 deletions

View File

@ -54,7 +54,7 @@ import java.util.stream.Collectors;
@SuppressWarnings({"DuplicatedCode", "resource"}) @SuppressWarnings({"DuplicatedCode", "resource"})
public class OllamaAPI { public class OllamaAPI {
private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class); private static final Logger LOG = LoggerFactory.getLogger(OllamaAPI.class);
private final String host; private final String host;
private Auth auth; private Auth auth;
@ -112,7 +112,7 @@ public class OllamaAPI {
} else { } else {
this.host = host; this.host = host;
} }
logger.info("Ollama API initialized with host: {}", this.host); LOG.info("Ollama API initialized with host: {}", this.host);
} }
/** /**
@ -450,7 +450,7 @@ public class OllamaAPI {
int attempt = currentRetry + 1; int attempt = currentRetry + 1;
if (attempt < maxRetries) { if (attempt < maxRetries) {
long backoffMillis = baseDelayMillis * (1L << currentRetry); long backoffMillis = baseDelayMillis * (1L << currentRetry);
logger.error("Failed to pull model {}, retrying in {}s... (attempt {}/{})", LOG.error("Failed to pull model {}, retrying in {}s... (attempt {}/{})",
modelName, backoffMillis / 1000, attempt, maxRetries); modelName, backoffMillis / 1000, attempt, maxRetries);
try { try {
Thread.sleep(backoffMillis); Thread.sleep(backoffMillis);
@ -459,7 +459,7 @@ public class OllamaAPI {
throw ie; throw ie;
} }
} else { } else {
logger.error("Failed to pull model {} after {} attempts, no more retries.", modelName, maxRetries); LOG.error("Failed to pull model {} after {} attempts, no more retries.", modelName, maxRetries);
} }
} }
@ -489,19 +489,19 @@ public class OllamaAPI {
} }
if (modelPullResponse.getStatus() != null) { if (modelPullResponse.getStatus() != null) {
logger.info("{}: {}", modelName, modelPullResponse.getStatus()); LOG.info("{}: {}", modelName, modelPullResponse.getStatus());
// Check if status is "success" and set success flag to true. // Check if status is "success" and set success flag to true.
if ("success".equalsIgnoreCase(modelPullResponse.getStatus())) { if ("success".equalsIgnoreCase(modelPullResponse.getStatus())) {
success = true; success = true;
} }
} }
} else { } else {
logger.error("Received null response for model pull."); LOG.error("Received null response for model pull.");
} }
} }
} }
if (!success) { if (!success) {
logger.error("Model pull failed or returned invalid status."); LOG.error("Model pull failed or returned invalid status.");
throw new OllamaBaseException("Model pull failed or returned invalid status."); throw new OllamaBaseException("Model pull failed or returned invalid status.");
} }
if (statusCode != 200) { if (statusCode != 200) {
@ -610,7 +610,7 @@ public class OllamaAPI {
if (responseString.contains("error")) { if (responseString.contains("error")) {
throw new OllamaBaseException(responseString); throw new OllamaBaseException(responseString);
} }
logger.debug(responseString); LOG.debug(responseString);
} }
/** /**
@ -646,7 +646,7 @@ public class OllamaAPI {
if (responseString.contains("error")) { if (responseString.contains("error")) {
throw new OllamaBaseException(responseString); throw new OllamaBaseException(responseString);
} }
logger.debug(responseString); LOG.debug(responseString);
} }
/** /**
@ -678,7 +678,7 @@ public class OllamaAPI {
if (responseString.contains("error")) { if (responseString.contains("error")) {
throw new OllamaBaseException(responseString); throw new OllamaBaseException(responseString);
} }
logger.debug(responseString); LOG.debug(responseString);
} }
/** /**
@ -949,9 +949,9 @@ public class OllamaAPI {
try { try {
String prettyJson = Utils.getObjectMapper().writerWithDefaultPrettyPrinter() String prettyJson = Utils.getObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(Utils.getObjectMapper().readValue(jsonData, Object.class)); .writeValueAsString(Utils.getObjectMapper().readValue(jsonData, Object.class));
logger.debug("Asking model:\n{}", prettyJson); LOG.debug("Asking model:\n{}", prettyJson);
} catch (Exception e) { } catch (Exception e) {
logger.debug("Asking model: {}", jsonData); LOG.debug("Asking model: {}", jsonData);
} }
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
@ -974,10 +974,10 @@ public class OllamaAPI {
ollamaResult.setPromptEvalDuration(structuredResult.getPromptEvalDuration()); ollamaResult.setPromptEvalDuration(structuredResult.getPromptEvalDuration());
ollamaResult.setEvalCount(structuredResult.getEvalCount()); ollamaResult.setEvalCount(structuredResult.getEvalCount());
ollamaResult.setEvalDuration(structuredResult.getEvalDuration()); ollamaResult.setEvalDuration(structuredResult.getEvalDuration());
logger.debug("Model response:\n{}", ollamaResult); LOG.debug("Model response:\n{}", ollamaResult);
return ollamaResult; return ollamaResult;
} else { } else {
logger.debug("Model response:\n{}", LOG.debug("Model response:\n{}",
Utils.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(responseBody)); Utils.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(responseBody));
throw new OllamaBaseException(statusCode + " - " + responseBody); throw new OllamaBaseException(statusCode + " - " + responseBody);
} }
@ -1031,7 +1031,7 @@ public class OllamaAPI {
// Try to parse the string to see if it's a valid JSON // Try to parse the string to see if it's a valid JSON
objectMapper.readTree(toolsResponse); objectMapper.readTree(toolsResponse);
} catch (JsonParseException e) { } catch (JsonParseException e) {
logger.warn("Response from model does not contain any tool calls. Returning the response as is."); LOG.warn("Response from model does not contain any tool calls. Returning the response as is.");
return toolResult; return toolResult;
} }
toolFunctionCallSpecs = objectMapper.readValue(toolsResponse, toolFunctionCallSpecs = objectMapper.readValue(toolsResponse,
@ -1390,7 +1390,7 @@ public class OllamaAPI {
*/ */
public void registerTool(Tools.ToolSpecification toolSpecification) { public void registerTool(Tools.ToolSpecification toolSpecification) {
toolRegistry.addTool(toolSpecification.getFunctionName(), toolSpecification); toolRegistry.addTool(toolSpecification.getFunctionName(), toolSpecification);
logger.debug("Registered tool: {}", toolSpecification.getFunctionName()); LOG.debug("Registered tool: {}", toolSpecification.getFunctionName());
} }
/** /**
@ -1415,7 +1415,7 @@ public class OllamaAPI {
*/ */
public void deregisterTools() { public void deregisterTools() {
toolRegistry.clear(); toolRegistry.clear();
logger.debug("All tools have been deregistered."); LOG.debug("All tools have been deregistered.");
} }
/** /**
@ -1631,7 +1631,7 @@ public class OllamaAPI {
String methodName = toolFunctionCallSpec.getName(); String methodName = toolFunctionCallSpec.getName();
Map<String, Object> arguments = toolFunctionCallSpec.getArguments(); Map<String, Object> arguments = toolFunctionCallSpec.getArguments();
ToolFunction function = toolRegistry.getToolFunction(methodName); ToolFunction function = toolRegistry.getToolFunction(methodName);
logger.debug("Invoking function {} with arguments {}", methodName, arguments); LOG.debug("Invoking function {} with arguments {}", methodName, arguments);
if (function == null) { if (function == null) {
throw new ToolNotFoundException( throw new ToolNotFoundException(
"No such tool: " + methodName + ". Please register the tool before invoking it."); "No such tool: " + methodName + ". Please register the tool before invoking it.");

View File

@ -1,10 +1,14 @@
package io.github.ollama4j.impl; package io.github.ollama4j.impl;
import io.github.ollama4j.models.generate.OllamaStreamHandler; import io.github.ollama4j.models.generate.OllamaStreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConsoleOutputStreamHandler implements OllamaStreamHandler { public class ConsoleOutputStreamHandler implements OllamaStreamHandler {
private static final Logger LOG = LoggerFactory.getLogger(ConsoleOutputStreamHandler.class);
@Override @Override
public void accept(String message) { public void accept(String message) {
System.out.print(message); LOG.info(message);
} }
} }