# @osohq/langchain

Oso integration for LangChain 0.x agents.

Callback handler that automatically captures and sends all LangChain agent events to Oso for monitoring, debugging, and security analysis.

## Installation

```bash
npm install @osohq/langchain
```

Or with yarn:

```bash
yarn add @osohq/langchain
```

## Quick Start

```typescript
import { OsoCallback } from "@osohq/langchain";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { ChatOpenAI } from "@langchain/openai";

// Create the callback (reads API key from OSO_AUTH environment variable)
const callback = new OsoCallback({
  agentId: "my-support-agent",
});

// Create your agent
const llm = new ChatOpenAI({ model: "gpt-4" });
const tools = [tool1, tool2, tool3];
const prompt = "You help.";
const agent = await createReactAgent({ llm, tools, prompt });

// Use your agent -- NOTE: make sure you pass the callback into
// the `invoke` method, rather than attaching it to a particular
// LangGraph node, so that all events are captured.
const result = await agent.invoke({
  input: "help!",
}, {
  callbacks: [callback],
});
```

## Configuration

### Environment Variables

Set these in your environment:

```bash
# Required: Your Oso API key
OSO_AUTH=your-oso-api-key

# Optional: Custom Oso endpoint (defaults to https://cloud.osohq.com)
OSO_URL=https://cloud.osohq.com
```

### Constructor Parameters

```typescript
new OsoCallback({
  url: "https://cloud.osohq.com", // Oso API URL (default: OSO_URL env var or https://cloud.osohq.com)
  apiKey: "your-api-key", // Oso API key (default: OSO_AUTH env var)
  agentId: "my-agent", // Agent identifier for tracking (default: "default-agent")
  sessionId: "unique-session-uuid", // Session ID to group related conversations (default: auto-generated UUID)
  users: [{ type: "User", id: "user-123" }], // Users associated with this session
  metadata: { environment: "production" }, // Additional metadata to attach to all events
  logger: (level, message, metadata) => console.log(level, message, metadata), // Custom logging function
});
```

All parameters are optional and fall back to environment variables or defaults.

## Error Handling

The callback is designed to fail gracefully:

- Network errors or timeouts won't crash your agent
- Failed event sends are logged but don't interrupt execution
- Comprehensive error logging for debugging

## Logging

The callback supports custom logging through the `logger` configuration option:

```typescript
const callback = new OsoCallback({
  agentId: "my-agent",
  logger: (level, message, metadata) => {
    console.log(`[${level.toUpperCase()}] ${message}`, metadata);
  },
});
```

The logger function receives three parameters:
- `level`: One of "error", "warn", "info", or "debug"
- `message`: The log message string
- `metadata`: Optional additional context (object)

## Examples

### Basic Agent with Tools

```typescript
import { OsoCallback } from "@osohq/langchain";
import { createOpenAIToolsAgent, AgentExecutor } from "langchain/agents";
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

const searchOrders = tool(
  async ({ customerId }: { customerId: string }) => {
    return `Orders for ${customerId}: ORD001, ORD002`;
  },
  {
    name: "search_orders",
    description: "Search for customer orders.",
    schema: z.object({
      customerId: z.string().describe("The customer ID"),
    }),
  }
);

async function main() {
  const callback = new OsoCallback({ agentId: "support-agent" });

  const llm = new ChatOpenAI({ model: "gpt-4o-mini" });
  const tools = [searchOrders];

  const agent = await createOpenAIToolsAgent({ llm, tools, prompt });
  const agentExecutor = new AgentExecutor({ agent, tools });

  const result = await agentExecutor.invoke(
    { input: "Find orders for customer CUST001" },
    { callbacks: [callback] }
  );

  console.log(result);
}
```

### With Custom Metadata and Users

```typescript
const callback = new OsoCallback({
  agentId: "support-agent",
  sessionId: "user-session-123",
  users: [{ type: "User", id: "user-456" }],
  metadata: {
    environment: "production",
    version: "1.2.3",
  },
});
```

### Multiple Agents in Same Session

```typescript
import { randomUUID } from "crypto";

const sessionId = randomUUID();

// Agent 1
const callback1 = new OsoCallback({
  agentId: "agent-1",
  sessionId,
});
const result1 = await agent1Executor.invoke(
  { input: "..." },
  { callbacks: [callback1] }
);

// Agent 2 - same session
const callback2 = new OsoCallback({
  agentId: "agent-2",
  sessionId,
});
const result2 = await agent2Executor.invoke(
  { input: "..." },
  { callbacks: [callback2] }
);
```

## TypeScript Support

This package is written in TypeScript and includes full type definitions. All types are exported for your convenience.

## Requirements

- Node.js 20.0.0 or higher
- @langchain/core >=0.1.0, <1.0.0

## License

Apache License 2.0

## Support

- Documentation: https://www.osohq.com/docs
- Website: https://www.osohq.com
