|
1 | 1 | package com.comet.opik.domain.llmproviders;
|
2 | 2 |
|
| 3 | +import com.comet.opik.utils.JsonUtils; |
| 4 | +import dev.ai4j.openai4j.OpenAiHttpException; |
| 5 | +import io.dropwizard.jersey.errors.ErrorMessage; |
| 6 | +import lombok.extern.slf4j.Slf4j; |
3 | 7 | import org.glassfish.jersey.server.ChunkedOutput;
|
4 | 8 |
|
5 |
| -public interface LlmProviderStreamHandler { |
6 |
| - void handleMessage(Object item, ChunkedOutput<String> chunkedOutput); |
7 |
| - void handleClose(ChunkedOutput<String> chunkedOutput); |
8 |
| - void handleError(Throwable throwable, ChunkedOutput<String> chunkedOutput); |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.UncheckedIOException; |
| 11 | + |
| 12 | +@Slf4j |
| 13 | +public class LlmProviderStreamHandler { |
| 14 | + private static final String UNEXPECTED_ERROR_CALLING_LLM_PROVIDER = "Unexpected error calling LLM provider"; |
| 15 | + |
| 16 | + public void handleMessage(Object item, ChunkedOutput<String> chunkedOutput) { |
| 17 | + if (chunkedOutput.isClosed()) { |
| 18 | + log.warn("Output stream is already closed"); |
| 19 | + return; |
| 20 | + } |
| 21 | + try { |
| 22 | + chunkedOutput.write(JsonUtils.writeValueAsString(item)); |
| 23 | + } catch (IOException ioException) { |
| 24 | + throw new UncheckedIOException(ioException); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public void handleClose(ChunkedOutput<String> chunkedOutput) { |
| 29 | + try { |
| 30 | + chunkedOutput.close(); |
| 31 | + } catch (IOException ioException) { |
| 32 | + log.error("Failed to close output stream", ioException); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public void handleError(Throwable throwable, ChunkedOutput<String> chunkedOutput) { |
| 37 | + log.error(UNEXPECTED_ERROR_CALLING_LLM_PROVIDER, throwable); |
| 38 | + var errorMessage = new ErrorMessage(UNEXPECTED_ERROR_CALLING_LLM_PROVIDER); |
| 39 | + if (throwable instanceof OpenAiHttpException openAiHttpException) { |
| 40 | + errorMessage = new ErrorMessage(openAiHttpException.code(), openAiHttpException.getMessage()); |
| 41 | + } |
| 42 | + try { |
| 43 | + handleMessage(errorMessage, chunkedOutput); |
| 44 | + } catch (UncheckedIOException uncheckedIOException) { |
| 45 | + log.error("Failed to stream error message to client", uncheckedIOException); |
| 46 | + } |
| 47 | + handleClose(chunkedOutput); |
| 48 | + } |
9 | 49 | }
|
0 commit comments