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
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, the purpose of this variable is now changed - so the name should be updated as well. A better suited name for this can be _streamObserved.

Please move it toward the end of the other private vars.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The semantic conventions have since been updated with the new guidelines being:

[30] gen_ai.response.finish_reasons: Values correspond to generations in the same order as the returned choices/candidates.
For interrupted generations, instrumentations SHOULD report the provider-reported interruption reason when available and interrupted otherwise.
Each position SHOULD contain the finish reason for the corresponding choice/candidate. If an expected finish reason is missing, instrumentations SHOULD report interrupted when the caller closes or disposes of the stream without an error, and error if generation fails or the stream ends unexpectedly.
error indicates that the generation ended abnormally, whether reported by the provider or inferred by the instrumentation.

See Ref.

Semconv previously dictated that missing finish_reasons be populated with error instead. This behavior of defaulting to error needs updating now.

// 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
Loading