|
| 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.external.anthropic; |
| 9 | + |
| 10 | +import org.apache.logging.log4j.LogManager; |
| 11 | +import org.apache.logging.log4j.Logger; |
| 12 | +import org.elasticsearch.ElasticsearchStatusException; |
| 13 | +import org.elasticsearch.rest.RestStatus; |
| 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.StreamingChatCompletionResults; |
| 19 | +import org.elasticsearch.xpack.inference.common.DelegatingProcessor; |
| 20 | +import org.elasticsearch.xpack.inference.external.response.streaming.ServerSentEvent; |
| 21 | +import org.elasticsearch.xpack.inference.external.response.streaming.ServerSentEventField; |
| 22 | + |
| 23 | +import java.io.IOException; |
| 24 | +import java.util.ArrayDeque; |
| 25 | +import java.util.Deque; |
| 26 | +import java.util.Optional; |
| 27 | + |
| 28 | +import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; |
| 29 | +import static org.elasticsearch.xpack.inference.external.response.XContentUtils.moveToFirstToken; |
| 30 | +import static org.elasticsearch.xpack.inference.external.response.XContentUtils.positionParserAtTokenAfterField; |
| 31 | + |
| 32 | +public class AnthropicStreamingProcessor extends DelegatingProcessor<Deque<ServerSentEvent>, StreamingChatCompletionResults.Results> { |
| 33 | + private static final Logger log = LogManager.getLogger(AnthropicStreamingProcessor.class); |
| 34 | + private static final String FAILED_TO_FIND_FIELD_TEMPLATE = "Failed to find required field [%s] in Anthropic chat completions response"; |
| 35 | + |
| 36 | + @Override |
| 37 | + protected void next(Deque<ServerSentEvent> item) throws Exception { |
| 38 | + if (item.isEmpty()) { |
| 39 | + upstream().request(1); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + var results = new ArrayDeque<StreamingChatCompletionResults.Result>(item.size()); |
| 44 | + for (var event : item) { |
| 45 | + if (event.name() == ServerSentEventField.DATA && event.hasValue()) { |
| 46 | + try (var parser = parser(event.value())) { |
| 47 | + var eventType = eventType(parser); |
| 48 | + switch (eventType) { |
| 49 | + case "error" -> { |
| 50 | + onError(parseError(parser)); |
| 51 | + return; |
| 52 | + } |
| 53 | + case "content_block_start" -> { |
| 54 | + parseStartBlock(parser).ifPresent(results::offer); |
| 55 | + } |
| 56 | + case "content_block_delta" -> { |
| 57 | + parseMessage(parser).ifPresent(results::offer); |
| 58 | + } |
| 59 | + case "message_start", "message_stop", "message_delta", "content_block_stop", "ping" -> { |
| 60 | + log.debug("Skipping event type [{}] for line [{}].", eventType, item); |
| 61 | + } |
| 62 | + default -> { |
| 63 | + // "handle unknown events gracefully" https://docs.anthropic.com/en/api/messages-streaming#other-events |
| 64 | + // we'll ignore unknown events |
| 65 | + log.debug("Unknown event type [{}] for line [{}].", eventType, item); |
| 66 | + } |
| 67 | + } |
| 68 | + } catch (Exception e) { |
| 69 | + log.warn("Failed to parse line {}", event); |
| 70 | + throw e; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + if (results.isEmpty()) { |
| 76 | + upstream().request(1); |
| 77 | + } else { |
| 78 | + downstream().onNext(new StreamingChatCompletionResults.Results(results)); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private Throwable parseError(XContentParser parser) throws IOException { |
| 83 | + positionParserAtTokenAfterField(parser, "error", FAILED_TO_FIND_FIELD_TEMPLATE); |
| 84 | + var type = parseString(parser, "type"); |
| 85 | + var message = parseString(parser, "message"); |
| 86 | + var statusCode = switch (type) { |
| 87 | + case "invalid_request_error" -> RestStatus.BAD_REQUEST; |
| 88 | + case "authentication_error" -> RestStatus.UNAUTHORIZED; |
| 89 | + case "permission_error" -> RestStatus.FORBIDDEN; |
| 90 | + case "not_found_error" -> RestStatus.NOT_FOUND; |
| 91 | + case "request_too_large" -> RestStatus.REQUEST_ENTITY_TOO_LARGE; |
| 92 | + case "rate_limit_error" -> RestStatus.TOO_MANY_REQUESTS; |
| 93 | + default -> RestStatus.INTERNAL_SERVER_ERROR; |
| 94 | + }; |
| 95 | + return new ElasticsearchStatusException(message, statusCode); |
| 96 | + } |
| 97 | + |
| 98 | + private Optional<StreamingChatCompletionResults.Result> parseStartBlock(XContentParser parser) throws IOException { |
| 99 | + positionParserAtTokenAfterField(parser, "content_block", FAILED_TO_FIND_FIELD_TEMPLATE); |
| 100 | + var text = parseString(parser, "text"); |
| 101 | + return text.isBlank() ? Optional.empty() : Optional.of(new StreamingChatCompletionResults.Result(text)); |
| 102 | + } |
| 103 | + |
| 104 | + private Optional<StreamingChatCompletionResults.Result> parseMessage(XContentParser parser) throws IOException { |
| 105 | + positionParserAtTokenAfterField(parser, "delta", FAILED_TO_FIND_FIELD_TEMPLATE); |
| 106 | + var text = parseString(parser, "text"); |
| 107 | + return text.isBlank() ? Optional.empty() : Optional.of(new StreamingChatCompletionResults.Result(text)); |
| 108 | + } |
| 109 | + |
| 110 | + private static XContentParser parser(String line) throws IOException { |
| 111 | + return XContentFactory.xContent(XContentType.JSON).createParser(XContentParserConfiguration.EMPTY, line); |
| 112 | + } |
| 113 | + |
| 114 | + private static String eventType(XContentParser parser) throws IOException { |
| 115 | + moveToFirstToken(parser); |
| 116 | + ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser); |
| 117 | + return parseString(parser, "type"); |
| 118 | + } |
| 119 | + |
| 120 | + private static String parseString(XContentParser parser, String fieldName) throws IOException { |
| 121 | + positionParserAtTokenAfterField(parser, fieldName, FAILED_TO_FIND_FIELD_TEMPLATE); |
| 122 | + ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.currentToken(), parser); |
| 123 | + return parser.text(); |
| 124 | + } |
| 125 | +} |
0 commit comments