LangChain.js Basic

Trace LangChain.js with NjiraAI callbacks and enforce at tool boundaries.

This example shows how to trace LangChain.js runs and wrap tools for enforcement.

Full code

import { NjiraAI } from "@njiraai/sdk";
import { NjiraCallbackHandler, wrapTool } from "@njiraai/langchain";
import { ChatOpenAI } from "@langchain/openai";

const njira = new NjiraAI({
  apiKey: process.env.NJIRA_API_KEY!,
  projectId: process.env.NJIRA_PROJECT_ID!,
  mode: "active",
});

// Create callback handler for automatic tracing
const handler = new NjiraCallbackHandler(njira);

// Initialize LLM
const llm = new ChatOpenAI({
  modelName: "gpt-4o-mini",
  temperature: 0,
});

// Example tool
const calculator = (expression: string): string => {
  try {
    // Simple eval for demo - use a proper math parser in production
    return String(eval(expression));
  } catch {
    return "Error: invalid expression";
  }
};

// Wrap tool for enforcement
const safeCalculator = wrapTool(calculator, njira, {
  toolName: "calculator",
  description: "Evaluates math expressions",
});

async function main() {
  // Traced LLM call with callback
  const response = await llm.invoke("What is 2 + 2?", {
    callbacks: [handler],
  });

  console.log("LLM response:", response.content);

  // Enforced tool call
  const result = await safeCalculator("2 + 2");
  console.log("Calculator result:", result);

  // Flush traces
  await njira.trace.flush();
}

main().catch(console.error);

Run it

cd sdks/typescript/examples/langchain-basic
pnpm install
NJIRA_API_KEY=your-key NJIRA_PROJECT_ID=your-project OPENAI_API_KEY=your-openai-key pnpm start

What's happening

  1. NjiraCallbackHandler automatically captures spans for LLM calls, chains, and tool invocations
  2. wrapTool adds pre/post enforcement around tool execution
  3. Traces are flushed at the end to ensure delivery