fix(langchain): read usage_metadata via duck-typing to support multiple @langchain/core copies#843
Open
seb7152 wants to merge 1 commit into
Open
Conversation
…le @langchain/core copies The CallbackHandler extracted token usage and model name using `generation.message instanceof AIMessage / AIMessageChunk`. When the host application and @langfuse/langchain resolve different copies of @langchain/core (pnpm/bun workspaces, nested deps, n8n community nodes, etc.), the message is an instance of the *other* copy's class, so the `instanceof` checks return false. As a result usageDetails (output, output_reasoning, input_cache_read) and the model name are silently dropped, even though the model returns them. Use duck-typing instead: read `message.usage_metadata` and `message.response_metadata.model_name` directly. This is realm-independent and matches the workaround recommended in the issue. Fixes #13075 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
Someone is attempting to deploy a commit to the langfuse Team on Vercel. A member of the Team first needs to authorize it. |
Author
|
Recheck |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
CallbackHandlerextracts token usage and model name with:When the host application and
@langfuse/langchainresolve different copies of@langchain/core(pnpm/bun workspaces, nested deps, n8n community nodes, etc.), the message is an instance of the other copy's class. Cross-realminstanceofreturnsfalse, so the handler falls through toundefinedand silently dropsusageDetails(output,output_reasoning,input_cache_read) and the model name — even though the model returned them.Fixes #13075.
Fix
Use duck-typing instead of class-identity checks — read
message.usage_metadataandmessage.response_metadata.model_namedirectly. This is realm-independent and matches the workaround recommended in the issue.AIMessage/AIMessageChunkare no longer referenced, so they're removed from the import.Verification
Reproduced with
@langchain/core1.x where the message originates from a different@langchain/coreinstance than the one bundled with the langchain integration (OpenAI Chat Completions and Anthropic, via n8n'slangfuse-langchain):extractUsageMetadatareturnsundefinedfor a message that is not an instance of the bundledAIMessage→ output/reasoning tokens missing in Langfuse.usage_metadatais read correctly → output (and reasoning/cached) tokens appear.Scope intentionally limited to the usage/model extraction from #13075. The
instanceof BaseMessagechecks on chain inputs have the same theoretical fragility but are a separate concern and out of scope here.🤖 Generated with Claude Code
Greptile Summary
Replaces
instanceof AIMessage / AIMessageChunkchecks in the LangChain callback handler with duck-typed property access (?.["message"]?.usage_metadata) so that usage metadata and model name are correctly extracted even when the host application and@langfuse/langchainresolve different copies of@langchain/core.extractUsageMetadatanow readsgeneration?.["message"]?.usage_metadatadirectly, dropping the now-unnecessaryAIMessage/AIMessageChunkimports and their cross-realm-fragile identity checks.extractModelNameFromMetadatareceives the same treatment forresponse_metadata.model_name, with both changes guarded by optional chaining so non-chat generations safely returnundefined.Confidence Score: 5/5
Safe to merge — the change is a narrow, well-scoped fix that removes a silent data-loss path without altering any other behavior.
Both helpers now read the relevant fields via optional-chaining duck-typed access instead of instanceof class-identity checks. Non-chat generations fall through to undefined exactly as before, the downstream ?? fallback chain in handleLLMEnd is untouched, and the removed imports were the only consumers of AIMessage/AIMessageChunk in the file. No new code paths are introduced.
No files require special attention.
Sequence Diagram
%%{init: {'theme': 'neutral'}}%% sequenceDiagram participant LLM as LLM / Chain participant CH as CallbackHandler participant EU as extractUsageMetadata() participant EM as extractModelNameFromMetadata() LLM->>CH: handleLLMEnd(output, runId) CH->>CH: "lastResponse = output.generations[last][last]" CH->>EU: extractUsageMetadata(lastResponse) Note over EU: Before: instanceof AIMessage/AIMessageChunk<br/>(fails across @langchain/core copies) Note over EU: After: (generation as any)?.["message"]?.usage_metadata<br/>(duck-typing, realm-independent) EU-->>CH: "UsageMetadata | undefined" CH->>EM: extractModelNameFromMetadata(lastResponse) Note over EM: Before: instanceof check + response_metadata.model_name<br/>After: generation?.["message"]?.response_metadata?.model_name EM-->>CH: "string | undefined" CH->>CH: Build usageDetails, update span%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% sequenceDiagram participant LLM as LLM / Chain participant CH as CallbackHandler participant EU as extractUsageMetadata() participant EM as extractModelNameFromMetadata() LLM->>CH: handleLLMEnd(output, runId) CH->>CH: "lastResponse = output.generations[last][last]" CH->>EU: extractUsageMetadata(lastResponse) Note over EU: Before: instanceof AIMessage/AIMessageChunk<br/>(fails across @langchain/core copies) Note over EU: After: (generation as any)?.["message"]?.usage_metadata<br/>(duck-typing, realm-independent) EU-->>CH: "UsageMetadata | undefined" CH->>EM: extractModelNameFromMetadata(lastResponse) Note over EM: Before: instanceof check + response_metadata.model_name<br/>After: generation?.["message"]?.response_metadata?.model_name EM-->>CH: "string | undefined" CH->>CH: Build usageDetails, update spanReviews (1): Last reviewed commit: "fix(langchain): read usage_metadata via ..." | Re-trigger Greptile