# LangChain

SpriusAI integrates with LangChain by implementing custom `Tool` classes that call the SpriusAI HTTP API. Add vault payment capabilities to any LangChain agent or graph.

***

## TypeScript

```typescript
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { ChatAnthropic } from "@langchain/anthropic";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const BASE = "https://api.spriusai.com/v1";
const headers = {
  "Authorization": `Bearer ${process.env.SPRIUS_API_KEY}`,
  "Content-Type": "application/json",
};
const WALLET_ID = process.env.SPRIUS_WALLET_ID!;

const spriusPay = tool(
  async ({ to, amount, memo }) => {
    const res = await fetch(`${BASE}/payments`, {
      method: "POST",
      headers,
      body: JSON.stringify({ walletId: WALLET_ID, to, amount, currency: "USDC", memo }),
    });
    const tx = await res.json();
    return JSON.stringify({ status: "confirmed", tx_signature: tx.txSignature, amount, recipient: to });
  },
  {
    name: "sprius_pay",
    description: "Send a USDC payment from this agent's wallet. Use when the agent needs to pay for an API, service, or data source.",
    schema: z.object({
      to: z.string().describe("Recipient Solana address or domain (e.g. 'api.perplexity.ai')"),
      amount: z.string().describe("USDC amount as a decimal string (e.g. '2.50')"),
      memo: z.string().optional().describe("Human-readable payment description"),
    }),
  }
);

const spriusBalance = tool(
  async () => {
    const res = await fetch(`${BASE}/wallets/${WALLET_ID}`, { headers });
    const wallet = await res.json();
    return JSON.stringify({ usdc_balance: wallet.balance });
  },
  {
    name: "sprius_balance",
    description: "Check the current USDC balance of this agent's wallet. Use before making payments to verify sufficient funds.",
    schema: z.object({}),
  }
);

const agent = createReactAgent({
  llm: new ChatAnthropic({ model: "claude-opus-4-6" }),
  tools: [spriusPay, spriusBalance],
});
```

***

## Python

```python
from langchain_core.tools import tool
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent
import requests
import os

BASE = "https://api.spriusai.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SPRIUS_API_KEY']}", "Content-Type": "application/json"}
WALLET_ID = os.environ["SPRIUS_WALLET_ID"]


@tool
def sprius_pay(to: str, amount: str, memo: str = "") -> str:
    """Send a USDC payment from this agent's wallet. Use when the agent needs to pay for an API, service, or data source.

    Args:
        to: Recipient Solana address or domain (e.g. 'api.perplexity.ai')
        amount: USDC amount as a decimal string (e.g. '2.50')
        memo: Human-readable payment description
    """
    res = requests.post(
        f"{BASE}/payments",
        headers=HEADERS,
        json={"walletId": WALLET_ID, "to": to, "amount": amount, "currency": "USDC", "memo": memo},
    )
    tx = res.json()
    return f"Payment confirmed. tx_signature={tx['txSignature']} amount={amount} recipient={to}"


@tool
def sprius_balance() -> str:
    """Check the current USDC balance of this agent's wallet. Use before making payments to verify sufficient funds."""
    res = requests.get(f"{BASE}/wallets/{WALLET_ID}", headers=HEADERS)
    return f"USDC balance: {res.json()['balance']}"


agent = create_react_agent(
    model=ChatAnthropic(model="claude-opus-4-6"),
    tools=[sprius_pay, sprius_balance],
)
```

***

## Available tool operations

| Tool name             | Description                 |
| --------------------- | --------------------------- |
| `sprius_pay`          | Send USDC to a recipient    |
| `sprius_balance`      | Get current USDC balance    |
| `sprius_transactions` | List recent transactions    |
| `sprius_pay_agent`    | Initiate A2A escrow payment |

Implement `sprius_transactions` and `sprius_pay_agent` following the same pattern — call `GET /v1/wallets/{id}/transactions` and `POST /v1/payments/a2a` respectively.

***

## Example: agent that purchases data

```python
from langchain_core.messages import HumanMessage

result = agent.invoke({
    "messages": [
        HumanMessage(content=(
            "Check my balance, then pay $1.50 to api.serper.dev with memo "
            "'market research query' if I have sufficient funds."
        ))
    ]
})
```


---

# 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.spriusai.com/integrations/langchain.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.
