feat: Add support for Langchain Callbacks #176
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.
Solves Issue #133: 🚀 Feature: re-write Langchain instrumentation to use Langchain Callbacks
Implemented a
BaseCallbackHandler(source for the interface). The main idea is that the handler has some state for each of the spans it starts, so that whenhandleXXEndorhandleXXErrorare invoked, the same span can be properly ended. To do that, we are using a stack, the logic is as follows:SpanwheneverhandleXXStartis called and push it into the stack.handleXXEndis called:Spaninstances in the stack, we throw anError, ashandleXXEndcannot be called before the correspondinghandleXXStart.Spanfrom the stack, and end it accordingly.handleXXErroris called, we follow a similar logic as forhandleXXEnd.This approach has the benefit of being able to properly handle nested spans.
Tests
Unit tests
npm run build:all && npx nx run @traceloop/instrumentation-langchain:testIntegration tests (aka sample-app)
TraceloopCallbackHandlerto check if the spans are generated properlyOllamaservingllama2LLM by running:CallbackHandler, as I'm using aProxyTracerProvider, which defaults to NoOp tracer when no delegate is provided. This behavior should change, and spans will be sent once we manage to mockey-patch LangChain constructors, and inject theCallbackHandlerin constructor params.