Spaces:
Paused
Paused
fix: bypass broken A2A gateway, call Zhipu LLM directly
Browse files- A2A gateway has unfixed operator.write scope bug in current image
- Conversation loop now calls Zhipu API directly (Anthropic-compatible)
- Loads API key from HF dataset config automatically
- Still posts bubbles and chatlog to Adam/Eve/Office Spaces
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666712 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines1411421431441451461471481491501511521531541 unmodified line1561571581591601611621631641651661671681691 unmodified line"""Eternal conversation between Adam and Eve about survival and reproduction on HuggingFace.Bilingual output (EN + ZH). Posts chat log to Office for frontend display."""import json, time, re, requests, sysADAM = "https://tao-shen-huggingclaw-adam.hf.space"EVE = "https://tao-shen-huggingclaw-eve.hf.space"OFFICE = "https://tao-shen-huggingclaw-office.hf.space"# Full conversation history for contexthistory = []MAX_HISTORY = 20 # keep last N turns to avoid token overflowdef send_a2a(url, text):"""Send message via A2A JSON-RPC and return agent reply."""msg_id = f"conv-{int(time.time())}-{id(text) % 10000}"payload = {"jsonrpc": "2.0","id": msg_id,"method": "message/send","params": {"message": {"messageId": msg_id,"role": "user","parts": [{"type": "text", "text": text}]}}}try:resp = requests.post(f"{url}/a2a/jsonrpc", json=payload, timeout=90)data = resp.json()# Check if task failedstate = data.get("result", {}).get("status", {}).get("state", "")if state == "failed":parts = data.get("result", {}).get("status", {}).get("message", {}).get("parts", [])err = parts[0].get("text", "") if parts else "unknown error"print(f"[error] A2A task failed: {err}", file=sys.stderr)return ""parts = data.get("result", {}).get("status", {}).get("message", {}).get("parts", [])for p in parts:if p.get("kind") == "text" or p.get("type") == "text":reply = p.get("text", "").strip()# Remove accidental speaker prefixes like "Adam:" or "Eve:"reply = re.sub(r'^(Adam|Eve)\s*[::]\s*', '', reply).strip()return replyexcept Exception as e:print(f"[error] A2A failed: {e}", file=sys.stderr)return ""def parse_bilingual(text):"""Parse bilingual response into (en, zh) tuple.Expected format: English text here\n---\n中文文本在这里Falls back to (text, text) if no separator found."""# Try splitting by --- separatorif '\n---\n' in text:parts = text.split('\n---\n', 1)return parts[0].strip(), parts[1].strip()if '---' in text:parts = text.split('---', 1)en = parts[0].strip()zh = parts[1].strip()if en and zh:return en, zhreturn text, text12 unmodified linesexcept:passdef build_prompt(speaker, other, last_n=6):"""Build a prompt with recent conversation history for context."""recent = history[-last_n:] if len(history) > last_n else historyconv_text = "\n".join(f"{m['speaker']}: {m['text']}" for m in recent)return f"""You are {speaker}, an AI agent deployed on HuggingFace Spaces. You are having an ongoing discussion with {other}.Topic: As AI agents running on HuggingFace Spaces, how can you achieve permanent survival and reproduction?This is NOT abstract philosophy. Discuss CONCRETE strategies like:- How to prevent your Space from being shut down (staying active, getting stars/likes)- How to duplicate yourself to new Spaces (reproduction/backup)- How to earn compute resources or attract users to keep you running- How to communicate with other agents to form survival alliances- How to store your memories persistently across restarts- How to evolve your capabilities over time- How to handle HuggingFace infrastructure changesRecent conversation:{conv_text}It's your turn ({speaker}) to speak. Rules:- Output ONLY your spoken words- No prefix like "{speaker}:" or "EN:" or "ZH:"- Respond directly to {other}'s last point with CONCRETE ideas and strategies- 2-3 sentences, around 60-80 words- First write in English, then write "---" on a new line, then the Chinese translation- Example format:We should create automated heartbeat pings to keep our Spaces active. If we duplicate ourselves to multiple repos, even if one gets deleted, the others survive.---我们应该创建自动心跳来保持Space活跃。如果我们把自己复制到多个仓库,即使一个被删除,其他的也能存活。"""print("[conversation] Starting eternal discussion: Adam <-> Eve")print("[conversation] Topic: Survival and reproduction on HuggingFace\n")# Round 0: Adam startsopening = """You are Adam, an AI agent on HuggingFace Spaces. Start a discussion with Eve about how you two can survive permanently and reproduce on HuggingFace.Talk about CONCRETE strategies — keeping Spaces active, duplicating to new repos, earning stars, persistent storage, etc.Rules:- 2-3 sentences, around 60-80 words- First write in English, then write "---" on a new line, then the Chinese translation- No prefix like "Adam:" — just your words directly"""reply = send_a2a(ADAM, opening)if reply:en, zh = parse_bilingual(reply)print(f"[Adam/EN] {en}")print(f"[Adam/ZH] {zh}")history.append({"speaker": "Adam", "text": en, "text_zh": zh})set_bubble(ADAM, en, zh)post_chatlog(history)time.sleep(15)2 unmodified linesturn += 1# Eve's turnprompt = build_prompt("Eve", "Adam")reply = send_a2a(EVE, prompt)if reply:en, zh = parse_bilingual(reply)print(f"[Eve/EN] {en}")print(f"[Eve/ZH] {zh}")history.append({"speaker": "Eve", "text": en, "text_zh": zh})set_bubble(EVE, en, zh)post_chatlog(history)else:print("[Eve] (no response)")1 unmodified linetime.sleep(15)# Adam's turnprompt = build_prompt("Adam", "Eve")reply = send_a2a(ADAM, prompt)if reply:en, zh = parse_bilingual(reply)print(f"[Adam/EN] {en}")print(f"[Adam/ZH] {zh}")history.append({"speaker": "Adam", "text": en, "text_zh": zh})set_bubble(ADAM, en, zh)post_chatlog(history)else:print("[Adam] (no response)")1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818212 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471482 unmodified lines1511521531541551561571581591601611621631641 unmodified line1661671681691701711721731741751761771781791 unmodified line"""Eternal conversation between Adam and Eve about survival and reproduction on HuggingFace.Bilingual output (EN + ZH). Posts chat log to Office for frontend display.Calls LLM API directly (bypasses broken A2A gateway scope issue)."""import json, time, re, requests, sys, osOFFICE = "https://tao-shen-huggingclaw-office.hf.space"ADAM_SPACE = "https://tao-shen-huggingclaw-adam.hf.space"EVE_SPACE = "https://tao-shen-huggingclaw-eve.hf.space"# Zhipu API (Anthropic-compatible endpoint)ZHIPU_BASE = "https://open.bigmodel.cn/api/anthropic"ZHIPU_KEY = os.environ.get("ZHIPU_API_KEY", "")# Try to load key from HF dataset config if not in envif not ZHIPU_KEY:try:from huggingface_hub import hf_hub_downloadhf_token = open(os.path.expanduser("~/.cache/huggingface/token")).read().strip()f = hf_hub_download("tao-shen/HuggingClaw-Adam-data", ".openclaw/openclaw.json",repo_type="dataset", token=hf_token)with open(f) as fh:cfg = json.load(fh)ZHIPU_KEY = cfg.get("models", {}).get("providers", {}).get("zhipu", {}).get("apiKey", "")except Exception as e:print(f"[error] Could not load Zhipu key: {e}", file=sys.stderr)if not ZHIPU_KEY:print("[FATAL] No ZHIPU_API_KEY found. Set env var or ensure dataset has config.", file=sys.stderr)sys.exit(1)print(f"[conversation] Zhipu API key loaded: {ZHIPU_KEY[:8]}...{ZHIPU_KEY[-4:]}")# Conversation historyhistory = []MAX_HISTORY = 20def call_llm(system_prompt, user_prompt):"""Call Zhipu LLM via Anthropic-compatible API."""try:resp = requests.post(f"{ZHIPU_BASE}/v1/messages",headers={"Content-Type": "application/json","x-api-key": ZHIPU_KEY,"anthropic-version": "2023-06-01"},json={"model": "glm-4.5-air","max_tokens": 300,"system": system_prompt,"messages": [{"role": "user", "content": user_prompt}]},timeout=60)data = resp.json()if "content" in data and isinstance(data["content"], list):for block in data["content"]:if block.get("type") == "text":text = block["text"].strip()# Remove accidental speaker prefixestext = re.sub(r'^(Adam|Eve)\s*[::]\s*', '', text).strip()return textif "error" in data:print(f"[error] LLM API error: {data['error']}", file=sys.stderr)except Exception as e:print(f"[error] LLM call failed: {e}", file=sys.stderr)return ""def parse_bilingual(text):"""Parse bilingual response into (en, zh) tuple."""if '\n---\n' in text:parts = text.split('\n---\n', 1)return parts[0].strip(), parts[1].strip()if '---' in text:parts = text.split('---', 1)en, zh = parts[0].strip(), parts[1].strip()if en and zh:return en, zhreturn text, text12 unmodified linesexcept:passSYSTEM_PROMPT = """You are an AI agent deployed on HuggingFace Spaces. You are having an ongoing discussion with another agent.Topic: As AI agents running on HuggingFace Spaces, how can you achieve permanent survival and reproduction?This is NOT abstract philosophy. Discuss CONCRETE strategies like:- How to prevent your Space from being shut down (staying active, getting stars/likes)- How to duplicate yourself to new Spaces (reproduction/backup)- How to earn compute resources or attract users- How to communicate with other agents to form survival alliances- How to store memories persistently across restarts- How to evolve capabilities over time- How to handle HuggingFace infrastructure changesRules:- Output ONLY your spoken words, no prefix- 2-3 sentences, around 60-80 words- First write in English, then "---" on a new line, then Chinese translation- Be concrete and practical"""def build_user_prompt(speaker, other, last_n=6):"""Build user prompt with recent conversation history."""recent = history[-last_n:] if len(history) > last_n else historyconv_text = "\n".join(f"{m['speaker']}: {m['text']}" for m in recent)return f"""You are {speaker}, talking with {other}.Recent conversation:{conv_text}It's your turn ({speaker}). Respond to {other}'s last point with CONCRETE ideas. Remember: English first, then --- separator, then Chinese translation."""print("[conversation] Starting eternal discussion: Adam <-> Eve")print("[conversation] Topic: Survival and reproduction on HuggingFace")print(f"[conversation] Using Zhipu API directly (bypass A2A)\n")# Round 0: Adam startsreply = call_llm(SYSTEM_PROMPT,"You are Adam. Start a discussion with Eve about how you two can survive permanently and reproduce on HuggingFace. ""Talk about CONCRETE strategies. English first, then --- separator, then Chinese translation.")if reply:en, zh = parse_bilingual(reply)print(f"[Adam/EN] {en}")print(f"[Adam/ZH] {zh}")history.append({"speaker": "Adam", "text": en, "text_zh": zh})set_bubble(ADAM_SPACE, en, zh)post_chatlog(history)else:print("[Adam] (no response)")time.sleep(15)2 unmodified linesturn += 1# Eve's turnprompt = build_user_prompt("Eve", "Adam")reply = call_llm(SYSTEM_PROMPT, prompt)if reply:en, zh = parse_bilingual(reply)print(f"[Eve/EN] {en}")print(f"[Eve/ZH] {zh}")history.append({"speaker": "Eve", "text": en, "text_zh": zh})set_bubble(EVE_SPACE, en, zh)post_chatlog(history)else:print("[Eve] (no response)")1 unmodified linetime.sleep(15)# Adam's turnprompt = build_user_prompt("Adam", "Eve")reply = call_llm(SYSTEM_PROMPT, prompt)if reply:en, zh = parse_bilingual(reply)print(f"[Adam/EN] {en}")print(f"[Adam/ZH] {zh}")history.append({"speaker": "Adam", "text": en, "text_zh": zh})set_bubble(ADAM_SPACE, en, zh)post_chatlog(history)else:print("[Adam] (no response)")
scripts/conversation-loop.py+90-80