




















@@ -11,6 +11,7 @@ import {
1111import {
1212createChildDiagnosticTraceContext,
1313freezeDiagnosticTraceContext,
14+formatDiagnosticTraceparent,
1415type DiagnosticTraceContext,
1516} from "../../../infra/diagnostic-trace-context.js";
1617import { getGlobalHookRunner } from "../../../plugins/hook-runner-global.js";
@@ -48,6 +49,8 @@ type ModelCallEndedHookFields = Pick<
4849>;
49505051const MODEL_CALL_STREAM_RETURN_TIMEOUT_MS = 1000;
52+const TRACEPARENT_HEADER_NAME = "traceparent";
53+type ModelCallStreamOptions = Parameters<StreamFn>[2];
51545255function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
5356if (value === null || (typeof value !== "object" && typeof value !== "function")) {
@@ -197,6 +200,29 @@ function emitModelCallError(
197200});
198201}
199202203+function withDiagnosticTraceparentHeader(
204+options: ModelCallStreamOptions,
205+trace: DiagnosticTraceContext,
206+): ModelCallStreamOptions {
207+const traceparent = formatDiagnosticTraceparent(trace);
208+if (!traceparent) {
209+return options;
210+}
211+212+const headers: Record<string, string> = {};
213+for (const [key, value] of Object.entries(options?.headers ?? {})) {
214+if (key.toLowerCase() === TRACEPARENT_HEADER_NAME) {
215+continue;
216+}
217+headers[key] = value;
218+}
219+headers[TRACEPARENT_HEADER_NAME] = traceparent;
220+return {
221+ ...(options ?? {}),
222+ headers,
223+};
224+}
225+200226async function safeReturnIterator(iterator: AsyncIterator<unknown>): Promise<void> {
201227let returnResult: unknown;
202228try {
@@ -316,9 +342,10 @@ export function wrapStreamFnWithDiagnosticModelCallEvents(
316342const eventBase = baseModelCallEvent(ctx, callId, trace);
317343emitModelCallStarted(eventBase);
318344const startedAt = Date.now();
345+const propagatedOptions = withDiagnosticTraceparentHeader(options, trace);
319346320347try {
321-const result = streamFn(model, streamContext, options);
348+const result = streamFn(model, streamContext, propagatedOptions);
322349if (isPromiseLike(result)) {
323350return result.then(
324351(resolved) => observeModelCallResult(resolved, eventBase, startedAt),
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。