openllmetry-js
openllmetry-js copied to clipboard
feat: Add support for Langchain Callbacks
Solves Issue https://github.com/traceloop/openllmetry-js/issues/133: 🚀 Feature: re-write Langchain instrumentation to use Langchain Callbacks
⚠️ This PR is actually in WIP status until we find a way to monkey patch class constructors ⚠️
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 when handleXXEnd or handleXXError are invoked, the same span can be properly ended. To do that, we are using a stack, the logic is as follows:
- We start a
SpanwheneverhandleXXStartis called and push it into the stack. - If
handleXXEndis called:- If there are no
Spaninstances in the stack, we throw anError, ashandleXXEndcannot be called before the correspondinghandleXXStart. - Otherwise, we pop the
Spanfrom the stack, and end it accordingly.
- If there are no
- If
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:test
Integration tests (aka sample-app)
- Modified the sample-app for LangChain (this is expected to go away before merging this PR, as it's just for my own testing purposes) to:
- Not depend on OpenAI stuff, as I lack an API key 🥲
- Make it faster by just running a single workflow
- Disable manual instrumentation of LangChain modules
- Instantiate and pass the
TraceloopCallbackHandlerto check if the spans are generated properly
- Start
Ollamaservingllama2LLM by running:
docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama && docker exec -it ollama ollama run llama2
- Ran the sample app via:
TRACELOOP_API_KEY=<REDACTED> npx nx run sample-app:run:langchain
- Verified that there is a trace in my Traceloop development stage, but it lacks the spans from the
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. - For the moment, I just verified the behavior via logs.
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
Xabier Lahuerta Vázquez seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.
@Xabilahu just for my own records, linking our discussion from Slack where I suggested a solution to the problems you've raised here.