Skip to main content

LangChain toolkit for KeeperHub — reliable onchain execution, DeFi protocol actions, and AI workflow generation for any LangChain agent

Project description

langchain-keeperhub

PyPI Python License

LangChain toolkit for KeeperHub — reliable onchain execution, DeFi automation, and AI workflow generation for any LangChain or LangGraph agent.

Why langchain-keeperhub?

Feature This package Other Web3 toolkits
Tools 10 (chains + ABI + transfer + contract + check-execute + gas + 4× workflows) 4–6
Never-throws pattern ok/summary/is_retryable on every tool ❌ raises on error
Prompt injection protection ✅ sanitized workflow metadata ❌ raw injection
Execution polling ✅ built-in (2 min timeout) ❌ you poll manually
System prompt builder ✅ live workflow list ❌ static
Async-first httpx.AsyncClient mixed
Proxy-aware ABI ✅ resolves EIP-1967/UUPS/Diamond

Install

pip install langchain-keeperhub

Quick start

import asyncio
import os

from langchain_keeperhub import KeeperHubToolkit
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

async def main():
    toolkit = KeeperHubToolkit()          # reads KEEPERHUB_API_KEY from env
    llm = ChatOpenAI(model="gpt-4o")

    system = await toolkit.build_system_prompt()   # injects live workflow list
    agent = create_react_agent(llm, toolkit.get_tools(), state_modifier=system)

    result = await agent.ainvoke({
        "messages": [{"role": "user", "content": "What chains does KeeperHub support?"}]
    })
    print(result["messages"][-1].content)

asyncio.run(main())

Set your API key:

export KEEPERHUB_API_KEY=kh_live_...

Tools reference

Chain discovery

Tool Description
keeperhub_list_chains All supported networks with chain IDs, symbols, explorer URLs
keeperhub_fetch_contract_abi Verified ABI — auto-resolves proxy patterns (EIP-1967, UUPS, Diamond)

Web3 execution

Tool Description
keeperhub_transfer_funds Send ETH or any ERC-20 token
keeperhub_contract_call Read (call_type="read") or write (call_type="write") any contract function
keeperhub_check_and_execute Atomic condition check + action — no race conditions
keeperhub_estimate_gas Estimate gas cost (ETH + USD) before submitting a write tx

Workflow automation

Tool Description
keeperhub_list_workflows Browse your org's saved workflows
keeperhub_execute_workflow Run a workflow by ID, blocks until complete (2-min timeout)
keeperhub_generate_workflow Create a new workflow from a plain-English description
keeperhub_get_execution_status Poll execution status + step logs

Selective tools

Load only the tools your agent needs:

toolkit = KeeperHubToolkit(
    tools=["list_workflows", "execute_workflow", "execution_status"]
)

Valid keys: list_chains, fetch_abi, transfer, contract_call, check_and_execute, estimate_gas, list_workflows, execute_workflow, generate_workflow, execution_status.


Observability / session context

Pass metadata that appears in KeeperHub execution logs and traces:

toolkit = KeeperHubToolkit(
    agent_context={
        "session_id": conversation_id,
        "run_id":     agent_run_id,
        "goal":       "Rebalance DeFi portfolio for user",
    }
)

These map to X-Agent-Session-Id, X-Agent-Run-Id, and X-Agent-Goal headers on every request.


System prompt builder

system = await toolkit.build_system_prompt(include_workflows=True)
# Returns a ready-to-use prompt fragment that:
# - Lists all 10 tools with usage guidance
# - Injects your org's live workflow names (sanitized against prompt injection)
# - Falls back gracefully if the API is unavailable

Never-throws design

Every tool returns a JSON string — never raises. The agent always has a path forward:

{
  "ok": false,
  "summary": "Workflow wf_abc failed with status 'error'. Execution ID: exec_xyz.",
  "execution_id": "exec_xyz",
  "status": "error",
  "is_retryable": true,
  "suggestion": "Check keeperhub_get_execution_status for details."
}

Agent reasoning guide baked into every tool description:

  1. keeperhub_list_workflows first — reuse before generating
  2. keeperhub_generate_workflowkeeperhub_execute_workflow for new automations
  3. For write calls: poll with keeperhub_get_execution_status
  4. If ok=false and is_retryable=true: retry once, then report failure
  5. Always surface summary to the user — it's written for humans

Direct tool usage (without toolkit)

from langchain_keeperhub import KeeperHubClient, ListChainsTool, ExecuteWorkflowTool

client = KeeperHubClient(api_key="kh_live_...")

chains_tool = ListChainsTool(client=client)
wf_tool = ExecuteWorkflowTool(client=client)

chains = await chains_tool._arun()
result = await wf_tool._arun(workflow_id="wf_abc123", input={"amount": "0.01"})

Context manager (resource cleanup)

async with KeeperHubToolkit() as toolkit:
    tools = toolkit.get_tools()
    # ... use tools
# httpx.AsyncClient is closed automatically

Configuration

KeeperHubToolkit(
    api_key="kh_live_...",           # default: KEEPERHUB_API_KEY env var
    base_url="https://app.keeperhub.com",  # default
    timeout=30.0,                    # per-request timeout in seconds
    tools=None,                      # None = all 10 tools
    agent_context=None,              # dict with session_id, run_id, goal
)

LangGraph full example

import asyncio
from langchain_keeperhub import KeeperHubToolkit
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

async def main():
    async with KeeperHubToolkit(
        agent_context={"session_id": "demo-001", "goal": "DeFi portfolio management"}
    ) as toolkit:
        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        system_prompt = await toolkit.build_system_prompt()
        agent = create_react_agent(
            llm,
            toolkit.get_tools(),
            state_modifier=system_prompt,
        )

        result = await agent.ainvoke({
            "messages": [{
                "role": "user",
                "content": (
                    "Swap 0.01 ETH for USDC on Base. "
                    "Check if a workflow exists first, otherwise create one."
                ),
            }]
        })

        for msg in result["messages"]:
            print(f"[{msg.type}] {msg.content[:200]}")

asyncio.run(main())

Requirements

  • Python ≥ 3.10
  • httpx >= 0.27
  • langchain-core >= 0.2
  • pydantic >= 2.0

Optional (for running agents):

pip install langchain-openai langgraph python-dotenv

License

Apache 2.0 — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

keeperhub_langchain-0.1.0.tar.gz (42.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

keeperhub_langchain-0.1.0-py3-none-any.whl (47.2 kB view details)

Uploaded Python 3

File details

Details for the file keeperhub_langchain-0.1.0.tar.gz.

File metadata

  • Download URL: keeperhub_langchain-0.1.0.tar.gz
  • Upload date:
  • Size: 42.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for keeperhub_langchain-0.1.0.tar.gz
Algorithm Hash digest
SHA256 93c223cc33f31c524bfc2297b04965c5da0f3764ae60912dca585f6a0de9eb32
MD5 1b8bb79cc612fa769875d544c308a0bd
BLAKE2b-256 6392bc93f8b10e19f8e833d42abc24a450f621904b4d7bf439d67b34912698d7

See more details on using hashes here.

File details

Details for the file keeperhub_langchain-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for keeperhub_langchain-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b8088fd336fdff08c55dd0068e6e0ed2c6592943a245ff19ef7f2c9b5e956571
MD5 44ba49e1ebdcc2f80c76fcdd9f23d17e
BLAKE2b-256 4acf9cc1fd248737053bde7a048a14df260b3a24e625229faecafeddee452ba6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page