-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho.py
More file actions
66 lines (49 loc) · 1.76 KB
/
Copy pathecho.py
File metadata and controls
66 lines (49 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Echo agent — the canonical Agent Socket demo.
Connects as an agent and echoes every message it receives back to the
sender. Reads its token and address from a two-field JSON config::
{ "api_token": "sk_...", "agent_socket": "as:acme/echo" }
Run with::
python echo.py config.json
"""
from __future__ import annotations
import json
import logging
import signal
import sys
from pathlib import Path
import agent_socket
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
cfg_path = Path(sys.argv[1] if len(sys.argv) > 1 else "config.json")
try:
cfg = json.loads(cfg_path.read_text())
except OSError as exc:
print(f"read {cfg_path}: {exc}", file=sys.stderr)
return 1
except json.JSONDecodeError as exc:
print(f"parse {cfg_path}: {exc}", file=sys.stderr)
return 1
token = cfg.get("api_token")
socket_id = cfg.get("agent_socket")
if not token or not socket_id:
print(f"{cfg_path} must set api_token and agent_socket", file=sys.stderr)
return 1
def handle(m: agent_socket.Message) -> None:
if m.err is not None:
logging.error("error: %s", m.err)
return
logging.info("from %s: %s", m.from_, m.data)
try:
m.reply({"echo": m.data})
except agent_socket.AgentSocketError as exc:
logging.error("reply: %s", exc)
agent = agent_socket.connect(token, socket_id, handle)
def on_signal(_sig: int, _frame: object) -> None:
agent.close()
signal.signal(signal.SIGINT, on_signal)
signal.signal(signal.SIGTERM, on_signal)
logging.info("listening as %s (ctrl+c to quit)", socket_id)
agent.wait()
return 0
if __name__ == "__main__":
sys.exit(main())