Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(vercel): allow nested executions in parent trace #466

Merged
merged 4 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
68 changes: 68 additions & 0 deletions integration-test/langfuse-integration-vercel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,4 +593,72 @@ describe("langfuse-integration-vercel", () => {
expect(generation.promptVersion).toBe(fetchedPrompt.version);
}
}, 10_000);

it("should nest multiple generateText call under a trace", async () => {
hassiebp marked this conversation as resolved.
Show resolved Hide resolved
const langfuse = new Langfuse();
const traceName = "parent_generate_text_multiple";

// Create parent trace
const parentTraceId = randomUUID();
langfuse.trace({ id: parentTraceId, name: traceName });
const baseRootSpanName = "root-span";

const NESTED_RUN_COUNT = 3;

for (let i = 0; i < NESTED_RUN_COUNT; i++) {
const testParams = {
traceId: parentTraceId,
modelName: "gpt-3.5-turbo",
maxTokens: 50,
prompt: "Invent a new holiday and describe its traditions.",
functionId: `${baseRootSpanName}-${i}`,
userId: "some-user-id",
sessionId: "some-session-id",
metadata: {
something: "custom",
someOtherThing: "other-value",
},
tags: ["vercel", "openai"],
};

const { traceId, modelName, maxTokens, prompt, functionId, userId, sessionId, metadata, tags } = testParams;

await generateText({
model: openai(modelName),
maxTokens,
prompt,
experimental_telemetry: {
isEnabled: true,
functionId,
metadata: {
langfuseTraceId: traceId,
userId,
sessionId,
tags,
...metadata,
},
},
});
}

await langfuse.flushAsync();
await sdk.shutdown();

// Fetch trace
const traceFetchResult = await fetchTraceById(parentTraceId);
expect(traceFetchResult.status).toBe(200);

// Validate trace
const fetchedTrace = traceFetchResult.data;
expect(fetchedTrace.name).toBe(traceName);

const rootObservations = fetchedTrace.observations
.filter((o: any) => !Boolean(o.parentObservationId))
.sort((a: any, b: any) => a.name - b.name);
hassiebp marked this conversation as resolved.
Show resolved Hide resolved

for (let i = 0; i < NESTED_RUN_COUNT; i++) {
const obs = rootObservations[i];
expect(obs.name).toBe(`${baseRootSpanName}-${i}`);
}
}, 15_000);
});
33 changes: 28 additions & 5 deletions langfuse-vercel/src/LangfuseExporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,35 +77,58 @@ export class LangfuseExporter implements SpanExporter {
const finalTraceId = userProvidedTraceId ?? traceId;
const langfusePrompt = this.parseLangfusePromptTraceAttribute(spans);

this.langfuse.trace({
const traceUpdate = {
id: finalTraceId,
name: this.parseTraceName(spans) ?? rootSpan?.name,
userId: this.parseUserIdTraceAttribute(spans),
sessionId: this.parseSessionIdTraceAttribute(spans),
tags: this.parseTagsTraceAttribute(spans).length > 0 ? this.parseTagsTraceAttribute(spans) : undefined,
};

const traceCreate = {
name: this.parseTraceName(spans) ?? rootSpan?.name,
input: this.parseInput(rootSpan),
output: this.parseOutput(rootSpan),
metadata: this.filterTraceAttributes(this.parseMetadataTraceAttribute(spans)),
};

this.langfuse.trace({
...traceUpdate,
...(!userProvidedTraceId ? traceCreate : {}),
});

for (const span of spans) {
if (this.isGenerationSpan(span)) {
this.processSpanAsLangfuseGeneration(finalTraceId, span, this.isRootAiSdkSpan(span, spans), langfusePrompt);
} else {
this.processSpanAsLangfuseSpan(finalTraceId, span, this.isRootAiSdkSpan(span, spans));
this.processSpanAsLangfuseSpan(
finalTraceId,
span,
this.isRootAiSdkSpan(span, spans),
userProvidedTraceId ? this.parseTraceName(spans) : undefined
);
}
}
}

private processSpanAsLangfuseSpan(traceId: string, span: ReadableSpan, isRootSpan: boolean): void {
private processSpanAsLangfuseSpan(
traceId: string,
span: ReadableSpan,
isRootSpan: boolean,
rootSpanName?: string
): void {
const spanContext = span.spanContext();
const attributes = span.attributes;

this.langfuse.span({
traceId,
parentObservationId: isRootSpan ? undefined : span.parentSpanId,
id: spanContext.spanId,
name: "ai.toolCall.name" in attributes ? "ai.toolCall " + attributes["ai.toolCall.name"]?.toString() : span.name,
name:
isRootSpan && rootSpanName
? rootSpanName
: "ai.toolCall.name" in attributes
? "ai.toolCall " + attributes["ai.toolCall.name"]?.toString()
: span.name,
startTime: this.hrTimeToDate(span.startTime),
endTime: this.hrTimeToDate(span.endTime),

Expand Down
Loading