🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: add span attributes for session span (#11549)
Max Deichmann60183f48fcbf
diff --git a/package.json b/package.jsonindex 3d72d0b0fc..2c94835e80 100644--- a/package.json+++ b/package.json@@ -100,4 +100,4 @@"[email protected]": "patches/[email protected]"}}-}+}\ No newline at end of filediff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex 645a4b54b8..e66ad17597 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -16,108 +16,122 @@ import {LLMApiKeySchema,logger,fetchLLMCompletion,+ contextWithLangfuseProps,} from "@langfuse/shared/src/server";+import * as opentelemetry from "@opentelemetry/api";export default async function chatCompletionHandler(req: NextRequest) {try {const body = validateChatCompletionBody(await req.json());const { userId } = await authorizeRequestOrThrow(body.projectId);- const { messages, modelParams, tools, structuredOutputSchema, streaming } =- body;-- const LLMApiKey = await prisma.llmApiKeys.findFirst({- where: {- projectId: body.projectId,- provider: modelParams.provider,- },+ const baggageCtx = contextWithLangfuseProps({+ userId: userId,+ projectId: body.projectId,});- if (!LLMApiKey)- throw new InvalidRequestError(- `No ${modelParams.provider} API key found in project. Please add one in the project settings.`,- );-- const parsedKey = LLMApiKeySchema.safeParse(LLMApiKey);- if (!parsedKey.success) {- throw new InternalServerError(- `Could not parse API key for provider ${body.modelParams.provider}: ${parsedKey.error.message}`,- );- }-- const fetchLLMCompletionParams = {- llmConnection: parsedKey.data,- messages,- modelParams,- structuredOutputSchema,- callbacks: [new PosthogCallbackHandler("playground", body, userId)],- };-- if (structuredOutputSchema) {- const result = await fetchLLMCompletion({- ...fetchLLMCompletionParams,- streaming: false,+ return opentelemetry.context.with(baggageCtx, async () => {+ const {+ messages,+ modelParams,+ tools,structuredOutputSchema,+ streaming,+ } = body;++ const LLMApiKey = await prisma.llmApiKeys.findFirst({+ where: {+ projectId: body.projectId,+ provider: modelParams.provider,+ },});- return NextResponse.json(result);- }- // If messages contain tool results, we include tools in the request- const hasToolResults = messages.some((msg) => msg.type === "tool-result");-- if ((tools && tools.length > 0) || hasToolResults) {- // Fix empty tool_call_id values by mapping to langgraph IDs- const fixedMessages = messages.map((msg) => {- if (- msg.type === "tool-result" &&- (!msg.toolCallId || msg.toolCallId === "")- ) {- const assistantMessages = messages- .filter((m) => m.type === "assistant-tool-call" && m.toolCalls)- .reverse();-- // Find the first matching tool call by name- // Note: using 'as any' because we filtered for assistant-tool-call messages above- for (const prevMsg of assistantMessages) {- const matchingToolCall = (prevMsg as any).toolCalls.find(- (tc: any) => tc.name === (msg as any)._originalRole,- );- if (matchingToolCall && matchingToolCall.id) {- return {- ...msg,- toolCallId: matchingToolCall.id,- };+ if (!LLMApiKey)+ throw new InvalidRequestError(+ `No ${modelParams.provider} API key found in project. Please add one in the project settings.`,+ );++ const parsedKey = LLMApiKeySchema.safeParse(LLMApiKey);+ if (!parsedKey.success) {+ throw new InternalServerError(+ `Could not parse API key for provider ${body.modelParams.provider}: ${parsedKey.error.message}`,+ );+ }++ const fetchLLMCompletionParams = {+ llmConnection: parsedKey.data,+ messages,+ modelParams,+ structuredOutputSchema,+ callbacks: [new PosthogCallbackHandler("playground", body, userId)],+ };++ if (structuredOutputSchema) {+ const result = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming: false,+ structuredOutputSchema,+ });+ return NextResponse.json(result);+ }++ // If messages contain tool results, we include tools in the request+ const hasToolResults = messages.some((msg) => msg.type === "tool-result");++ if ((tools && tools.length > 0) || hasToolResults) {+ // Fix empty tool_call_id values by mapping to langgraph IDs+ const fixedMessages = messages.map((msg) => {+ if (+ msg.type === "tool-result" &&+ (!msg.toolCallId || msg.toolCallId === "")+ ) {+ const assistantMessages = messages+ .filter((m) => m.type === "assistant-tool-call" && m.toolCalls)+ .reverse();++ // Find the first matching tool call by name+ // Note: using 'as any' because we filtered for assistant-tool-call messages above+ for (const prevMsg of assistantMessages) {+ const matchingToolCall = (prevMsg as any).toolCalls.find(+ (tc: any) => tc.name === (msg as any)._originalRole,+ );+ if (matchingToolCall && matchingToolCall.id) {+ return {+ ...msg,+ toolCallId: matchingToolCall.id,+ };+ }}}- }-- return msg;- });-- const result = await (fetchLLMCompletion as any)({- ...fetchLLMCompletionParams,- messages: fixedMessages,- streaming: false,- tools: tools ?? [],- });- return NextResponse.json(result);- }-- if (streaming) {- const completion = await fetchLLMCompletion({- ...fetchLLMCompletionParams,- streaming,- });-- return new StreamingTextResponse(completion);- } else {- const completion = await fetchLLMCompletion({- ...fetchLLMCompletionParams,- streaming,- });- return NextResponse.json({ content: completion });- }+ return msg;+ });++ const result = await (fetchLLMCompletion as any)({+ ...fetchLLMCompletionParams,+ messages: fixedMessages,+ streaming: false,+ tools: tools ?? [],+ });+ return NextResponse.json(result);+ }++ if (streaming) {+ const completion = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming,+ });++ return new StreamingTextResponse(completion);+ } else {+ const completion = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming,+ });++ return NextResponse.json({ content: completion });+ }+ });} catch (err) {logger.error("Failed to handle chat completion", err);diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 544010f691..6749de138b 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -611,7 +611,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {},callbacks: {async session({ session, token }): Promise<Session> {- return instrumentAsync({ name: "next-auth-session" }, async () => {+ return instrumentAsync({ name: "next-auth-session" }, async (span) => {const dbUser = await prisma.user.findUnique({where: {email: token.email!.toLowerCase(),@@ -647,6 +647,9 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {},});+ span.setAttribute("langfuse.user.email", dbUser?.email ?? "");+ span.setAttribute("langfuse.user.id", dbUser?.id ?? "");+return {...session,environment: {