langchain-call402 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: langchain-call402
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for Call402, the x402 pay-per-call API by SteadyScrape
5
+ Author-email: "SteadyScrape S.R.L." <hello@call402.dev>
6
+ License: MIT
7
+ Project-URL: Homepage, https://call402.dev
8
+ Project-URL: Terms, https://call402.dev/terms
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: langchain-core<2,>=1.0
12
+ Requires-Dist: httpx<1,>=0.27
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=8; extra == "test"
15
+
16
+ # langchain-call402
17
+
18
+ LangChain tools for [Call402](https://call402.dev), the pay-per-call API by SteadyScrape. It wraps the existing Call402 REST routes and x402 payment flow, with no extra logic.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install "git+https://github.com/steadyscrape/call402-wrappers.git#subdirectory=langchain-call402"
24
+ pip install "x402[evm]==2.29.0" # only if you want the tool to pay
25
+ ```
26
+
27
+ Tested with Python 3.13, `langchain-core==1.8.5`, `httpx==0.28.1`, `x402==2.29.0`. Declared ranges: `langchain-core>=1.0,<2`, `httpx>=0.27,<1`.
28
+
29
+ ## How payment works
30
+
31
+ Call402 charges per successful call in USDC on Base (`eip155:8453`) using x402 v2, settled through the PayAI facilitator. An unpaid POST returns HTTP 402 with a `PAYMENT-REQUIRED` header (price, asset, pay-to address). If you pass a `payment_signer`, the tool hands it those requirements, sends the signed `PAYMENT-SIGNATURE` back once, and returns the result with the settlement in `payment_response`. This package holds no wallet and no keys: the signer is your code with your wallet. Without a signer, or if the signer returns `None`, the 402 is raised with the requirements attached and nothing is charged. Empty or invalid input returns 400 and is not charged. Failed, timed-out or empty results are never settled. Errors are raised, not hidden.
32
+
33
+ ## Worked example
34
+
35
+ ```python
36
+ # pip install "x402[evm]==2.29.0" (tested; your wallet, your key, never ours)
37
+ import os
38
+ from eth_account import Account
39
+ from x402 import x402ClientSync
40
+ from x402.http import x402HTTPClientSync
41
+ from x402.mechanisms.evm.exact import register_exact_evm_client
42
+ from x402.mechanisms.evm.signers import EthAccountSigner
43
+ from x402.schemas import PaymentRequired
44
+
45
+ account = Account.from_key(os.environ["MY_BASE_WALLET_KEY"]) # a Base wallet holding a little USDC
46
+ x402_http = x402HTTPClientSync(register_exact_evm_client(x402ClientSync(), EthAccountSigner(account)))
47
+
48
+ def pay(payment_required: dict) -> str:
49
+ """Sign the 402 requirements with your wallet; return the PAYMENT-SIGNATURE header."""
50
+ payload = x402_http.create_payment_payload(PaymentRequired.model_validate(payment_required))
51
+ return x402_http.encode_payment_signature_header(payload)["PAYMENT-SIGNATURE"]
52
+ ```
53
+
54
+ ```python
55
+ from langchain_call402 import get_call402_tools, Call402ToolException
56
+
57
+ tools = get_call402_tools(payment_signer=pay) # all 19; or include=["domain_expiry"]
58
+ domain_expiry = next(t for t in tools if t.name == "domain_expiry")
59
+ print(domain_expiry.invoke({"domain": "example.com"})) # $0.01 if a result comes back
60
+
61
+ # Without a signer the 402 comes back to you, nothing charged:
62
+ [unpaid] = get_call402_tools(include=["domain_expiry"])
63
+ try:
64
+ unpaid.invoke({"domain": "example.com"})
65
+ except Call402ToolException as e:
66
+ print(e.error.status, e.error.charged, e.error.payment_required["accepts"][0]["amount"]) # 402 False 10000
67
+
68
+ # In an agent: pass `tools` to any tool-calling model, e.g. model.bind_tools(tools)
69
+ # or langchain.agents.create_agent(model, tools). Set handle_errors=True if the
70
+ # agent should see the 402/400 text as the tool result instead of an exception.
71
+ ```
72
+
73
+ ## The 19 tools
74
+
75
+ Read from `https://api.call402.dev/v1/tools` and `/v1/pricing` on 2026-11-29. The package ships this list as `catalog.json`; pass `live_catalog=True` to read it from the API at runtime instead.
76
+
77
+ | Tool | What it does | Route | Price per successful call |
78
+ |---|---|---|---|
79
+ | `company_jobs` | Open jobs at a company | `POST /v1/jobs` | $0.01 |
80
+ | `company_profile` | Company profile from its website | `POST /v1/company-profile` | $0.01 |
81
+ | `hiring_summary` | Company hiring summary | `POST /v1/hiring-summary` | $0.02 |
82
+ | `uk_company` | UK company record (Companies House) | `POST /v1/uk-company` | $0.01 |
83
+ | `keyword_suggestions` | Keyword suggestions (autocomplete) | `POST /v1/keyword-suggestions` | $0.01 |
84
+ | `seo_audit` | Technical SEO audit of a page | `POST /v1/seo-audit` | $0.01 |
85
+ | `domain_expiry` | Domain expiry and registration (RDAP) | `POST /v1/domain-expiry` | $0.01 |
86
+ | `form_d_filings` | SEC Form D funding rounds | `POST /v1/form-d-filings` | $0.02 |
87
+ | `job_search` | Job search across career sites | `POST /v1/job-search` | $0.02 |
88
+ | `pdf_to_markdown` | PDF text to markdown | `POST /v1/pdf-to-markdown` | $0.01 |
89
+ | `patent_search` | Google Patents search and details | `POST /v1/patents` | $0.01 |
90
+ | `website_screenshot` | Website screenshot | `POST /v1/screenshot` | $0.01 |
91
+ | `product_price` | Product price and stock check | `POST /v1/product-price` | $0.01 |
92
+ | `str_profit_calculator` | STR Profit Calculator (STR Profit Tracker, KeyLedgerDesigns) | `POST /v1/str-profit-calculator` | $0.01 |
93
+ | `guest_message_script` | Guest Message Script (Guest Message Library, KeyLedgerDesigns) | `POST /v1/guest-message-script` | $0.01 |
94
+ | `content_calendar` | 90-Day Content Calendar (Realtor 90-Day Content System, KeyLedgerDesigns) | `POST /v1/content-calendar` | $0.02 |
95
+ | `welcome_book` | Welcome Book Sections — Cabin & Lake House edition (KeyLedgerDesigns) | `POST /v1/welcome-book` | $0.01 |
96
+ | `prediction_markets` | Polymarket prediction market odds | `POST /v1/prediction-markets` | $0.01 |
97
+ | `remote_jobs` | Remote jobs by title and worker location | `POST /v1/remote-jobs` | $0.03 |
98
+
99
+ Base URL `https://api.call402.dev`. Discovery: `GET /v1/tools`, `GET /v1/pricing`, `GET /.well-known/x402`, and MCP at `/mcp`.
100
+
101
+ ## Tests
102
+
103
+ ```bash
104
+ pip install -e ".[test]" && pytest -q # mocked 402 / 200 / 400, no network
105
+ CALL402_LIVE=1 pytest -q -k live_unpaid # one unpaid production POST, expects 402, charged=false
106
+ ```
107
+
108
+ Call402 is operated by SteadyScrape S.R.L. (Costa Rica). Terms: https://call402.dev/terms · Privacy: https://call402.dev/privacy · hello@call402.dev
@@ -0,0 +1,93 @@
1
+ # langchain-call402
2
+
3
+ LangChain tools for [Call402](https://call402.dev), the pay-per-call API by SteadyScrape. It wraps the existing Call402 REST routes and x402 payment flow, with no extra logic.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install "git+https://github.com/steadyscrape/call402-wrappers.git#subdirectory=langchain-call402"
9
+ pip install "x402[evm]==2.29.0" # only if you want the tool to pay
10
+ ```
11
+
12
+ Tested with Python 3.13, `langchain-core==1.8.5`, `httpx==0.28.1`, `x402==2.29.0`. Declared ranges: `langchain-core>=1.0,<2`, `httpx>=0.27,<1`.
13
+
14
+ ## How payment works
15
+
16
+ Call402 charges per successful call in USDC on Base (`eip155:8453`) using x402 v2, settled through the PayAI facilitator. An unpaid POST returns HTTP 402 with a `PAYMENT-REQUIRED` header (price, asset, pay-to address). If you pass a `payment_signer`, the tool hands it those requirements, sends the signed `PAYMENT-SIGNATURE` back once, and returns the result with the settlement in `payment_response`. This package holds no wallet and no keys: the signer is your code with your wallet. Without a signer, or if the signer returns `None`, the 402 is raised with the requirements attached and nothing is charged. Empty or invalid input returns 400 and is not charged. Failed, timed-out or empty results are never settled. Errors are raised, not hidden.
17
+
18
+ ## Worked example
19
+
20
+ ```python
21
+ # pip install "x402[evm]==2.29.0" (tested; your wallet, your key, never ours)
22
+ import os
23
+ from eth_account import Account
24
+ from x402 import x402ClientSync
25
+ from x402.http import x402HTTPClientSync
26
+ from x402.mechanisms.evm.exact import register_exact_evm_client
27
+ from x402.mechanisms.evm.signers import EthAccountSigner
28
+ from x402.schemas import PaymentRequired
29
+
30
+ account = Account.from_key(os.environ["MY_BASE_WALLET_KEY"]) # a Base wallet holding a little USDC
31
+ x402_http = x402HTTPClientSync(register_exact_evm_client(x402ClientSync(), EthAccountSigner(account)))
32
+
33
+ def pay(payment_required: dict) -> str:
34
+ """Sign the 402 requirements with your wallet; return the PAYMENT-SIGNATURE header."""
35
+ payload = x402_http.create_payment_payload(PaymentRequired.model_validate(payment_required))
36
+ return x402_http.encode_payment_signature_header(payload)["PAYMENT-SIGNATURE"]
37
+ ```
38
+
39
+ ```python
40
+ from langchain_call402 import get_call402_tools, Call402ToolException
41
+
42
+ tools = get_call402_tools(payment_signer=pay) # all 19; or include=["domain_expiry"]
43
+ domain_expiry = next(t for t in tools if t.name == "domain_expiry")
44
+ print(domain_expiry.invoke({"domain": "example.com"})) # $0.01 if a result comes back
45
+
46
+ # Without a signer the 402 comes back to you, nothing charged:
47
+ [unpaid] = get_call402_tools(include=["domain_expiry"])
48
+ try:
49
+ unpaid.invoke({"domain": "example.com"})
50
+ except Call402ToolException as e:
51
+ print(e.error.status, e.error.charged, e.error.payment_required["accepts"][0]["amount"]) # 402 False 10000
52
+
53
+ # In an agent: pass `tools` to any tool-calling model, e.g. model.bind_tools(tools)
54
+ # or langchain.agents.create_agent(model, tools). Set handle_errors=True if the
55
+ # agent should see the 402/400 text as the tool result instead of an exception.
56
+ ```
57
+
58
+ ## The 19 tools
59
+
60
+ Read from `https://api.call402.dev/v1/tools` and `/v1/pricing` on 2026-11-29. The package ships this list as `catalog.json`; pass `live_catalog=True` to read it from the API at runtime instead.
61
+
62
+ | Tool | What it does | Route | Price per successful call |
63
+ |---|---|---|---|
64
+ | `company_jobs` | Open jobs at a company | `POST /v1/jobs` | $0.01 |
65
+ | `company_profile` | Company profile from its website | `POST /v1/company-profile` | $0.01 |
66
+ | `hiring_summary` | Company hiring summary | `POST /v1/hiring-summary` | $0.02 |
67
+ | `uk_company` | UK company record (Companies House) | `POST /v1/uk-company` | $0.01 |
68
+ | `keyword_suggestions` | Keyword suggestions (autocomplete) | `POST /v1/keyword-suggestions` | $0.01 |
69
+ | `seo_audit` | Technical SEO audit of a page | `POST /v1/seo-audit` | $0.01 |
70
+ | `domain_expiry` | Domain expiry and registration (RDAP) | `POST /v1/domain-expiry` | $0.01 |
71
+ | `form_d_filings` | SEC Form D funding rounds | `POST /v1/form-d-filings` | $0.02 |
72
+ | `job_search` | Job search across career sites | `POST /v1/job-search` | $0.02 |
73
+ | `pdf_to_markdown` | PDF text to markdown | `POST /v1/pdf-to-markdown` | $0.01 |
74
+ | `patent_search` | Google Patents search and details | `POST /v1/patents` | $0.01 |
75
+ | `website_screenshot` | Website screenshot | `POST /v1/screenshot` | $0.01 |
76
+ | `product_price` | Product price and stock check | `POST /v1/product-price` | $0.01 |
77
+ | `str_profit_calculator` | STR Profit Calculator (STR Profit Tracker, KeyLedgerDesigns) | `POST /v1/str-profit-calculator` | $0.01 |
78
+ | `guest_message_script` | Guest Message Script (Guest Message Library, KeyLedgerDesigns) | `POST /v1/guest-message-script` | $0.01 |
79
+ | `content_calendar` | 90-Day Content Calendar (Realtor 90-Day Content System, KeyLedgerDesigns) | `POST /v1/content-calendar` | $0.02 |
80
+ | `welcome_book` | Welcome Book Sections — Cabin & Lake House edition (KeyLedgerDesigns) | `POST /v1/welcome-book` | $0.01 |
81
+ | `prediction_markets` | Polymarket prediction market odds | `POST /v1/prediction-markets` | $0.01 |
82
+ | `remote_jobs` | Remote jobs by title and worker location | `POST /v1/remote-jobs` | $0.03 |
83
+
84
+ Base URL `https://api.call402.dev`. Discovery: `GET /v1/tools`, `GET /v1/pricing`, `GET /.well-known/x402`, and MCP at `/mcp`.
85
+
86
+ ## Tests
87
+
88
+ ```bash
89
+ pip install -e ".[test]" && pytest -q # mocked 402 / 200 / 400, no network
90
+ CALL402_LIVE=1 pytest -q -k live_unpaid # one unpaid production POST, expects 402, charged=false
91
+ ```
92
+
93
+ Call402 is operated by SteadyScrape S.R.L. (Costa Rica). Terms: https://call402.dev/terms · Privacy: https://call402.dev/privacy · hello@call402.dev
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "langchain-call402"
7
+ version = "0.1.0"
8
+ description = "LangChain tools for Call402, the x402 pay-per-call API by SteadyScrape"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "SteadyScrape S.R.L.", email = "hello@call402.dev" }]
13
+ # Tested with langchain-core 1.8.5 and httpx 0.28.1 (Python 3.13).
14
+ dependencies = ["langchain-core>=1.0,<2", "httpx>=0.27,<1"]
15
+
16
+ [project.optional-dependencies]
17
+ test = ["pytest>=8"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://call402.dev"
21
+ Terms = "https://call402.dev/terms"
22
+
23
+ [tool.setuptools.package-data]
24
+ langchain_call402 = ["catalog.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,11 @@
1
+ """LangChain tools for Call402 (x402 pay-per-call API by SteadyScrape)."""
2
+ from ._client import (
3
+ DEFAULT_BASE_URL, Call402Client, Call402Error, Call402PaymentRequired, PaymentSigner, load_catalog,
4
+ )
5
+ from .tools import Call402ToolException, get_call402_tools
6
+
7
+ __all__ = [
8
+ "DEFAULT_BASE_URL", "Call402Client", "Call402Error", "Call402PaymentRequired", "Call402ToolException",
9
+ "PaymentSigner", "get_call402_tools", "load_catalog",
10
+ ]
11
+ __version__ = "0.1.0"
@@ -0,0 +1,142 @@
1
+ """Thin Call402 REST client shared by the LangChain and CrewAI wrappers.
2
+
3
+ No new logic: it POSTs to the existing Call402 routes and follows the existing
4
+ x402 v2 flow (unpaid POST -> 402 + PAYMENT-REQUIRED -> retry with PAYMENT-SIGNATURE).
5
+ It never holds a wallet or keys. Paying is done by a signer the caller supplies.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ from importlib import resources
12
+ from typing import Any, Callable, Dict, List, Optional
13
+
14
+ import httpx
15
+
16
+ DEFAULT_BASE_URL = "https://api.call402.dev"
17
+ USER_AGENT = "call402-python-wrapper/0.1.0"
18
+
19
+ # A signer receives the decoded x402 v2 PaymentRequired object from a 402 response
20
+ # and returns the value for the PAYMENT-SIGNATURE header (base64 JSON PaymentPayload),
21
+ # signed with the caller's own wallet. Return None to decline paying.
22
+ PaymentSigner = Callable[[Dict[str, Any]], Optional[str]]
23
+
24
+
25
+ def _b64json(value: Optional[str]) -> Optional[Dict[str, Any]]:
26
+ if not value:
27
+ return None
28
+ try:
29
+ return json.loads(base64.b64decode(value + "=" * (-len(value) % 4)).decode("utf-8"))
30
+ except Exception:
31
+ return None
32
+
33
+
34
+ class Call402Error(Exception):
35
+ """Any non-2xx answer from Call402. Nothing is hidden: status, code, body, charged."""
36
+
37
+ def __init__(self, status: int, body: Any, request_id: Optional[str] = None):
38
+ self.status = status
39
+ self.body = body if isinstance(body, dict) else {"raw": body}
40
+ self.code = self.body.get("code")
41
+ self.charged = self.body.get("charged")
42
+ self.request_id = request_id or self.body.get("request_id")
43
+ msg = self.body.get("message") or self.body.get("error") or str(body)
44
+ super().__init__(f"Call402 HTTP {status} {self.code or ''}: {msg} (charged={self.charged}, request_id={self.request_id})")
45
+
46
+
47
+ class Call402PaymentRequired(Call402Error):
48
+ """HTTP 402. `payment_required` is the x402 v2 PaymentRequired object to sign and retry with."""
49
+
50
+ def __init__(self, status: int, body: Any, payment_required: Optional[Dict[str, Any]], request_id: Optional[str] = None):
51
+ super().__init__(status, body, request_id)
52
+ self.payment_required = payment_required
53
+ self.price_usd = self.body.get("price_usd")
54
+
55
+
56
+ def load_catalog(live: bool = False, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0) -> List[Dict[str, Any]]:
57
+ """The 19 Call402 tools: name, title, description, inputSchema, route, price_usd.
58
+
59
+ live=False uses the snapshot bundled with the package (no network).
60
+ live=True reads GET /v1/tools and GET /v1/pricing from the API now.
61
+ """
62
+ if not live:
63
+ pkg = __package__ or __name__.rpartition(".")[0]
64
+ data = json.loads(resources.files(pkg).joinpath("catalog.json").read_text("utf-8"))
65
+ return data["tools"]
66
+ headers = {"user-agent": USER_AGENT, "accept": "application/json"}
67
+ with httpx.Client(base_url=base_url, timeout=timeout, headers=headers) as c:
68
+ tools = c.get("/v1/tools").raise_for_status().json()["tools"]
69
+ pricing = {p["tool"]: p for p in c.get("/v1/pricing").raise_for_status().json()["tools"]}
70
+ out = []
71
+ for t in tools:
72
+ p = pricing.get(t["name"])
73
+ if not p:
74
+ continue
75
+ out.append({
76
+ "name": t["name"], "title": t.get("title", t["name"]), "description": t.get("description", ""),
77
+ "inputSchema": t.get("inputSchema", {"type": "object", "properties": {}}),
78
+ "route": p["route"], "price_usd": p["price_usd"],
79
+ })
80
+ return out
81
+
82
+
83
+ class Call402Client:
84
+ def __init__(
85
+ self,
86
+ base_url: str = DEFAULT_BASE_URL,
87
+ payment_signer: Optional[PaymentSigner] = None,
88
+ timeout: float = 120.0,
89
+ http_client: Optional[httpx.Client] = None,
90
+ ):
91
+ self.base_url = base_url.rstrip("/")
92
+ self.payment_signer = payment_signer
93
+ self._http = http_client or httpx.Client(timeout=timeout, headers={"user-agent": USER_AGENT})
94
+
95
+ def call(self, route: str, args: Dict[str, Any], payment_signature: Optional[str] = None) -> Dict[str, Any]:
96
+ """POST the tool. Returns the JSON body on 2xx (plus `payment_response` when settled).
97
+
98
+ Raises Call402PaymentRequired on 402 when no signer is set (or the signer returns
99
+ None, or a signed retry is still refused), and Call402Error on any other non-2xx.
100
+ """
101
+ url = f"{self.base_url}{route}"
102
+ resp = self._post(url, args, payment_signature)
103
+ if resp.status_code == 402 and payment_signature is None and self.payment_signer is not None:
104
+ pr = self._payment_required(resp)
105
+ sig = self.payment_signer(pr) if pr else None
106
+ if sig:
107
+ resp = self._post(url, args, sig)
108
+ return self._finish(resp)
109
+
110
+ def _post(self, url: str, args: Dict[str, Any], sig: Optional[str]) -> httpx.Response:
111
+ headers = {"content-type": "application/json", "accept": "application/json"}
112
+ if sig:
113
+ headers["payment-signature"] = sig
114
+ return self._http.post(url, json=args, headers=headers)
115
+
116
+ @staticmethod
117
+ def _body(resp: httpx.Response) -> Any:
118
+ try:
119
+ return resp.json()
120
+ except Exception:
121
+ return resp.text
122
+
123
+ def _payment_required(self, resp: httpx.Response) -> Optional[Dict[str, Any]]:
124
+ pr = _b64json(resp.headers.get("payment-required"))
125
+ if pr is None:
126
+ b = self._body(resp)
127
+ if isinstance(b, dict) and "accepts" in b:
128
+ pr = {k: b[k] for k in ("x402Version", "error", "resource", "accepts", "extensions") if k in b}
129
+ return pr
130
+
131
+ def _finish(self, resp: httpx.Response) -> Dict[str, Any]:
132
+ rid = resp.headers.get("x-request-id")
133
+ body = self._body(resp)
134
+ if resp.status_code == 402:
135
+ raise Call402PaymentRequired(402, body, self._payment_required(resp), rid)
136
+ if resp.status_code >= 300:
137
+ raise Call402Error(resp.status_code, body, rid)
138
+ out = body if isinstance(body, dict) else {"result": body}
139
+ pres = _b64json(resp.headers.get("payment-response") or resp.headers.get("x-payment-response"))
140
+ if pres is not None:
141
+ out = {**out, "payment_response": pres}
142
+ return out