|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.inference.services.huggingface; |
| 9 | + |
| 10 | +import org.elasticsearch.core.Nullable; |
| 11 | +import org.elasticsearch.rest.RestStatus; |
| 12 | +import org.elasticsearch.xcontent.ConstructingObjectParser; |
| 13 | +import org.elasticsearch.xcontent.ParseField; |
| 14 | +import org.elasticsearch.xcontent.XContentFactory; |
| 15 | +import org.elasticsearch.xcontent.XContentParser; |
| 16 | +import org.elasticsearch.xcontent.XContentParserConfiguration; |
| 17 | +import org.elasticsearch.xcontent.XContentType; |
| 18 | +import org.elasticsearch.xpack.core.inference.results.UnifiedChatCompletionException; |
| 19 | +import org.elasticsearch.xpack.inference.external.http.HttpResult; |
| 20 | +import org.elasticsearch.xpack.inference.external.http.retry.ErrorResponse; |
| 21 | +import org.elasticsearch.xpack.inference.external.http.retry.ResponseParser; |
| 22 | +import org.elasticsearch.xpack.inference.external.request.Request; |
| 23 | +import org.elasticsearch.xpack.inference.services.huggingface.response.HuggingFaceErrorResponseEntity; |
| 24 | +import org.elasticsearch.xpack.inference.services.openai.OpenAiUnifiedChatCompletionResponseHandler; |
| 25 | + |
| 26 | +import java.util.Locale; |
| 27 | +import java.util.Optional; |
| 28 | + |
| 29 | +import static org.elasticsearch.core.Strings.format; |
| 30 | + |
| 31 | +/** |
| 32 | + * Handles streaming chat completion responses and error parsing for Hugging Face inference endpoints. |
| 33 | + * Adapts the OpenAI handler to support Hugging Face's simpler error schema with fields like "message" and "http_status_code". |
| 34 | + */ |
| 35 | +public class HuggingFaceChatCompletionResponseHandler extends OpenAiUnifiedChatCompletionResponseHandler { |
| 36 | + |
| 37 | + private static final String HUGGING_FACE_ERROR = "hugging_face_error"; |
| 38 | + |
| 39 | + public HuggingFaceChatCompletionResponseHandler(String requestType, ResponseParser parseFunction) { |
| 40 | + super(requestType, parseFunction, HuggingFaceErrorResponseEntity::fromResponse); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + protected Exception buildError(String message, Request request, HttpResult result, ErrorResponse errorResponse) { |
| 45 | + assert request.isStreaming() : "Only streaming requests support this format"; |
| 46 | + var responseStatusCode = result.response().getStatusLine().getStatusCode(); |
| 47 | + if (request.isStreaming()) { |
| 48 | + var errorMessage = errorMessage(message, request, result, errorResponse, responseStatusCode); |
| 49 | + var restStatus = toRestStatus(responseStatusCode); |
| 50 | + return errorResponse instanceof HuggingFaceErrorResponseEntity |
| 51 | + ? new UnifiedChatCompletionException( |
| 52 | + restStatus, |
| 53 | + errorMessage, |
| 54 | + HUGGING_FACE_ERROR, |
| 55 | + restStatus.name().toLowerCase(Locale.ROOT) |
| 56 | + ) |
| 57 | + : new UnifiedChatCompletionException( |
| 58 | + restStatus, |
| 59 | + errorMessage, |
| 60 | + createErrorType(errorResponse), |
| 61 | + restStatus.name().toLowerCase(Locale.ROOT) |
| 62 | + ); |
| 63 | + } else { |
| 64 | + return super.buildError(message, request, result, errorResponse); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + protected Exception buildMidStreamError(Request request, String message, Exception e) { |
| 70 | + var errorResponse = StreamingHuggingFaceErrorResponseEntity.fromString(message); |
| 71 | + if (errorResponse instanceof StreamingHuggingFaceErrorResponseEntity streamingHuggingFaceErrorResponseEntity) { |
| 72 | + return new UnifiedChatCompletionException( |
| 73 | + RestStatus.INTERNAL_SERVER_ERROR, |
| 74 | + format( |
| 75 | + "%s for request from inference entity id [%s]. Error message: [%s]", |
| 76 | + SERVER_ERROR_OBJECT, |
| 77 | + request.getInferenceEntityId(), |
| 78 | + errorResponse.getErrorMessage() |
| 79 | + ), |
| 80 | + HUGGING_FACE_ERROR, |
| 81 | + extractErrorCode(streamingHuggingFaceErrorResponseEntity) |
| 82 | + ); |
| 83 | + } else if (e != null) { |
| 84 | + return UnifiedChatCompletionException.fromThrowable(e); |
| 85 | + } else { |
| 86 | + return new UnifiedChatCompletionException( |
| 87 | + RestStatus.INTERNAL_SERVER_ERROR, |
| 88 | + format("%s for request from inference entity id [%s]", SERVER_ERROR_OBJECT, request.getInferenceEntityId()), |
| 89 | + createErrorType(errorResponse), |
| 90 | + "stream_error" |
| 91 | + ); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private static String extractErrorCode(StreamingHuggingFaceErrorResponseEntity streamingHuggingFaceErrorResponseEntity) { |
| 96 | + return streamingHuggingFaceErrorResponseEntity.httpStatusCode() != null |
| 97 | + ? String.valueOf(streamingHuggingFaceErrorResponseEntity.httpStatusCode()) |
| 98 | + : null; |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Represents a structured error response specifically for streaming operations |
| 103 | + * using HuggingFace APIs. This is separate from non-streaming error responses, |
| 104 | + * which are handled by {@link HuggingFaceErrorResponseEntity}. |
| 105 | + * An example error response for failed field validation for streaming operation would look like |
| 106 | + * <code> |
| 107 | + * { |
| 108 | + * "error": "Input validation error: cannot compile regex from schema", |
| 109 | + * "http_status_code": 422 |
| 110 | + * } |
| 111 | + * </code> |
| 112 | + */ |
| 113 | + private static class StreamingHuggingFaceErrorResponseEntity extends ErrorResponse { |
| 114 | + private static final ConstructingObjectParser<Optional<ErrorResponse>, Void> ERROR_PARSER = new ConstructingObjectParser<>( |
| 115 | + HUGGING_FACE_ERROR, |
| 116 | + true, |
| 117 | + args -> Optional.ofNullable((StreamingHuggingFaceErrorResponseEntity) args[0]) |
| 118 | + ); |
| 119 | + private static final ConstructingObjectParser<StreamingHuggingFaceErrorResponseEntity, Void> ERROR_BODY_PARSER = |
| 120 | + new ConstructingObjectParser<>( |
| 121 | + HUGGING_FACE_ERROR, |
| 122 | + true, |
| 123 | + args -> new StreamingHuggingFaceErrorResponseEntity(args[0] != null ? (String) args[0] : "unknown", (Integer) args[1]) |
| 124 | + ); |
| 125 | + |
| 126 | + static { |
| 127 | + ERROR_BODY_PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), new ParseField("message")); |
| 128 | + ERROR_BODY_PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), new ParseField("http_status_code")); |
| 129 | + |
| 130 | + ERROR_PARSER.declareObjectOrNull( |
| 131 | + ConstructingObjectParser.optionalConstructorArg(), |
| 132 | + ERROR_BODY_PARSER, |
| 133 | + null, |
| 134 | + new ParseField("error") |
| 135 | + ); |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Parses a streaming HuggingFace error response from a JSON string. |
| 140 | + * |
| 141 | + * @param response the raw JSON string representing an error |
| 142 | + * @return a parsed {@link ErrorResponse} or {@link ErrorResponse#UNDEFINED_ERROR} if parsing fails |
| 143 | + */ |
| 144 | + private static ErrorResponse fromString(String response) { |
| 145 | + try ( |
| 146 | + XContentParser parser = XContentFactory.xContent(XContentType.JSON) |
| 147 | + .createParser(XContentParserConfiguration.EMPTY, response) |
| 148 | + ) { |
| 149 | + return ERROR_PARSER.apply(parser, null).orElse(ErrorResponse.UNDEFINED_ERROR); |
| 150 | + } catch (Exception e) { |
| 151 | + // swallow the error |
| 152 | + } |
| 153 | + |
| 154 | + return ErrorResponse.UNDEFINED_ERROR; |
| 155 | + } |
| 156 | + |
| 157 | + @Nullable |
| 158 | + private final Integer httpStatusCode; |
| 159 | + |
| 160 | + StreamingHuggingFaceErrorResponseEntity(String errorMessage, @Nullable Integer httpStatusCode) { |
| 161 | + super(errorMessage); |
| 162 | + this.httpStatusCode = httpStatusCode; |
| 163 | + } |
| 164 | + |
| 165 | + @Nullable |
| 166 | + public Integer httpStatusCode() { |
| 167 | + return httpStatusCode; |
| 168 | + } |
| 169 | + |
| 170 | + } |
| 171 | +} |
0 commit comments