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
- Yarn
- pnpm
npm install @langchain/community
yarn add @langchain/community
pnpm add @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:
- Serialized from
@langchain/core/load/serializable
- BaseCallbackHandler from
@langchain/core/callbacks/base
- AgentAction from
@langchain/core/agents
- AgentFinish from
@langchain/core/agents
- ChainValues from
@langchain/core/utils/types
You could then use it as described in the section above.