Ollama4j
A Java library (wrapper/binding) for Ollama server.
Loading...
Searching...
No Matches
OllamaChatEndpointCaller.java
Go to the documentation of this file.
1package io.github.ollama4j.models.request;
2
3import com.fasterxml.jackson.core.JsonProcessingException;
4import com.fasterxml.jackson.core.type.TypeReference;
5import io.github.ollama4j.exceptions.OllamaBaseException;
6import io.github.ollama4j.models.chat.OllamaChatMessage;
7import io.github.ollama4j.models.response.OllamaResult;
8import io.github.ollama4j.models.chat.OllamaChatResponseModel;
9import io.github.ollama4j.models.chat.OllamaChatStreamObserver;
10import io.github.ollama4j.models.generate.OllamaStreamHandler;
11import io.github.ollama4j.utils.OllamaRequestBody;
12import io.github.ollama4j.utils.Utils;
13import org.slf4j.Logger;
14import org.slf4j.LoggerFactory;
15
16import java.io.IOException;
17
22
23 private static final Logger LOG = LoggerFactory.getLogger(OllamaChatEndpointCaller.class);
24
25 private OllamaChatStreamObserver streamObserver;
26
27 public OllamaChatEndpointCaller(String host, BasicAuth basicAuth, long requestTimeoutSeconds, boolean verbose) {
28 super(host, basicAuth, requestTimeoutSeconds, verbose);
29 }
30
31 @Override
32 protected String getEndpointSuffix() {
33 return "/api/chat";
34 }
35
47 @Override
48 protected boolean parseResponseAndAddToBuffer(String line, StringBuilder responseBuffer) {
49 try {
50 OllamaChatResponseModel ollamaResponseModel = Utils.getObjectMapper().readValue(line, OllamaChatResponseModel.class);
51 // it seems that under heavy load ollama responds with an empty chat message part in the streamed response
52 // thus, we null check the message and hope that the next streamed response has some message content again
53 OllamaChatMessage message = ollamaResponseModel.getMessage();
54 if(message != null) {
55 responseBuffer.append(message.getContent());
56 if (streamObserver != null) {
57 streamObserver.notify(ollamaResponseModel);
58 }
59 }
60 return ollamaResponseModel.isDone();
61 } catch (JsonProcessingException e) {
62 LOG.error("Error parsing the Ollama chat response!", e);
63 return true;
64 }
65 }
66
68 throws OllamaBaseException, IOException, InterruptedException {
69 streamObserver = new OllamaChatStreamObserver(streamHandler);
70 return super.callSync(body);
71 }
72}
void notify(OllamaChatResponseModel currentResponsePart)
OllamaResult call(OllamaRequestBody body, OllamaStreamHandler streamHandler)
OllamaChatEndpointCaller(String host, BasicAuth basicAuth, long requestTimeoutSeconds, boolean verbose)
boolean parseResponseAndAddToBuffer(String line, StringBuilder responseBuffer)
static ObjectMapper getObjectMapper()
Definition Utils.java:17