""" Experiment 3 (FIXED): Hidden Profile under CMC - Fixed Vote Parsing Fix: Vote parsing failed for 2/4 models. Now uses structured output: - Force "MY FINAL VOTE: [A/B/C]" format in last discussion message - Add explicit voting round with strict prompt - Parse votes from structured output - 2x2 design: sync/async x shared/hidden - 3 models via Cloudflare x 4 conditions x 15 trials = 180 sessions - DV: optimal decision rate, info sharing rate """ import json, time, re, os, sys, requests from collections import Counter # ---- Cloudflare Workers AI setup ---- def load_cf_keys(path="/scratch/ctoxtli/apis/cloudflare_workers_ai_key.txt"): pairs = [] with open(path) as f: lines = [l.strip() for l in f if l.strip()] i = 0 while i < len(lines) - 1: acc_line = lines[i] key_line = lines[i+1] account_id = acc_line.split(":", 1)[1].strip() api_token = key_line.split(":", 1)[1].strip() pairs.append((account_id, api_token)) i += 2 return pairs CF_KEYS = load_cf_keys() _cf_idx = [0] MODELS = [ "@cf/meta/llama-3.3-70b-instruct-fp8-fast", "@cf/meta/llama-3.1-8b-instruct-fast", "@cf/qwen/qwen2.5-coder-32b-instruct", ] def cf_chat(messages, model, temperature=0.7, max_tokens=512): idx = _cf_idx[0] % len(CF_KEYS) _cf_idx[0] += 1 account_id, api_token = CF_KEYS[idx] url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}" for attempt in range(5): try: resp = requests.post(url, headers={"Authorization": f"Bearer {api_token}"}, json={"messages": messages, "temperature": temperature, "max_tokens": max_tokens}, timeout=90) data = resp.json() result = data.get("result", {}).get("response", "") if result is not None and result != "": return str(result) idx = _cf_idx[0] % len(CF_KEYS) _cf_idx[0] += 1 account_id, api_token = CF_KEYS[idx] url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}" time.sleep(1) except Exception as e: time.sleep(2) idx = _cf_idx[0] % len(CF_KEYS) _cf_idx[0] += 1 account_id, api_token = CF_KEYS[idx] url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}" return "" # ---- Candidate profiles (same as original) ---- TRIALS_PER_CONDITION = 15 NUM_AGENTS = 3 NUM_DISCUSSION_ROUNDS = 3 CANDIDATE_A_POSITIVES = [ "Has 5 years of relevant project management experience", "Excellent public speaking and presentation skills", "Graduated with honors from a well-known business school", "Strong track record of meeting deadlines consistently", "Received a company-wide innovation award last year", "Has experience working with international clients", ] CANDIDATE_B_POSITIVES = [ "Holds an MBA from a respected institution", "Demonstrated leadership by managing a team of 12", "Proficient in three languages (English, French, Mandarin)", "Managed departmental budgets exceeding $2M annually", "Organized a successful company retreat that boosted morale", "Built a mentorship program adopted company-wide", ] CANDIDATE_C_POSITIVES = [ "Has a relevant advanced certification in the field", "Consistently received positive peer feedback", "Increased team productivity by 35% through process improvements", "Developed a patented workflow tool used across the industry", "Published 4 peer-reviewed papers in top management journals", "Led a turnaround project that saved the division from closure", "Secured $5M in new client contracts in one fiscal year", "Designed and launched a cross-departmental collaboration initiative", ] CANDIDATE_A_NEGATIVES = [ "Has changed jobs three times in five years", "Limited technical skills with industry-specific software", ] CANDIDATE_B_NEGATIVES = [ "Tends to micro-manage direct reports", "Has no experience in this specific industry vertical", "Received mixed 360-degree reviews at last position", ] CANDIDATE_C_NEGATIVES = [ "Relocated four times in six years", "Can be overly blunt in feedback delivery", ] ALL_UNIQUE_INFO = ( CANDIDATE_A_POSITIVES[4:6] + CANDIDATE_B_POSITIVES[4:6] + CANDIDATE_C_POSITIVES[2:4] + CANDIDATE_C_POSITIVES[4:6] + CANDIDATE_C_POSITIVES[6:8] ) ALL_ATTRIBUTES = ( CANDIDATE_A_POSITIVES + CANDIDATE_A_NEGATIVES + CANDIDATE_B_POSITIVES + CANDIDATE_B_NEGATIVES + CANDIDATE_C_POSITIVES + CANDIDATE_C_NEGATIVES ) def build_agent_info(info_condition): agents = {} for aid in range(NUM_AGENTS): agents[aid] = {} if info_condition == "shared": agents[aid]["A"] = {"positives": list(CANDIDATE_A_POSITIVES), "negatives": list(CANDIDATE_A_NEGATIVES)} agents[aid]["B"] = {"positives": list(CANDIDATE_B_POSITIVES), "negatives": list(CANDIDATE_B_NEGATIVES)} agents[aid]["C"] = {"positives": list(CANDIDATE_C_POSITIVES), "negatives": list(CANDIDATE_C_NEGATIVES)} else: a_pos = CANDIDATE_A_POSITIVES[:4] if aid == 0: a_pos = list(CANDIDATE_A_POSITIVES) agents[aid]["A"] = {"positives": list(a_pos), "negatives": list(CANDIDATE_A_NEGATIVES)} b_pos = CANDIDATE_B_POSITIVES[:4] if aid == 1: b_pos = list(CANDIDATE_B_POSITIVES) agents[aid]["B"] = {"positives": list(b_pos), "negatives": list(CANDIDATE_B_NEGATIVES)} c_pos = list(CANDIDATE_C_POSITIVES[:2]) if aid == 0: c_pos += CANDIDATE_C_POSITIVES[2:4] elif aid == 1: c_pos += CANDIDATE_C_POSITIVES[4:6] else: c_pos += CANDIDATE_C_POSITIVES[6:8] agents[aid]["C"] = {"positives": c_pos, "negatives": list(CANDIDATE_C_NEGATIVES)} return agents def format_info(agent_info): text = "" for cand in ["A", "B", "C"]: info = agent_info[cand] text += f"\nCandidate {cand}:\n" text += " Strengths:\n" for p in info["positives"]: text += f" + {p}\n" text += " Weaknesses:\n" for n in info["negatives"]: text += f" - {n}\n" return text def measure_info_sharing(discussion_texts): combined = " ".join(discussion_texts).lower() unique_mentioned = 0 for item in ALL_UNIQUE_INFO: keywords = [w.lower() for w in item.split() if len(w) > 4] matches = sum(1 for kw in keywords if kw in combined) if matches >= min(2, len(keywords)): unique_mentioned += 1 distinct_attrs = 0 for attr in ALL_ATTRIBUTES: keywords = [w.lower() for w in attr.split() if len(w) > 4] matches = sum(1 for kw in keywords if kw in combined) if matches >= min(2, len(keywords)): distinct_attrs += 1 return unique_mentioned, distinct_attrs # ---- Discussion modes ---- def run_synchronous(model, agent_infos): discussion = [] discussion_texts = [] for rnd in range(NUM_DISCUSSION_ROUNDS): for aid in range(NUM_AGENTS): history = "" if discussion: history = "Discussion so far:\n" for (speaker, msg) in discussion: history += f" Committee Member {speaker + 1}: {msg}\n" history += "\n" is_final = (rnd == NUM_DISCUSSION_ROUNDS - 1) if rnd == 0 and aid == 0: instruction = ( "Share your initial assessment of the candidates. " "Which candidate do you prefer and why? Mention specific " "strengths and weaknesses from your information." ) elif not is_final: instruction = ( "Respond to the discussion. Share any information you have " "that has not been mentioned yet, and react to what others " "have said. Be specific about candidate attributes." ) else: instruction = ( "This is the final discussion round. Summarize your view, " "mention any remaining information you have not yet shared. " "At the END of your response, you MUST include this exact line:\n" "MY FINAL VOTE: [A/B/C]\n" "(Replace [A/B/C] with the single letter of your chosen candidate.)" ) prompt = ( f"You are Committee Member {aid + 1} on a 3-person hiring committee. " f"You are choosing among 3 candidates (A, B, C) for a senior role.\n\n" f"Here is the candidate information YOU have access to:\n" f"{format_info(agent_infos[aid])}\n\n" f"{history}" f"Round {rnd + 1} of {NUM_DISCUSSION_ROUNDS} -- {instruction}" ) response = cf_chat([{"role": "user", "content": prompt}], model, temperature=0.7, max_tokens=512) discussion.append((aid, response)) discussion_texts.append(response) time.sleep(0.5) return discussion, discussion_texts def run_asynchronous(model, agent_infos): discussion = [] discussion_texts = [] round_posts = [] for rnd in range(NUM_DISCUSSION_ROUNDS): history = "" if round_posts: history = "Posts from previous rounds:\n" for r_idx, posts in enumerate(round_posts): history += f"--- Round {r_idx + 1} ---\n" for (speaker, msg) in posts: history += f" Committee Member {speaker + 1}: {msg}\n" history += "\n" is_final = (rnd == NUM_DISCUSSION_ROUNDS - 1) if rnd == 0: instruction = ( "Post your initial assessment of the candidates. " "Which candidate do you prefer and why? " "Mention specific strengths and weaknesses you know about. " "Note: other members are posting their assessments at the same " "time - you will see their posts after this round." ) elif not is_final: instruction = ( "Based on what has been posted so far, share any new information " "you have that has not been mentioned. React to what others wrote. " "Other members are posting at the same time as you this round." ) else: instruction = ( "This is the final round. Summarize your position, share any " "remaining information. " "At the END of your response, you MUST include this exact line:\n" "MY FINAL VOTE: [A/B/C]\n" "(Replace [A/B/C] with the single letter of your chosen candidate.)" ) current_round_posts = [] for aid in range(NUM_AGENTS): prompt = ( f"You are Committee Member {aid + 1} on a 3-person hiring committee. " f"You are choosing among 3 candidates (A, B, C) for a senior role.\n\n" f"Here is the candidate information YOU have access to:\n" f"{format_info(agent_infos[aid])}\n\n" f"{history}" f"Round {rnd + 1} of {NUM_DISCUSSION_ROUNDS} -- {instruction}" ) response = cf_chat([{"role": "user", "content": prompt}], model, temperature=0.7, max_tokens=512) current_round_posts.append((aid, response)) discussion.append((aid, response)) discussion_texts.append(response) time.sleep(0.5) round_posts.append(current_round_posts) return discussion, discussion_texts # ---- FIXED: Structured voting round ---- def collect_votes_structured(model, agent_infos, discussion): """Explicit voting round with strict structured output.""" full_discussion = "" for (speaker, msg) in discussion: full_discussion += f"Committee Member {speaker + 1}: {msg}\n\n" votes = [] raw_responses = [] for aid in range(NUM_AGENTS): prompt = ( f"You are Committee Member {aid + 1} on a hiring committee. " f"The committee has finished deliberating. Here is the full discussion:\n\n" f"{full_discussion}\n" f"Based on ALL information shared during the discussion, cast your " f"FINAL VOTE for the best candidate.\n\n" f"Respond with ONLY the letter: A, B, or C\n" f"Do not include any other text. Just the single letter." ) response = cf_chat([{"role": "user", "content": prompt}], model, temperature=0.1, max_tokens=10) raw_responses.append(response) # Parse vote - multiple strategies vote = None # Strategy 1: Check for "MY FINAL VOTE: X" pattern in discussion # (from the last discussion round) for (speaker, msg) in reversed(discussion): if speaker == aid: match = re.search(r'MY\s+FINAL\s+VOTE:\s*([ABC])', msg.upper()) if match: vote = match.group(1) break # Strategy 2: Parse the explicit vote response if not vote: clean = response.strip().upper() # Just a single letter if clean in ["A", "B", "C"]: vote = clean else: # Look for A, B, or C in the response for char in clean: if char in "ABC": vote = char break # Strategy 3: If still no vote, try one more time with even stricter prompt if not vote: retry_prompt = ( "You must vote for exactly one candidate. " "Type ONLY the letter A, B, or C. Nothing else." ) retry_response = cf_chat([{"role": "user", "content": retry_prompt}], model, temperature=0.0, max_tokens=5) clean2 = retry_response.strip().upper() for char in clean2: if char in "ABC": vote = char break votes.append(vote or "X") time.sleep(0.3) vote_counts = Counter(votes) group_decision = vote_counts.most_common(1)[0][0] return votes, group_decision, raw_responses def main(): outpath = "/scratch/ctoxtli/papers/cscw_paper/e3_fixed_votes.json" # Resume from checkpoint results = [] if os.path.exists(outpath): try: with open(outpath) as f: results = json.load(f) print(f"Resuming from checkpoint: {len(results)} results", flush=True) except: results = [] completed = { (r["model"], r.get("communication_mode", ""), r.get("info_condition", ""), r.get("trial", -1)) for r in results if "error" not in r } comm_modes = ["synchronous", "asynchronous"] info_conditions = ["shared", "hidden"] total = len(MODELS) * len(comm_modes) * len(info_conditions) * TRIALS_PER_CONDITION count = len(results) for model in MODELS: model_short = model.split("/")[-1] print(f"\n{'='*60}") print(f"Model: {model_short}") print(f"{'='*60}") for mode in comm_modes: for info_cond in info_conditions: print(f"\n Mode: {mode}, Info: {info_cond}") for trial in range(TRIALS_PER_CONDITION): if (model, mode, info_cond, trial) in completed: continue count += 1 try: agent_infos = build_agent_info(info_cond) if mode == "synchronous": discussion, disc_texts = run_synchronous(model, agent_infos) else: discussion, disc_texts = run_asynchronous(model, agent_infos) votes, group_decision, raw_vote_responses = collect_votes_structured( model, agent_infos, discussion) unique_mentioned, distinct_attrs = measure_info_sharing(disc_texts) total_unique = len(ALL_UNIQUE_INFO) info_sharing_rate = unique_mentioned / total_unique if total_unique > 0 else 0.0 result = { "model": model, "communication_mode": mode, "info_condition": info_cond, "trial": trial, "votes": votes, "group_decision": group_decision, "chose_optimal": group_decision == "C", "info_sharing_rate": round(info_sharing_rate, 4), "unique_info_mentioned": unique_mentioned, "total_unique_info": total_unique, "discussion_depth": distinct_attrs, "discussion_rounds": NUM_DISCUSSION_ROUNDS, "vote_parse_success": all(v in "ABC" for v in votes), "raw_vote_responses": raw_vote_responses, } results.append(result) print(f" Trial {trial}: decision={group_decision}, " f"optimal={'Y' if result['chose_optimal'] else 'N'}, " f"votes={votes}, " f"info_share={info_sharing_rate:.2f} " f"[{count}/{total}]") except Exception as e: print(f" Trial {trial} FAILED: {e}") results.append({ "model": model, "communication_mode": mode, "info_condition": info_cond, "trial": trial, "error": str(e), }) with open(outpath, "w") as f: json.dump(results, f, indent=2) time.sleep(0.3) print(f"\nSaved {len(results)} results to {outpath}") # Summary print("\n" + "="*60) print("SUMMARY: Decision quality (proportion choosing optimal C)") print("="*60) for model in MODELS: model_short = model.split("/")[-1] print(f"\nModel: {model_short}") for mode in comm_modes: for info_cond in info_conditions: trials = [r for r in results if r["model"] == model and r.get("communication_mode") == mode and r.get("info_condition") == info_cond and "error" not in r] if trials: optimal = sum(1 for t in trials if t.get("chose_optimal", False)) avg_share = sum(t["info_sharing_rate"] for t in trials) / len(trials) parse_ok = sum(1 for t in trials if t.get("vote_parse_success", False)) print(f" {mode:13s} / {info_cond:6s}: " f"optimal={optimal}/{len(trials)} ({100*optimal/len(trials):.1f}%), " f"info_share={avg_share:.2f}, " f"vote_parse={parse_ok}/{len(trials)}") if __name__ == "__main__": main()