UNPKG

@anthropic-ai/sdk

Version:
203 lines • 9.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TOTALS_IN_MESSAGE_DELTA = exports.FINAL_FROM_MESSAGE_DELTA = void 0; exports.recordStreamedMessageContent = recordStreamedMessageContent; exports.endAnthropicApiCallSpanWhenStreamEnds = endAnthropicApiCallSpanWhenStreamEnds; const api_1 = require("@opentelemetry/api"); const error_1 = require("../../../core/error.js"); const streaming_1 = require("../../../core/streaming.js"); const tracing_1 = require("../../../internal/tracing.js"); const log_1 = require("../../../internal/utils/log.js"); const values_1 = require("../../../internal/utils/values.js"); const attributes_1 = require("./attributes.js"); const content_1 = require("./content.js"); const response_1 = require("./response.js"); /** * In content mode, records `message`, which a stream helper accumulated, as the response content * of `call`, under the same size limit as a response that is not streamed. */ function recordStreamedMessageContent(client, call, body, message) { if (!call.span.isRecording() || client.openTelemetry.traces.contentMode !== 'content') { return; } try { (0, content_1.setMessageContentAttributes)(call, body, message.content, client.openTelemetry.traces.maxContentBytes); } catch (problem) { (0, log_1.loggerFor)(client).debug('could not record the streamed message on its span', problem); } } /** * Ends `span` when the application's read of `stream` ends. Only the stream of `messages.create` * has events that the span records. */ function endAnthropicApiCallSpanWhenStreamEnds(client, span, stream, props) { if (props.options.__span?.name === 'anthropic.messages.create' && stream instanceof streaming_1.Stream) { endMessagesCreateSpanWhenStreamEnds(client, span, stream, props); } else { (0, tracing_1.endApiCallSpanWhenStreamEnds)(span, stream, props); } } /** * Ends the span of a `messages.create` API call when the application's read of `stream` ends, with * the attributes of the Message that the events reconstruct, as far as it was read. The content is * that of a stream helper's Message: the helper records it at `message_stop` * (`recordStreamedMessageContent`), and a stream that ends earlier records it here. */ function endMessagesCreateSpanWhenStreamEnds(client, span, stream, props) { if (!span.isRecording()) { return; } span.setAttribute(tracing_1.ATTR_HTTP_RESPONSE_STATUS_CODE, props.response.status); (0, tracing_1.setResponseHeaderAttributes)(span, props.response); const call = props.options.__span; const startTime = call?.startTime; // What the span reads of the Message, and the usage, as the events have them so far. let message; let usage; let sawDelta = false; let sawMessageDelta = false; let sawStop = false; (0, tracing_1.observeStream)(stream, props.controller.signal, { onItem(event) { try { switch (event.type) { case 'message_start': { // Only what the span reads, because this lives for as long as the application holds the stream. const atStart = { ...event.message }; usage = { ...event.message.usage }; message = {}; for (const [, [name]] of tracing_1.SPAN_ATTRIBUTES[call?.name ?? '']?.response ?? []) { if (name !== undefined && name !== 'usage') { message[name] = atStart[name]; } } break; } case 'content_block_start': { // A fallback block names the model that produces the rest of the Message. const block = event.content_block; if (message && (0, values_1.isObj)(block) && block['type'] === 'fallback' && (0, values_1.isObj)(block['to'])) { message['model'] = block['to']['model']; } break; } case 'message_delta': if (message && usage) { const totals = (0, values_1.isObj)(event.usage) ? event.usage : {}; // The final count, which replaces the placeholder of `message_start` whatever it is. usage['output_tokens'] = totals['output_tokens']; // Totals for the whole Message, null when they do not apply, so one that is present // replaces the earlier value. for (const name of exports.TOTALS_IN_MESSAGE_DELTA) { if (totals[name] != null) { usage[name] = totals[name]; } } if (event.delta.stop_reason != null) { message['stop_reason'] = event.delta.stop_reason; } sawMessageDelta = true; } break; case 'message_stop': sawStop = true; break; case 'content_block_delta': // The first chunk is the first delta, of any type, not an earlier event. if (!sawDelta && startTime !== undefined) { span.setAttribute(attributes_1.ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, (Date.now() - startTime) / 1000); } sawDelta = true; break; case 'content_block_stop': break; default: (0, values_1.checkNever)(event); } } catch (problem) { (0, log_1.loggerFor)(client).debug('could not record the stream on its span', problem); } }, onEnd(end) { try { if (message && usage && call) { // `message_delta` has the stop reason and the final output usage, so a stream cut short // after it still has them. Before it, `message_start` has only placeholders for them. const complete = sawMessageDelta || sawStop; let response = { ...message, usage }; if (!complete) { for (const path of exports.FINAL_FROM_MESSAGE_DELTA) { response = without(response, path); } } (0, tracing_1.setResponseAttributes)(span, call.name, response); (0, response_1.setUsageSumAttributes)(span, usage, complete); } } catch (problem) { (0, log_1.loggerFor)(client).debug('could not record the stream on its span', problem); } const failure = call?.failure; // A helper that failed on an event did not build the Message that the stream sent. if (!sawStop && call?.streamed && failure === undefined) { recordStreamedMessageContent(client, call, call.streamed.body, call.streamed.message); } if (end.reason === 'failed') { (0, tracing_1.setErrorStatus)(span, end.error); } else if (failure !== undefined) { (0, tracing_1.setErrorStatus)(span, failure, 'client_error'); } else if (end.reason === 'completed') { if (sawStop) { span.setStatus({ code: api_1.SpanStatusCode.OK }); } else { // The application sees the stream end without an error, so only the span fails. (0, tracing_1.setErrorStatus)(span, new error_1.AnthropicError('The stream ended before message_stop.'), 'api_error'); } } // Otherwise the application closed the stream before the API did, which leaves the status // unset, even after `message_stop`. (0, tracing_1.guardTracing)(client, () => span.end()); }, }); } /** * The paths in a streamed Message whose values are final only from `message_delta` on. * `message_start` has placeholders for them, so the span of a stream that ended before * `message_delta` records nothing under them. */ exports.FINAL_FROM_MESSAGE_DELTA = [ ['stop_reason'], ['usage', 'output_tokens'], ['usage', 'output_tokens_details'], ]; /** * The totals in the usage of `message_delta`, besides `output_tokens`, that replace those of * `message_start`. Of the rest of the event, the span records the stop reason alone. */ exports.TOTALS_IN_MESSAGE_DELTA = [ 'input_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens', 'output_tokens_details', 'iterations', ]; /** `data` without the value at `path`, as a copy that shares what the path does not go through. */ function without(data, path) { const [name, ...rest] = path; if (name === undefined || !(name in data)) { return data; } if (rest.length === 0) { const { [name]: _, ...others } = data; return others; } const value = data[name]; return (0, values_1.isObj)(value) ? { ...data, [name]: without(value, rest) } : data; } //# sourceMappingURL=streaming.js.map