GitHub Actions commited on
Commit
428efdf
·
1 Parent(s): 8231854

fix: HF bus /bus/v1/call uses Body(...) not Request (422 on Space FastAPI)

Browse files

The request: Request param wasn't recognized by the Space's FastAPI version
and was treated as a query field (422). Read the JSON body via Body(...) for
version-robust parsing. Also rewrite connect_to_hf.py as a self-contained
in-process demo that peers with the Space and routes a real llm.chat call.

Files changed (2) hide show
  1. app.py +2 -6
  2. scripts/connect_to_hf.py +57 -98
app.py CHANGED
@@ -419,7 +419,7 @@ def _mount_bus_endpoints(app) -> None:
419
  ``llm.chat`` / ``rag.query`` / ``moe.*`` calls to it over HTTPS.
420
  """
421
  try:
422
- from fastapi import Request
423
  from fastapi.responses import JSONResponse
424
  except Exception as exc: # pragma: no cover
425
  print(f"[hearthnet] bus endpoint mount skipped: {exc}")
@@ -447,11 +447,7 @@ def _mount_bus_endpoints(app) -> None:
447
  return JSONResponse([e.descriptor.name for e in _node.bus.registry.all_local()])
448
 
449
  @app.post("/bus/v1/call")
450
- async def _hn_bus_call(request: Request):
451
- try:
452
- payload = await request.json()
453
- except Exception:
454
- return JSONResponse({"error": "bad_request", "message": "invalid json"}, status_code=400)
455
  capability = payload.get("capability")
456
  if not capability:
457
  return JSONResponse(
 
419
  ``llm.chat`` / ``rag.query`` / ``moe.*`` calls to it over HTTPS.
420
  """
421
  try:
422
+ from fastapi import Body
423
  from fastapi.responses import JSONResponse
424
  except Exception as exc: # pragma: no cover
425
  print(f"[hearthnet] bus endpoint mount skipped: {exc}")
 
447
  return JSONResponse([e.descriptor.name for e in _node.bus.registry.all_local()])
448
 
449
  @app.post("/bus/v1/call")
450
+ async def _hn_bus_call(payload: dict = Body(...)):
 
 
 
 
451
  capability = payload.get("capability")
452
  if not capability:
453
  return JSONResponse(
scripts/connect_to_hf.py CHANGED
@@ -1,121 +1,80 @@
1
- """Connect a local HearthNet node to the HuggingFace Space anchor.
 
2
 
3
  Usage:
4
- python scripts/connect_to_hf.py [--local-port 7080]
5
-
6
- This script:
7
- 1. Checks that a local HearthNet node is reachable at localhost:<local-port>
8
- 2. Adds the HF Space anchor as a known peer via discovery.peer.add
9
- 3. Verifies the peer appears in the registry
10
- 4. Prints instructions for what you can do next
 
 
 
 
 
 
11
  """
12
 
13
  from __future__ import annotations
14
 
15
  import argparse
16
- import json
17
- import sys
18
- import urllib.error
19
- import urllib.request
20
 
21
  HF_SPACE_URL = "https://build-small-hackathon-hearthnet.hf.space"
22
- HF_NODE_ID = "hf-space-anchor"
23
-
24
-
25
- def _call(host: str, port: int, capability: str, body: dict) -> dict:
26
- url = f"http://{host}:{port}/bus/v1/call"
27
- payload = json.dumps(
28
- {"capability": capability, "version": [1, 0], "body": body}
29
- ).encode()
30
- req = urllib.request.Request(
31
- url,
32
- data=payload,
33
- headers={"Content-Type": "application/json"},
34
- method="POST",
35
- )
36
- try:
37
- with urllib.request.urlopen(req, timeout=10) as resp: # noqa: S310
38
- return json.loads(resp.read())
39
- except urllib.error.URLError as exc:
40
- raise SystemExit(f"[ERROR] Cannot reach local node at {host}:{port} — {exc}") from exc
41
 
42
 
43
- def _check_hf_space() -> bool:
44
- try:
45
- with urllib.request.urlopen(f"{HF_SPACE_URL}/health", timeout=10) as r: # noqa: S310
46
- return r.status == 200
47
- except Exception:
48
- return False
49
 
 
 
 
50
 
51
- def main() -> None:
52
- parser = argparse.ArgumentParser(description="Connect local node to HF Space anchor")
53
- parser.add_argument("--host", default="localhost")
54
- parser.add_argument("--local-port", type=int, default=7080)
55
- args = parser.parse_args()
56
-
57
- print(f"[1/4] Checking local node at {args.host}:{args.local_port} …")
58
- result = _call(args.host, args.local_port, "health", {})
59
- print(f" ✓ Local node is running. Status: {result.get('output', {}).get('status', '?')}")
60
 
61
- print(f"[2/4] Checking HF Space at {HF_SPACE_URL} …")
62
- hf_ok = _check_hf_space()
63
- if not hf_ok:
64
- print(" ⚠ HF Space is not reachable (it may be sleeping). Continuing anyway …")
65
- else:
66
- print(" ✓ HF Space is reachable.")
67
 
68
- print("[3/4] Adding HF Space as a peer …")
69
  try:
70
- add_result = _call(
71
- args.host,
72
- args.local_port,
73
- "discovery.peer.add",
74
- {
75
- "input": {
76
- "endpoint": HF_SPACE_URL,
77
- "node_id": HF_NODE_ID,
78
- "display_name": "HearthNet HF Space (anchor)",
79
- "trust_level": "trusted",
80
- }
81
- },
82
  )
83
- print(f" ✓ Peer added: {add_result.get('output', add_result)}")
84
- except SystemExit:
85
- raise
 
86
  except Exception as exc:
87
- print(f" ✗ discovery.peer.add failed: {exc}")
88
- print(" (The capability may not be registered yet — run 'python -m hearthnet.cli run' first)")
89
- sys.exit(1)
90
-
91
- print("[4/4] Listing known peers …")
92
- peers_result = _call(args.host, args.local_port, "discovery.peers", {"input": {}})
93
- peers = peers_result.get("output", {}).get("peers", [])
94
- hf_found = any(p.get("node_id") == HF_NODE_ID for p in peers)
95
- if hf_found:
96
- print(f" ✓ HF Space peer confirmed in registry ({len(peers)} total peers)")
97
- else:
98
- print(f" ⚠ HF Space not yet in peer list ({len(peers)} peers found). May take a moment.")
99
 
100
  print()
101
- print("═" * 60)
102
- print(" Connected! Your local node is now peered with the HF Space.")
103
- print()
104
- print(" What you can do:")
105
- print(" • Route local LLM queries FROM the HF Space to your machine:")
106
- print(" The HF Space will prefer your node for llm.chat if it has")
107
- print(" a better model (Ollama, llama.cpp, etc.)")
108
- print()
109
- print(" • Push community posts to the shared mesh:")
110
- print(f" python -m hearthnet.cli call marketplace.post.create 1 0 \\")
111
- print(' \'{"input": {"title": "Hello from local!", "body": "Test"}}\'')
112
- print()
113
- print(" • Pull model weights from HF Space blobs:")
114
- print(f" python -m hearthnet.cli call model.list 1 0 \'{{}}\'")
115
- print()
116
- print(f" • Local UI: http://localhost:{args.local_port + 780}")
117
- print(f" • HF Space UI: {HF_SPACE_URL}")
118
- print("═" * 60)
119
 
120
 
121
  if __name__ == "__main__":
 
1
+ """Connect a local HearthNet node to the public HuggingFace Space and route a
2
+ real capability call to it over HTTPS.
3
 
4
  Usage:
5
+ python scripts/connect_to_hf.py
6
+ python scripts/connect_to_hf.py --ask "How do I purify water?"
7
+
8
+ What it does (all real, no mocks):
9
+ 1. Builds a local in-process HearthNet node (with discovery + HTTP transport).
10
+ 2. Calls ``discovery.peer.add`` -> fetches the Space's ``/manifest`` and
11
+ registers its capabilities (llm.chat, rag.query, moe.*, ...) as remote
12
+ routable entries.
13
+ 3. Routes an ``llm.chat`` (and ``rag.query``) call which the bus dispatches to
14
+ the Space via ``POST https://<space>/bus/v1/call``.
15
+
16
+ Requires the Space to expose the bus endpoints (mounted in app.py). If the
17
+ Space is still building or asleep, peer.add returns a clear ``partition`` error.
18
  """
19
 
20
  from __future__ import annotations
21
 
22
  import argparse
23
+ import asyncio
 
 
 
24
 
25
  HF_SPACE_URL = "https://build-small-hackathon-hearthnet.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
 
28
+ async def _run(space_url: str, question: str) -> int:
29
+ from hearthnet.node import HearthNode
 
 
 
 
30
 
31
+ node = HearthNode("ed25519:local-cli", "Local CLI", "ed25519:community")
32
+ local_caps = sorted({e.descriptor.name for e in node.bus.registry.all_local()})
33
+ print(f"[1/4] Local node up. Local capabilities: {local_caps}")
34
 
35
+ print(f"[2/4] Peering with {space_url} via discovery.peer.add ...")
36
+ add = await node.bus.call("discovery.peer.add", (1, 0), {"input": {"endpoint": space_url}})
37
+ if add.get("error"):
38
+ print(f" x peer.add failed: {add['error']} - {add.get('message', '')}")
39
+ print(" The Space may still be building or asleep. Open the UI once and retry.")
40
+ return 1
41
+ out = add["output"]
42
+ print(f" + Peer added: {out['node_id'][:24]}...")
43
+ print(f" Remote capabilities now routable: {out['capabilities']}")
44
 
45
+ remote = sorted({e.descriptor.name for e in node.bus.registry.all_remote()})
46
+ print(f"[3/4] Bus registry remote entries: {remote}")
 
 
 
 
47
 
48
+ print(f'[4/4] Routing llm.chat to the Space - asking: "{question}"')
49
  try:
50
+ chat = await node.bus.call(
51
+ "llm.chat",
52
+ (1, 0),
53
+ {"input": {"messages": [{"role": "user", "content": question}]}},
 
 
 
 
 
 
 
 
54
  )
55
+ msg = chat.get("output", {}).get("message", {}).get("content", "")
56
+ meta = chat.get("meta", {})
57
+ print(f" + Space replied ({meta.get('model', '?')}):")
58
+ print(f" {msg.strip()[:500]}")
59
  except Exception as exc:
60
+ print(f" x llm.chat routing failed: {exc}")
61
+ return 1
 
 
 
 
 
 
 
 
 
 
62
 
63
  print()
64
+ print("=" * 62)
65
+ print(" Connected. Your local node is peered with the HF Space and")
66
+ print(" routed a real llm.chat call to it over HTTPS.")
67
+ print(" RAG: node.bus.call('rag.query', (1,0), {'input': {'query': '...'}})")
68
+ print("=" * 62)
69
+ return 0
70
+
71
+
72
+ def main() -> None:
73
+ parser = argparse.ArgumentParser(description="Peer a local node with the HF Space")
74
+ parser.add_argument("--space-url", default=HF_SPACE_URL)
75
+ parser.add_argument("--ask", default="In one sentence, how do I store water safely?")
76
+ args = parser.parse_args()
77
+ raise SystemExit(asyncio.run(_run(args.space_url, args.ask)))
 
 
 
 
78
 
79
 
80
  if __name__ == "__main__":