# LangChain Implementation Example

This guide shows how to integrate Boson Protocol commerce capabilities into a LangChain AI agent. The [bosonprotocol/agent-builder](https://github.com/bosonprotocol/agent-builder) repository contains different AI agent examples using Boson tools, with the [LangChain](https://js.langchain.com/docs/tutorials/) example at [`src/examples/standalone/langchain/index.ts`](https://github.com/bosonprotocol/agent-builder/blob/main/src/examples/standalone/langchain/index.ts).

## Integration Code Snippets

### 1. Getting Boson Tools

```typescript
import { bosonProtocolPlugin } from "@bosonprotocol/agentic-commerce";
import { BOSON_MCP_URL, CHAIN_MAP } from "@common/chains.ts";
import { getOnChainTools } from "@goat-sdk/adapter-langchain";
import { viem } from "@goat-sdk/wallet-viem";

// Get tools with the Boson Protocol plugin
const tools = await getOnChainTools({
  wallet: viem(walletClient),
  plugins: [bosonProtocolPlugin({ url: bosonMcpUrl })],
});

console.log(
  "Available tools:",
  tools.map((tool: any) => tool.name),
);
```

### 2. LangChain Agent Integration

```typescript
import { ChatAnthropic } from "@langchain/anthropic";
import { AgentExecutor, createStructuredChatAgent } from "langchain/agents";
import { pull } from "langchain/hub";

// Initialize LLM
const llm = new ChatAnthropic({
  apiKey: anthropicApiKey,
  model: "claude-4-sonnet-20250514", // change model as needed,
  temperature: 0,
});

// Pull the structured chat agent system prompt from LangChain Hub
const systemPrompt = await pull<ChatPromptTemplate>(
  "hwchase17/structured-chat-agent",
);

// Create structured chat agent
const agent = await createStructuredChatAgent({
  llm,
  tools: tools as any, // Type assertion to resolve complex type inference
  prompt: systemPrompt,
});

const agentExecutor = new AgentExecutor({
  agent,
  tools: tools as any,
});
```

## Transaction Signing

The example shows how wallet setup enables automatic transaction signing through the GOAT SDK plugin:

```typescript
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";

// Validate and format private key
const privateKey = rawPrivateKey.startsWith("0x")
  ? rawPrivateKey
  : `0x${rawPrivateKey}`;

if (privateKey.length !== 66) {
  throw new Error(
    `Invalid private key length: expected 66 characters (0x + 64 hex), got ${privateKey.length}`,
  );
}

if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
  throw new Error("Invalid private key format: must be hex string");
}

const account = privateKeyToAccount(privateKey as `0x${string}`);

const walletClient = createWalletClient({
  account,
  chain,
  transport: http(rpcUrl),
});

// Check wallet balance before proceeding
const publicClient = createPublicClient({
  chain,
  transport: http(rpcUrl),
});

const balance = await publicClient.getBalance({ address: account.address });

if (balance === 0n) {
  console.error("❌ Wallet has no balance!");
  console.log("💳 Your address:", account.address);
  process.exit(1);
}
```

When you provide this wallet client to the GOAT SDK plugin, it handles all transaction signing automatically when the agent calls Boson tools.

## Required Environment Variables

```bash
BOSON_MCP_URL=https://boson-mcp-server-staging-170470978472.europe-west2.run.app/mcp
CHAIN_ID=80002
PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
ANTHROPIC_API_KEY=sk-ant-api03-...
```

## Agent Usage Example

```typescript
const result = await agentExecutor.invoke({
  input: prompt,
  chat_history: chatHistory,
});

console.log(result.output);

// Add messages to chat history for context in next interaction
chatHistory.push(new HumanMessage(prompt));
chatHistory.push(new AIMessage(result.output));
```

## Key Dependencies

```json
{
  "dependencies": {
    "@bosonprotocol/agentic-commerce": "^1.0.0-alpha.90",
    "@goat-sdk/adapter-langchain": "^0.2.12",
    "@goat-sdk/wallet-viem": "^0.3.0",
    "@langchain/anthropic": "^0.3.26",
    "@langchain/core": "^0.3.72",
    "langchain": "^0.3.6"
  }
}
```

## Additional Examples

Other framework implementations in the repository:

* [**Vercel AI SDK**](https://github.com/bosonprotocol/agent-builder/tree/main/src/examples/standalone/vercel)
* [**Telegram Bot**](https://github.com/bosonprotocol/agent-builder/tree/main/src/examples/telegram/vercel)
* [**Email Integration**](https://github.com/bosonprotocol/agent-builder/tree/main/src/examples/email)

## Next Steps

1. **Clone the Repository**: [Get the complete working example](https://github.com/bosonprotocol/agent-builder)
2. **Set Environment Variables**: Configure for your target network
3. **Optional - Local Development Setup**: For local testing, fork the [agentic-commerce repository](https://github.com/bosonprotocol/agentic-commerce) and follow these steps:

   **Step 1: Install and Build**

   ```bash
   npm ci
   npm run build
   ```

   **Step 2: Start E2E Services**

   ```bash
   npm run e2e:boson:services
   # Keep this terminal running
   ```

   **Step 3: Start MCP Server (New Terminal)**

   ```bash
   npm run dev:boson:http
   # Keep this terminal running
   ```

   **Step 4: Optional - Start Inspector (New Terminal)**

   ```bash
   npm run dev:boson:http:inspector
   ```

   **Prerequisites:**

   * Make sure you have `.env` file configured
   * Ensure `mcpServer.json` exists in project root
4. **Run the Example**: Test the integration with your setup


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.bosonprotocol.io/v2.4.2/using-the-protocol/agent-integration/langchain-implementation-example.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
