1
1
package com .comet .opik .domain .llmproviders ;
2
2
3
3
import com .comet .opik .utils .JsonUtils ;
4
- import dev .ai4j .openai4j .OpenAiHttpException ;
5
4
import io .dropwizard .jersey .errors .ErrorMessage ;
6
5
import lombok .extern .slf4j .Slf4j ;
7
6
import org .glassfish .jersey .server .ChunkedOutput ;
8
7
9
8
import java .io .IOException ;
10
9
import java .io .UncheckedIOException ;
10
+ import java .util .function .Consumer ;
11
+ import java .util .function .Function ;
11
12
12
13
@ Slf4j
13
14
public class LlmProviderStreamHandler {
@@ -33,17 +34,18 @@ public void handleClose(ChunkedOutput<String> chunkedOutput) {
33
34
}
34
35
}
35
36
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 );
37
+ public Consumer <Throwable > getErrorHandler (
38
+ Function <Throwable , ErrorMessage > mapper , ChunkedOutput <String > chunkedOutput ) {
39
+ return throwable -> {
40
+ log .error (UNEXPECTED_ERROR_CALLING_LLM_PROVIDER , throwable );
41
+
42
+ var errorMessage = mapper .apply (throwable );
43
+ try {
44
+ handleMessage (errorMessage , chunkedOutput );
45
+ } catch (UncheckedIOException uncheckedIOException ) {
46
+ log .error ("Failed to stream error message to client" , uncheckedIOException );
47
+ }
48
+ handleClose (chunkedOutput );
49
+ };
48
50
}
49
51
}
0 commit comments