Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 12 additions & 5 deletions packages/genai-util/src/invocations/inference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,13 @@ export class InferenceInvocation extends BaseInvocation {
private readonly _serverAddress?: string;
private readonly _serverPort?: number;
private readonly _contentCaptureMode: ContentCaptureMode;
private _isStreaming: boolean;
/**
* Whether the response was observed as a stream, through {@link setStreaming}
* (called by the stream wrapper and {@link recordStreamChunk}). Requesting a
* stream alone does not set it: a caller that never reads the stream has no
* finish reason to report, missing or otherwise.
*/
private _isStreaming = false;
private _responseModel?: string;
private _finishReasons?: FinishReason[];
private _usage?: TokenUsageDetails;
Expand Down Expand Up @@ -159,7 +165,6 @@ export class InferenceInvocation extends BaseInvocation {
this._requestModel = options.requestModel;
this._serverAddress = options.serverAddress;
this._serverPort = options.serverPort;
this._isStreaming = options.requestOptions?.stream === true;
this._contentCaptureMode = handler.getContentCaptureMode();
this._inputMessages = options.inputMessages
? [...options.inputMessages]
Expand All @@ -171,6 +176,7 @@ export class InferenceInvocation extends BaseInvocation {
* Set the request streaming attribute to true.
*
* This is a convenience method for the case when the user is streaming the response.
* Once called, a stream that ends without a finish reason reports `'error'`.
*/
public setStreaming(): this {
this.setAttribute(ATTR_GEN_AI_REQUEST_STREAM, true);
Expand Down Expand Up @@ -360,9 +366,10 @@ export class InferenceInvocation extends BaseInvocation {
_endTime: HrTime,
errorType?: string
): void {
// Avoids putting ['error'] on a successful non-streaming span when
// setFinishReasons() wasn't called, while still defaulting to ['error'] if
// a stream ends early (e.g. break before the final chunk) or if fail() is called.
// Avoids putting ['error'] on a successful span when setFinishReasons()
// wasn't called and no stream was observed, while still defaulting to
// ['error'] if an observed stream ends early (e.g. break before the final
// chunk) or if fail() is called.
if (
this._finishReasons !== undefined ||
errorType !== undefined ||
Expand Down
41 changes: 41 additions & 0 deletions packages/genai-util/test/invocations/inference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,47 @@ describe('InferenceInvocation', () => {
);
});

it('should default finish_reasons to error only once a requested stream has been observed', () => {
const handler = new TelemetryHandler({
instrumentationName: 'test-instrumentation',
instrumentationVersion: '1.0.0',
tracerProvider: ctx.tracerProvider,
});
const startStreaming = () =>
handler.startInference({
providerName: 'openai',
requestOptions: { stream: true },
});

// The caller took the raw response and never read the stream, so there is
// no finish reason to report.
startStreaming().stop();

const observed = startStreaming();
observed.recordStreamChunk();
observed.stop();

const explicit = startStreaming();
explicit.setStreaming();
explicit.stop();

startStreaming().fail({ errorType: 'TimeoutError' });

const spans = ctx.memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 4);
assert.strictEqual(spans[0].attributes[ATTR_GEN_AI_REQUEST_STREAM], true);
assert.strictEqual(
spans[0].attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS],
undefined
);
for (const span of spans.slice(1)) {
assert.deepStrictEqual(
span.attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS],
['error']
);
}
});

it('should record time to first chunk once and time per output chunk for each later chunk', async () => {
const handler = new TelemetryHandler({
instrumentationName: 'test-instrumentation',
Expand Down
18 changes: 14 additions & 4 deletions packages/instrumentation-anthropic/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,22 @@ instead; see its `openTelemetry` client option.
- `anthropic.messages.create({ stream: true })`
- `anthropic.messages.stream()`

The current scaffold creates a client span for each call, records the GenAI
provider, operation, and requested model, and marks failed calls as errors. The
Telemetry is produced through the `TelemetryHandler` of
[`@opentelemetry/genai-util`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/genai-util), which owns each call's span and
metrics. Each call creates a client span that records the GenAI provider,
operation, requested model and request parameters (`max_tokens`,
`temperature`, `top_p`, `top_k`, `stop_sequences`, `stream`), the response id,
model, finish reason and token usage, and marks failed calls as errors. The
provider is derived from the client's base URL, so `AnthropicBedrock` and
`AnthropicVertex` calls are reported as `aws.bedrock` and `gcp.vertex_ai`.
Response attributes, tools, metrics, logs, and content capture are intentionally
out of scope.

The GenAI client metrics are recorded for each call: operation duration, input
and output token usage (including prompt cache reads and writes), and, for
streams, time to first chunk and time per output chunk. As with
`gen_ai.usage.input_tokens`, input token counts include prompt cache reads and
writes, which Anthropic reports separately from `input_tokens`.

Tools, logs, and message content capture are out of scope.

The patch is registered on the shared `Messages` resource module rather than on
the package root, in both its CommonJS and ESM builds, so it applies however the
Expand Down
1 change: 1 addition & 0 deletions packages/instrumentation-anthropic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
},
"dependencies": {
"@opentelemetry/core": "^3.0.0",
"@opentelemetry/genai-util": "^0.5.0",
"@opentelemetry/instrumentation": "^0.301.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-anthropic#readme"
Expand Down
Loading