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
pip install nervepay langchain openai
Quick Example
Here's a LangChain agent that uses NervePay for scoped OpenAI access:
"""LangChain agent with NervePay scoped secrets.The agent can only use the OpenAI key we explicitly grant it."""import osfrom nervepay import VaultClientfrom langchain.agents import AgentExecutor, create_openai_functions_agentfrom langchain_openai import ChatOpenAIfrom langchain import hubfrom langchain.tools import Toolclass 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_didself.vault = VaultClient(agent_did, vault_api_url)self._cached_key = Nonedef 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 onlyimport openaiopenai.api_key = self._cached_keyresponse = openai.ChatCompletion.create(model="gpt-4",messages=[{"role": "user", "content": prompt}])return response.choices[0].message.content# Initialize with your agent's DIDagent_did = os.getenv("NERVEPAY_AGENT_DID")openai_tool = NervePayOpenAITool(agent_did)# Create LangChain toolstools = [Tool(name="openai_complete",func=openai_tool.run,description="Use OpenAI GPT-4 for text generation. Input: a prompt.")]# Build the agentllm = 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:
"""LangChain agent with NervePay approval flow.Sensitive tool calls require human approval."""import osfrom nervepay import VaultClient, ApprovalClientfrom langchain.agents import AgentExecutor, create_openai_functions_agentfrom langchain_openai import ChatOpenAIfrom langchain import hubfrom langchain.tools import Toolclass ApprovalGateTool:"""Tool that requires approval before execution."""def __init__(self, agent_did: str):self.agent_did = agent_didself.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 actionif 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 outresult = self.approvals.wait_for_decision(approval_id)if result["status"] != "approved":raise Exception(f"Action {action} was rejected")# Execute the approved actionreturn self._execute(action, **kwargs)def _execute(self, action: str, **kwargs) -> str:# Your sensitive logic herepass# Example: Agent that can query database but requires approvalclass 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_stringdef run(self, query: str) -> str:# This will block for approval if configuredreturn super().run("database_query", query=query)# Configure: Production queries require approvalagent_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 approvalsresult = 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:
"""LangChain agent with receipt generation.Every tool call is logged with full context."""import osfrom nervepay import ReceiptClientfrom langchain.agents import AgentExecutor, create_openai_functions_agentfrom langchain_openai import ChatOpenAIfrom langchain import hubfrom datetime import datetimeclass ReceiptedTool:"""Base tool that automatically generates receipts."""def __init__(self, agent_did: str):self.agent_did = agent_didself.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 toolresult = func(input_data)# Generate receiptreceipt = 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# Usageagent_did = os.getenv("NERVEPAY_AGENT_DID")receipted_openai = ReceiptedTool(agent_did)# Every call generates a receipt automaticallyresult = 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}/receiptsprint("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.