| 
 | 1 | +package ee.carlrobert.llm.client.watsonx;  | 
 | 2 | + | 
 | 3 | +import static ee.carlrobert.llm.client.DeserializationUtil.OBJECT_MAPPER;  | 
 | 4 | + | 
 | 5 | +import com.fasterxml.jackson.core.JsonProcessingException;  | 
 | 6 | +import ee.carlrobert.llm.PropertiesLoader;  | 
 | 7 | +import ee.carlrobert.llm.client.DeserializationUtil;  | 
 | 8 | +import ee.carlrobert.llm.client.openai.completion.ErrorDetails;  | 
 | 9 | +import ee.carlrobert.llm.client.watsonx.completion.WatsonxCompletionRequest;  | 
 | 10 | +import ee.carlrobert.llm.client.watsonx.completion.WatsonxCompletionResponse;  | 
 | 11 | +import ee.carlrobert.llm.client.watsonx.completion.WatsonxCompletionResponseError;  | 
 | 12 | +import ee.carlrobert.llm.completion.CompletionEventListener;  | 
 | 13 | +import ee.carlrobert.llm.completion.CompletionEventSourceListener;  | 
 | 14 | +import java.io.IOException;  | 
 | 15 | +import java.util.HashMap;  | 
 | 16 | +import java.util.Map;  | 
 | 17 | +import okhttp3.Headers;  | 
 | 18 | +import okhttp3.MediaType;  | 
 | 19 | +import okhttp3.OkHttpClient;  | 
 | 20 | +import okhttp3.Request;  | 
 | 21 | +import okhttp3.RequestBody;  | 
 | 22 | +import okhttp3.sse.EventSource;  | 
 | 23 | +import okhttp3.sse.EventSources;  | 
 | 24 | + | 
 | 25 | +public class WatsonxClient {  | 
 | 26 | + | 
 | 27 | +  private static final MediaType APPLICATION_JSON = MediaType.parse("application/json");  | 
 | 28 | +  private final OkHttpClient httpClient;  | 
 | 29 | +  private final String host;  | 
 | 30 | +  private final String apiVersion;  | 
 | 31 | +  private final WatsonxAuthenticator authenticator;  | 
 | 32 | + | 
 | 33 | +  private WatsonxClient(Builder builder, OkHttpClient.Builder httpClientBuilder) {  | 
 | 34 | +    this.httpClient = httpClientBuilder.build();  | 
 | 35 | +    this.apiVersion = builder.apiVersion;  | 
 | 36 | +    this.host = builder.host;  | 
 | 37 | +    if (builder.isOnPrem) {  | 
 | 38 | +      if (builder.isZenApiKey) {  | 
 | 39 | +        this.authenticator = new WatsonxAuthenticator(builder.username, builder.apiKey);  | 
 | 40 | +      } else {  | 
 | 41 | +        this.authenticator = new WatsonxAuthenticator(builder.username, builder.apiKey,  | 
 | 42 | +            builder.host);  | 
 | 43 | +      }  | 
 | 44 | +    } else {  | 
 | 45 | +      this.authenticator = new WatsonxAuthenticator(builder.apiKey);  | 
 | 46 | +    }  | 
 | 47 | +  }  | 
 | 48 | + | 
 | 49 | +  public EventSource getCompletionAsync(  | 
 | 50 | +      WatsonxCompletionRequest request,  | 
 | 51 | +      CompletionEventListener<String> eventListener) {  | 
 | 52 | +    return EventSources.createFactory(httpClient).newEventSource(  | 
 | 53 | +        buildCompletionRequest(request),  | 
 | 54 | +        getCompletionEventSourceListener(eventListener));  | 
 | 55 | +  }  | 
 | 56 | + | 
 | 57 | +  public WatsonxCompletionResponse getCompletion(WatsonxCompletionRequest request) {  | 
 | 58 | +    try (var response = httpClient.newCall(buildCompletionRequest(request)).execute()) {  | 
 | 59 | +      return DeserializationUtil.mapResponse(response, WatsonxCompletionResponse.class);  | 
 | 60 | +    } catch (IOException e) {  | 
 | 61 | +      throw new RuntimeException(e);  | 
 | 62 | +    }  | 
 | 63 | +  }  | 
 | 64 | + | 
 | 65 | +  protected Request buildCompletionRequest(WatsonxCompletionRequest request) {  | 
 | 66 | +    var headers = new HashMap<>(getRequiredHeaders());  | 
 | 67 | +    if (request.getStream()) {  | 
 | 68 | +      headers.put("Accept", "text/event-stream");  | 
 | 69 | +    }  | 
 | 70 | +    try {  | 
 | 71 | +      String deployment = request.getDeploymentId().isEmpty() ? ""  | 
 | 72 | +          : "deployments/" + request.getDeploymentId() + "/";  | 
 | 73 | +      String generation = request.getStream() ? "generation_stream" : "generation";  | 
 | 74 | +      return new Request.Builder()  | 
 | 75 | +          .url(host + "/ml/v1/text/" + deployment + generation + "?version=" + apiVersion)  | 
 | 76 | +          .headers(Headers.of(headers))  | 
 | 77 | +          .post(RequestBody.create(OBJECT_MAPPER.writeValueAsString(request), APPLICATION_JSON))  | 
 | 78 | +          .build();  | 
 | 79 | +    } catch (JsonProcessingException e) {  | 
 | 80 | +      throw new RuntimeException("Unable to process request", e);  | 
 | 81 | +    }  | 
 | 82 | +  }  | 
 | 83 | + | 
 | 84 | +  private Map<String, String> getRequiredHeaders() {  | 
 | 85 | +    return new HashMap<>(Map.of("Authorization",  | 
 | 86 | +        (this.authenticator.isZenApiKey ? "ZenApiKey " : "Bearer ")  | 
 | 87 | +            + authenticator.getBearerTokenValue()));  | 
 | 88 | +  }  | 
 | 89 | + | 
 | 90 | +  private CompletionEventSourceListener<String> getCompletionEventSourceListener(  | 
 | 91 | +      CompletionEventListener<String> eventListener) {  | 
 | 92 | +    return new CompletionEventSourceListener<>(eventListener) {  | 
 | 93 | +      @Override  | 
 | 94 | +      protected String getMessage(String data) {  | 
 | 95 | +        try {  | 
 | 96 | +          return OBJECT_MAPPER.readValue(data, WatsonxCompletionResponse.class)  | 
 | 97 | +              .getResults().get(0).getGeneratedText();  | 
 | 98 | +        } catch (Exception e) {  | 
 | 99 | +          try {  | 
 | 100 | +            System.out.println(data);  | 
 | 101 | +            String message = OBJECT_MAPPER.readValue(data, WatsonxCompletionResponseError.class)  | 
 | 102 | +                .getError()  | 
 | 103 | +                .getMessage();  | 
 | 104 | +            if (message == null) return "";  | 
 | 105 | +            return message;  | 
 | 106 | +          } catch (Exception ex) {  | 
 | 107 | +            System.out.println(ex.toString());  | 
 | 108 | +            return "";  | 
 | 109 | +          }  | 
 | 110 | +        }  | 
 | 111 | +      }  | 
 | 112 | + | 
 | 113 | +      @Override  | 
 | 114 | +      protected ErrorDetails getErrorDetails(String error) {  | 
 | 115 | +        try {  | 
 | 116 | +          return OBJECT_MAPPER.readValue(error, WatsonxCompletionResponseError.class).getError();  | 
 | 117 | +        } catch (JsonProcessingException e) {  | 
 | 118 | +          throw new RuntimeException(e);  | 
 | 119 | +        }  | 
 | 120 | +      }  | 
 | 121 | +    };  | 
 | 122 | +  }  | 
 | 123 | + | 
 | 124 | +  public static class Builder {  | 
 | 125 | + | 
 | 126 | +    private final String apiKey;  | 
 | 127 | +    private String host = PropertiesLoader.getValue("watsonx.baseUrl");  | 
 | 128 | +    private String apiVersion = "2024-03-14";  | 
 | 129 | +    private Boolean isOnPrem;  | 
 | 130 | +    private Boolean isZenApiKey;  | 
 | 131 | +    private String username;  | 
 | 132 | + | 
 | 133 | +    public Builder(String apiKey) {  | 
 | 134 | +      this.apiKey = apiKey;  | 
 | 135 | +    }  | 
 | 136 | + | 
 | 137 | +    public Builder setApiVersion(String apiVersion) {  | 
 | 138 | +      this.apiVersion = apiVersion;  | 
 | 139 | +      return this;  | 
 | 140 | +    }  | 
 | 141 | + | 
 | 142 | +    public Builder setHost(String host) {  | 
 | 143 | +      this.host = host;  | 
 | 144 | +      return this;  | 
 | 145 | +    }  | 
 | 146 | + | 
 | 147 | +    public Builder setIsZenApiKey(Boolean isZenApiKey) {  | 
 | 148 | +      this.isZenApiKey = isZenApiKey;  | 
 | 149 | +      return this;  | 
 | 150 | +    }  | 
 | 151 | + | 
 | 152 | +    public Builder setIsOnPrem(Boolean isOnPrem) {  | 
 | 153 | +      this.isOnPrem = isOnPrem;  | 
 | 154 | +      return this;  | 
 | 155 | +    }  | 
 | 156 | + | 
 | 157 | +    public Builder setUsername(String username) {  | 
 | 158 | +      this.username = username;  | 
 | 159 | +      return this;  | 
 | 160 | +    }  | 
 | 161 | + | 
 | 162 | +    public WatsonxClient build(OkHttpClient.Builder builder) {  | 
 | 163 | +      return new WatsonxClient(this, builder);  | 
 | 164 | +    }  | 
 | 165 | + | 
 | 166 | +    public WatsonxClient build() {  | 
 | 167 | +      return build(new OkHttpClient.Builder());  | 
 | 168 | +    }  | 
 | 169 | +  }  | 
 | 170 | +}  | 
 | 171 | + | 
 | 172 | + | 
 | 173 | + | 
 | 174 | + | 
 | 175 | + | 
 | 176 | + | 
0 commit comments