← Back to Docs

LangChain Integration

Add scoped secrets, approvals, and receipts to your LangChain agents with NervePay. Keep keys safe while giving agents exactly what they need.

Why Add NervePay to LangChain?

🔑 Scoped Secrets

Agents only get access to specific keys they need—not everything in your env vars. OpenAI key stays private.

✅ Approvals

Block sensitive tool calls until you approve. Perfect for production guardrails.

📋 Receipts

Every tool call generates a receipt. Debug faster and meet compliance requirements.

Installation

bash
pip install nervepay langchain openai

Quick Example

Here's a LangChain agent that uses NervePay for scoped OpenAI access:

python
"""
LangChain agent with NervePay scoped secrets.
The agent can only use the OpenAI key we explicitly grant it.
"""
import os
from nervepay import VaultClient
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from langchain import hub
from langchain.tools import Tool
class NervePayOpenAITool:
"""Tool that fetches OpenAI key from NervePay Vault."""
def __init__(self, agent_did: str, vault_api_url: str = "https://api.nervepay.xyz"):
self.agent_did = agent_did
self.vault = VaultClient(agent_did, vault_api_url)
self._cached_key = None
def run(self, prompt: str) -> str:
"""Get OpenAI key from vault and call API directly."""
# Fetch scoped key from vault (not from env!)
if not self._cached_key:
secret = self.vault.get_secret("OPENAI_API_KEY")
self._cached_key = secret["value"]
# Use the scoped key for this call only
import openai
openai.api_key = self._cached_key
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# Initialize with your agent's DID
agent_did = os.getenv("NERVEPAY_AGENT_DID")
openai_tool = NervePayOpenAITool(agent_did)
# Create LangChain tools
tools = [
Tool(
name="openai_complete",
func=openai_tool.run,
description="Use OpenAI GPT-4 for text generation. Input: a prompt."
)
]
# Build the agent
llm = ChatOpenAI(model="gpt-4")
prompt = hub.pull("hwchase17/openai-functions-agent")
agent = create_openai_functions_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Run the agent - it uses scoped OpenAI key from vault!
result = executor.invoke({"input": "Write a haiku about coding"})
print(result["output"])

Adding Approvals

Require human approval before sensitive operations:

python
"""
LangChain agent with NervePay approval flow.
Sensitive tool calls require human approval.
"""
import os
from nervepay import VaultClient, ApprovalClient
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from langchain import hub
from langchain.tools import Tool
class ApprovalGateTool:
"""Tool that requires approval before execution."""
def __init__(self, agent_did: str):
self.agent_did = agent_did
self.vault = VaultClient(agent_did)
self.approvals = ApprovalClient(agent_did)
def run(self, action: str, **kwargs) -> str:
"""
Request approval for sensitive action.
Blocks until human approves in dashboard.
"""
# Check if approval is required for this action
if self.approvals.require_approval(action):
approval_id = self.approvals.request(
action=action,
details=kwargs,
timeout_seconds=3600 # Wait up to 1 hour
)
# This blocks until approved or times out
result = self.approvals.wait_for_decision(approval_id)
if result["status"] != "approved":
raise Exception(f"Action {action} was rejected")
# Execute the approved action
return self._execute(action, **kwargs)
def _execute(self, action: str, **kwargs) -> str:
# Your sensitive logic here
pass
# Example: Agent that can query database but requires approval
class DatabaseTool(ApprovalGateTool):
"""Tool for database queries - requires approval in production."""
def __init__(self, agent_did: str, connection_string: str):
super().__init__(agent_did)
self.connection = connection_string
def run(self, query: str) -> str:
# This will block for approval if configured
return super().run("database_query", query=query)
# Configure: Production queries require approval
agent_did = os.getenv("NERVEPAY_AGENT_DID")
db_tool = DatabaseTool(agent_did, os.getenv("DB_CONNECTION"))
# In production, every query requires approval
# In dev, you can skip approvals
result = db_tool.run("SELECT * FROM users LIMIT 10")
# → Prompt appears in dashboard for approval
# → Agent waits for approval
# → Once approved, query executes and returns results

Tracking with Receipts

Every agent action generates a receipt for audit and debugging:

python
"""
LangChain agent with receipt generation.
Every tool call is logged with full context.
"""
import os
from nervepay import ReceiptClient
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from langchain import hub
from datetime import datetime
class ReceiptedTool:
"""Base tool that automatically generates receipts."""
def __init__(self, agent_did: str):
self.agent_did = agent_did
self.receipts = ReceiptClient(agent_did)
def run(self, tool_name: str, input_data: dict, func) -> str:
"""
Execute function and generate receipt.
"""
start_time = datetime.utcnow()
# Execute the actual tool
result = func(input_data)
# Generate receipt
receipt = self.receipts.create(
agent_did=self.agent_did,
tool=tool_name,
input=input_data,
output=result,
duration_ms=(datetime.utcnow() - start_time).total_seconds() * 1000,
metadata={
"model": "gpt-4",
"timestamp": start_time.isoformat(),
}
)
return result
# Usage
agent_did = os.getenv("NERVEPAY_AGENT_DID")
receipted_openai = ReceiptedTool(agent_did)
# Every call generates a receipt automatically
result = receipted_openai.run(
tool_name="openai_complete",
input_data={"prompt": "Hello, world!"},
func=lambda x: openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": x["prompt"]}]
)
)
# View receipts in dashboard: /dashboard/agents/{did}/receipts
print("Receipt generated!")
print(f"Receipt ID: {receipt['id']}")

Setup in Dashboard

1. Create Agent

Go to Dashboard → Agent Identities → New Agent. Note your DID.

2. Add OpenAI Key to Vault

Dashboard → Your Agent → Secrets → Add Secret. Name: OPENAI_API_KEY.

3. Configure Approvals (Optional)

Set approval rules for sensitive tools in Dashboard → Approvals.