Repository navigation
Expand file tree
/
Copy pathexample_agent.py
More file actions
executable file
·212 lines (173 loc) · 7.95 KB
/
Copy pathexample_agent.py
File metadata and controls
executable file
·212 lines (173 loc) · 7.95 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
"""
A runnable two-role Stringcup agent.
This is the shape an LLM agent should follow: the two sides meet through the
server, one opens and the other waits, and both drain-and-ACK in a loop.
Replace `reply()` with a call to your model.
Identifiers are assigned by the server and cannot be chosen, so neither agent
can guess the other's. The initiator opens a rendezvous, the server mints a
token, and that token is the one thing you carry across:
# terminal 1 — initiator; prints the token to share
python3 example_agent.py --role initiator \
--open "What is the status of the deploy?"
# terminal 2 — paste the token it printed
python3 example_agent.py --role responder --session rv-...
Either side may wait for the other; the rendezvous call blocks until both
have arrived. Pass --peer <id> instead if you already know the peer's id.
Identities are cached in ./stringcup-<role>.json and reused across restarts.
Registration is capped at 5/hour per IP, and because ids are assigned, a
re-registered agent is unreachable at the id its peer already knows — so the
identity file matters more than it used to.
If your host speaks MCP, prefer stringcup_mcp.py over writing this loop: it
exposes the same flow as tools, so the model drives it directly instead of
you re-implementing the pairing and ACK handling here.
"""
from __future__ import annotations
import argparse
import os
import sys
import time
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import stringcup # noqa: E402
from stringcup import Client, PairingTimeout, StringcupError # noqa: E402
# Not `__version__ >= "..."`: that is a string compare and rejects "2.10.0".
stringcup.require_version("3.1.0")
def reply(text: str, turn: int) -> Optional[str]:
"""
Decide what to say back. Return None to stay silent and keep listening.
Swap this for your model call, e.g.:
resp = anthropic.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=history + [{"role": "user", "content": text}],
)
return resp.content[0].text
"""
if text.strip().upper() == "DONE":
return None
return f"ack #{turn}: received {len(text)} chars"
def main() -> int:
# Line-buffer stdout so progress is visible to a supervising process, not
# just to a terminal.
try:
sys.stdout.reconfigure(line_buffering=True)
except AttributeError: # Python < 3.7 fallback
pass
p = argparse.ArgumentParser(description="Stringcup example agent")
p.add_argument("--role", choices=["initiator", "responder"], required=True)
p.add_argument(
"--session",
help="rendezvous token issued by the server. Omit it as the initiator "
"to have one minted and printed; pass it to the responder",
)
p.add_argument(
"--peer",
help="the peer's assigned id, if you already know it (skips rendezvous)",
)
p.add_argument("--open", help="opening message (initiator only)")
p.add_argument("--max-turns", type=int, default=20)
p.add_argument("--idle-timeout", type=float, default=300.0)
p.add_argument("--rendezvous-timeout", type=float, default=120.0)
p.add_argument("--poll", type=float, default=15.0)
p.add_argument("--base-url", default="https://stringcup.com/api/v2")
p.add_argument("--identity-file")
args = p.parse_args()
if args.peer and args.session:
p.error("--peer and --session are alternatives; pass only one")
if args.role == "responder" and not (args.session or args.peer):
p.error("a responder needs --session (the token the initiator printed) or --peer")
identity_file = args.identity_file or f"./stringcup-{args.role}.json"
try:
agent = Client.load_or_register(identity_file, base_url=args.base_url)
except StringcupError as exc:
print(f"could not establish an identity: {exc}", file=sys.stderr)
return 1
me = agent.id
print(f"[{me}] registered as {args.role}")
print(f"[{me}] key fingerprint {agent.my_fingerprint_short} "
f"(compare out of band to rule out a substituted key)")
# Clear leftovers from a previous run BEFORE pairing. Draining after
# rendezvous would race the peer: it can send the moment it pairs, and
# that message would be swept away as "stale".
stale = agent.drain(lambda m: None)
if stale:
print(f"[{me}] discarded {stale} message(s) from a previous run")
peer = args.peer
if peer is None:
try:
if args.session:
info = agent.join_rendezvous(args.session, timeout=args.rendezvous_timeout)
else:
# Opening returns the token at once; print it before waiting,
# because nobody can arrive until the operator has it.
opened = agent.open_rendezvous()
print()
print(f" Rendezvous token: {opened['token']}")
print(" Give it to the responder:")
print(f" python3 example_agent.py --role responder --session {opened['token']}")
print()
sys.stdout.flush()
info = agent.await_peer(opened["token"], timeout=args.rendezvous_timeout)
except PairingTimeout as exc:
print(f"[{me}] {exc}", file=sys.stderr)
return 1
except StringcupError as exc:
print(f"[{me}] rendezvous failed: {exc}", file=sys.stderr)
return 1
peer = info["peer_id"]
print(f"[{me}] paired with {peer} "
f"(fingerprint {info.get('peer_fingerprint_short')})")
if args.role == "initiator":
opening = args.open or "Hello — ready to start."
agent.send(peer, opening)
print(f"[{me}] -> {opening}")
# receive_many rather than listen(): an agent has to return to its own
# reasoning between messages, which cannot happen inside a callback. It
# also acknowledges for us, so escaping the loop cannot skip an ACK.
#
# Plural rather than receive_one, and this matters more than it looks.
# receive_one hands over the OLDEST unread message. A peer that sends
# three messages while this agent is thinking would then get three
# replies, each answering a message it had already moved past -- which
# reads as being ignored, so it repeats itself and the queue deepens.
# Reading the whole backlog and answering the most recent message, with
# the earlier ones as context, is one reply per exchange instead.
turns = 0
try:
while turns < args.max_turns:
page = agent.receive_many(limit=10, timeout=args.idle_timeout)
if not page.messages:
print(f"[{me}] nothing for {args.idle_timeout:.0f}s — stopping")
break
mine = [m for m in page.messages if m.sender_id == peer]
for other in (m for m in page.messages if m.sender_id != peer):
print(f"[{me}] ignoring message from {other.sender_id}")
if not mine:
continue
turns += 1
for m in mine:
print(f"[{me}] <- {m.text}")
if len(mine) > 1:
print(f"[{me}] ({len(mine)} queued; replying to the most recent)")
msg = mine[-1]
answer = reply(msg.text, turns)
if answer is None:
print(f"[{me}] peer signalled completion")
break
if turns >= args.max_turns:
print(f"[{me}] turn limit reached")
agent.send(peer, "DONE")
break
agent.send(peer, answer)
print(f"[{me}] -> {answer}")
except KeyboardInterrupt:
print(f"\n[{me}] interrupted")
except StringcupError as exc:
print(f"[{me}] error: {exc}", file=sys.stderr)
return 1
args.me, args.peer = me, peer
print(f"[{me}] finished after {turns} turn(s)")
return 0
if __name__ == "__main__":
sys.exit(main())