Skip to main content

Creating custom callback handlers

You can also create your own handler by implementing the BaseCallbackHandler interface. This is useful if you want to do something more complex than just logging to the console, eg. send the events to a logging service. As an example here is a simple implementation of a handler that logs to the console:

npm install @langchain/community
import { Serialized } from "@langchain/core/load/serializable";
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
import { AgentAction, AgentFinish } from "@langchain/core/agents";
import { ChainValues } from "@langchain/core/utils/types";

export class MyCallbackHandler extends BaseCallbackHandler {
name = "MyCallbackHandler";

async handleChainStart(chain: Serialized) {
console.log(`Entering new ${chain.id} chain...`);
}

async handleChainEnd(_output: ChainValues) {
console.log("Finished chain.");
}

async handleAgentAction(action: AgentAction) {
console.log(action.log);
}

async handleToolEnd(output: string) {
console.log(output);
}

async handleText(text: string) {
console.log(text);
}

async handleAgentEnd(action: AgentFinish) {
console.log(action.log);
}
}

API Reference:

You could then use it as described in the section above.


Help us out by providing feedback on this documentation page: