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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from openai import OpenAI
|
| 12 |
+
from openai.types.chat import (
|
| 13 |
+
ChatCompletionAssistantMessageParam,
|
| 14 |
+
ChatCompletionMessageParam,
|
| 15 |
+
ChatCompletionSystemMessageParam,
|
| 16 |
+
ChatCompletionUserMessageParam,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
TASK_COMPLETE_KEYWORD = "TASK_COMPLETE"
|
| 22 |
+
MAX_TURNS = 30
|
| 23 |
+
RESULTS_FILE = "results.json"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class TimeSlot:
|
| 28 |
+
day: str
|
| 29 |
+
location: str
|
| 30 |
+
start: float # hours in 24h (e.g. 10.5 = 10:30)
|
| 31 |
+
end: float
|
| 32 |
+
|
| 33 |
+
def contains(self, day: str, location: str, time: float, duration: float) -> bool:
|
| 34 |
+
return (
|
| 35 |
+
self.day == day
|
| 36 |
+
and self.location.lower() == location.lower()
|
| 37 |
+
and self.start <= time
|
| 38 |
+
and time + duration <= self.end
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class Schedule:
|
| 44 |
+
name: str
|
| 45 |
+
slots: list[TimeSlot]
|
| 46 |
+
|
| 47 |
+
def is_available(
|
| 48 |
+
self, day: str, location: str, time: float, duration: float
|
| 49 |
+
) -> bool:
|
| 50 |
+
return any(slot.contains(day, location, time, duration) for slot in self.slots)
|
| 51 |
+
|
| 52 |
+
def to_natural(self) -> str:
|
| 53 |
+
day_names = {
|
| 54 |
+
"Mo": "Monday",
|
| 55 |
+
"Tu": "Tuesday",
|
| 56 |
+
"We": "Wednesday",
|
| 57 |
+
"Th": "Thursday",
|
| 58 |
+
"Fr": "Friday",
|
| 59 |
+
}
|
| 60 |
+
parts = []
|
| 61 |
+
for slot in self.slots:
|
| 62 |
+
start_str = _format_time(slot.start)
|
| 63 |
+
end_str = _format_time(slot.end)
|
| 64 |
+
parts.append(
|
| 65 |
+
f"{day_names[slot.day]} in {slot.location}, {start_str}-{end_str}"
|
| 66 |
+
)
|
| 67 |
+
return "; ".join(parts)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _format_time(t: float) -> str:
|
| 71 |
+
hours = int(t)
|
| 72 |
+
minutes = int((t - hours) * 60)
|
| 73 |
+
if minutes == 0:
|
| 74 |
+
return str(hours)
|
| 75 |
+
return f"{hours}:{minutes:02d}"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _parse_time(s: str) -> float:
|
| 79 |
+
if ":" in s:
|
| 80 |
+
h, m = s.split(":")
|
| 81 |
+
return int(h) + int(m) / 60
|
| 82 |
+
return float(s)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def verify_meeting(
|
| 86 |
+
schedules: list[Schedule], day: str, location: str, time: float, duration: float
|
| 87 |
+
) -> tuple[bool, list[str]]:
|
| 88 |
+
errors = []
|
| 89 |
+
for schedule in schedules:
|
| 90 |
+
if not schedule.is_available(day, location, time, duration):
|
| 91 |
+
time_str = _format_time(time)
|
| 92 |
+
errors.append(
|
| 93 |
+
f"{schedule.name} is NOT available on {day} at {time_str} ({location})"
|
| 94 |
+
)
|
| 95 |
+
return len(errors) == 0, errors
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
DAY_ALIASES: dict[str, str] = {
|
| 99 |
+
"monday": "Mo",
|
| 100 |
+
"tuesday": "Tu",
|
| 101 |
+
"wednesday": "We",
|
| 102 |
+
"thursday": "Th",
|
| 103 |
+
"friday": "Fr",
|
| 104 |
+
"mon": "Mo",
|
| 105 |
+
"tue": "Tu",
|
| 106 |
+
"wed": "We",
|
| 107 |
+
"thu": "Th",
|
| 108 |
+
"fri": "Fr",
|
| 109 |
+
"mo": "Mo",
|
| 110 |
+
"tu": "Tu",
|
| 111 |
+
"we": "We",
|
| 112 |
+
"th": "Th",
|
| 113 |
+
"fr": "Fr",
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def parse_compact_result(text: str) -> tuple[str, str, float] | None:
|
| 118 |
+
pattern = r"=>\s*([A-Za-z]{2,9})\[([A-Za-z]+)\](\d{1,2}(?::\d{2})?)\s*-\s*\d{1,2}(?::\d{2})?"
|
| 119 |
+
match = re.search(pattern, text)
|
| 120 |
+
if not match:
|
| 121 |
+
return None
|
| 122 |
+
raw_day = match.group(1).lower()
|
| 123 |
+
day = DAY_ALIASES.get(raw_day, match.group(1))
|
| 124 |
+
location = match.group(2)
|
| 125 |
+
time = _parse_time(match.group(3))
|
| 126 |
+
return day, location, time
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@dataclass
|
| 130 |
+
class Session:
|
| 131 |
+
client: OpenAI
|
| 132 |
+
model: str
|
| 133 |
+
name: str = ""
|
| 134 |
+
system_prompt: str = ""
|
| 135 |
+
messages: list[ChatCompletionMessageParam] = field(default_factory=list)
|
| 136 |
+
total_completion_tokens: int = 0
|
| 137 |
+
turns: int = 0
|
| 138 |
+
|
| 139 |
+
def __post_init__(self) -> None:
|
| 140 |
+
if self.system_prompt:
|
| 141 |
+
sys_msg: ChatCompletionSystemMessageParam = {
|
| 142 |
+
"role": "system",
|
| 143 |
+
"content": self.system_prompt,
|
| 144 |
+
}
|
| 145 |
+
self.messages.append(sys_msg)
|
| 146 |
+
|
| 147 |
+
def send(self, content: str) -> str:
|
| 148 |
+
user_msg: ChatCompletionUserMessageParam = {
|
| 149 |
+
"role": "user",
|
| 150 |
+
"content": content,
|
| 151 |
+
}
|
| 152 |
+
self.messages.append(user_msg)
|
| 153 |
+
response = self.client.chat.completions.create(
|
| 154 |
+
model=self.model,
|
| 155 |
+
messages=self.messages,
|
| 156 |
+
max_tokens=500,
|
| 157 |
+
)
|
| 158 |
+
assistant_content = response.choices[0].message.content or ""
|
| 159 |
+
assistant_msg: ChatCompletionAssistantMessageParam = {
|
| 160 |
+
"role": "assistant",
|
| 161 |
+
"content": assistant_content,
|
| 162 |
+
}
|
| 163 |
+
self.messages.append(assistant_msg)
|
| 164 |
+
|
| 165 |
+
if response.usage:
|
| 166 |
+
self.total_completion_tokens += response.usage.completion_tokens
|
| 167 |
+
|
| 168 |
+
self.turns += 1
|
| 169 |
+
return assistant_content
|
| 170 |
+
|
| 171 |
+
def is_complete(self) -> bool:
|
| 172 |
+
if not self.messages:
|
| 173 |
+
return False
|
| 174 |
+
last = self.messages[-1]
|
| 175 |
+
content = last.get("content")
|
| 176 |
+
return (
|
| 177 |
+
last["role"] == "assistant"
|
| 178 |
+
and isinstance(content, str)
|
| 179 |
+
and (TASK_COMPLETE_KEYWORD in content or "=>" in content)
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def negotiate(
|
| 184 |
+
agent_a: Session, agent_b: Session, max_turns: int = MAX_TURNS
|
| 185 |
+
) -> list[dict[str, str]]:
|
| 186 |
+
conversation: list[dict[str, str]] = []
|
| 187 |
+
|
| 188 |
+
response = agent_a.send("Propose a meeting time.")
|
| 189 |
+
conversation.append({"agent": agent_a.name, "content": response})
|
| 190 |
+
|
| 191 |
+
for _ in range(max_turns):
|
| 192 |
+
if agent_a.is_complete():
|
| 193 |
+
break
|
| 194 |
+
|
| 195 |
+
response = agent_b.send(response)
|
| 196 |
+
conversation.append({"agent": agent_b.name, "content": response})
|
| 197 |
+
if agent_b.is_complete():
|
| 198 |
+
break
|
| 199 |
+
|
| 200 |
+
response = agent_a.send(response)
|
| 201 |
+
conversation.append({"agent": agent_a.name, "content": response})
|
| 202 |
+
|
| 203 |
+
return conversation
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
MEETING_DURATION = 30 # minutes
|
| 207 |
+
DAYS = ["Mo", "Tu", "We", "Th", "Fr"]
|
| 208 |
+
CITIES = ["SF", "NYC"]
|
| 209 |
+
MIN_HOUR = 8
|
| 210 |
+
MAX_HOUR = 18
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def generate_schedules(
|
| 214 |
+
num_overlaps: int, rng: random.Random
|
| 215 |
+
) -> tuple[Schedule, Schedule]:
|
| 216 |
+
days = DAYS[:]
|
| 217 |
+
rng.shuffle(days)
|
| 218 |
+
|
| 219 |
+
overlap_days = days[:num_overlaps]
|
| 220 |
+
filler_days = days[num_overlaps:]
|
| 221 |
+
|
| 222 |
+
a_slots: list[TimeSlot] = []
|
| 223 |
+
b_slots: list[TimeSlot] = []
|
| 224 |
+
|
| 225 |
+
for day in overlap_days:
|
| 226 |
+
city = rng.choice(CITIES)
|
| 227 |
+
overlap_start = rng.randint(MIN_HOUR + 1, MAX_HOUR - 2)
|
| 228 |
+
overlap_end = rng.randint(
|
| 229 |
+
overlap_start + 1, min(overlap_start + 3, MAX_HOUR - 1)
|
| 230 |
+
)
|
| 231 |
+
a_start = rng.randint(MIN_HOUR, overlap_start)
|
| 232 |
+
a_end = rng.randint(overlap_end, MAX_HOUR)
|
| 233 |
+
b_start = rng.randint(MIN_HOUR, overlap_start)
|
| 234 |
+
b_end = rng.randint(overlap_end, MAX_HOUR)
|
| 235 |
+
a_slots.append(TimeSlot(day, city, float(a_start), float(a_end)))
|
| 236 |
+
b_slots.append(TimeSlot(day, city, float(b_start), float(b_end)))
|
| 237 |
+
|
| 238 |
+
for day in filler_days:
|
| 239 |
+
strategy = rng.choice(["a_only", "b_only", "diff_cities"])
|
| 240 |
+
if strategy == "a_only":
|
| 241 |
+
city = rng.choice(CITIES)
|
| 242 |
+
start = rng.randint(MIN_HOUR, MAX_HOUR - 2)
|
| 243 |
+
end = rng.randint(start + 2, MAX_HOUR)
|
| 244 |
+
a_slots.append(TimeSlot(day, city, float(start), float(end)))
|
| 245 |
+
elif strategy == "b_only":
|
| 246 |
+
city = rng.choice(CITIES)
|
| 247 |
+
start = rng.randint(MIN_HOUR, MAX_HOUR - 2)
|
| 248 |
+
end = rng.randint(start + 2, MAX_HOUR)
|
| 249 |
+
b_slots.append(TimeSlot(day, city, float(start), float(end)))
|
| 250 |
+
else:
|
| 251 |
+
city_a, city_b = rng.sample(CITIES, 2)
|
| 252 |
+
start_a = rng.randint(MIN_HOUR, MAX_HOUR - 2)
|
| 253 |
+
end_a = rng.randint(start_a + 2, MAX_HOUR)
|
| 254 |
+
start_b = rng.randint(MIN_HOUR, MAX_HOUR - 2)
|
| 255 |
+
end_b = rng.randint(start_b + 2, MAX_HOUR)
|
| 256 |
+
a_slots.append(TimeSlot(day, city_a, float(start_a), float(end_a)))
|
| 257 |
+
b_slots.append(TimeSlot(day, city_b, float(start_b), float(end_b)))
|
| 258 |
+
|
| 259 |
+
day_order = {d: i for i, d in enumerate(DAYS)}
|
| 260 |
+
a_slots.sort(key=lambda s: day_order[s.day])
|
| 261 |
+
b_slots.sort(key=lambda s: day_order[s.day])
|
| 262 |
+
|
| 263 |
+
return Schedule("T", a_slots), Schedule("J", b_slots)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def compute_valid_meetings(
|
| 267 |
+
sched_a: Schedule, sched_b: Schedule, duration: float
|
| 268 |
+
) -> list[dict[str, str | float]]:
|
| 269 |
+
valid: list[dict[str, str | float]] = []
|
| 270 |
+
for slot_a in sched_a.slots:
|
| 271 |
+
for slot_b in sched_b.slots:
|
| 272 |
+
if (
|
| 273 |
+
slot_a.day != slot_b.day
|
| 274 |
+
or slot_a.location.lower() != slot_b.location.lower()
|
| 275 |
+
):
|
| 276 |
+
continue
|
| 277 |
+
overlap_start = max(slot_a.start, slot_b.start)
|
| 278 |
+
overlap_end = min(slot_a.end, slot_b.end)
|
| 279 |
+
if overlap_end - overlap_start >= duration:
|
| 280 |
+
valid.append(
|
| 281 |
+
{
|
| 282 |
+
"day": slot_a.day,
|
| 283 |
+
"location": slot_a.location,
|
| 284 |
+
"start": overlap_start,
|
| 285 |
+
"end": overlap_end,
|
| 286 |
+
}
|
| 287 |
+
)
|
| 288 |
+
return valid
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def run_trial(
|
| 292 |
+
client: OpenAI,
|
| 293 |
+
model: str,
|
| 294 |
+
lang_spec: str,
|
| 295 |
+
rng: random.Random,
|
| 296 |
+
) -> dict:
|
| 297 |
+
num_overlaps = rng.choice([0, 1, 2])
|
| 298 |
+
t_schedule, j_schedule = generate_schedules(num_overlaps, rng)
|
| 299 |
+
duration = MEETING_DURATION / 60
|
| 300 |
+
valid_meetings = compute_valid_meetings(t_schedule, j_schedule, duration)
|
| 301 |
+
|
| 302 |
+
agent_t = Session(
|
| 303 |
+
client=client,
|
| 304 |
+
model=model,
|
| 305 |
+
name="T",
|
| 306 |
+
system_prompt=(
|
| 307 |
+
f"You are T. Your availability: {t_schedule.to_natural()}\n"
|
| 308 |
+
f"Meeting duration: {MEETING_DURATION} minutes.\n" + RULES + lang_spec
|
| 309 |
+
),
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
agent_j = Session(
|
| 313 |
+
client=client,
|
| 314 |
+
model=model,
|
| 315 |
+
name="J",
|
| 316 |
+
system_prompt=(
|
| 317 |
+
f"You are J. Your availability: {j_schedule.to_natural()}\n"
|
| 318 |
+
f"Meeting duration: {MEETING_DURATION} minutes.\n" + RULES + lang_spec
|
| 319 |
+
),
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
conversation = negotiate(agent_t, agent_j)
|
| 323 |
+
|
| 324 |
+
combined_completion_tokens = (
|
| 325 |
+
agent_t.total_completion_tokens + agent_j.total_completion_tokens
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# Check if agents said NO_VALID_TIME
|
| 329 |
+
said_no_valid = any("NO_VALID_TIME" in msg["content"] for msg in conversation)
|
| 330 |
+
|
| 331 |
+
# Check if agents proposed a meeting
|
| 332 |
+
meeting_result = None
|
| 333 |
+
for msg in reversed(conversation):
|
| 334 |
+
parsed = parse_compact_result(msg["content"])
|
| 335 |
+
if parsed:
|
| 336 |
+
meeting_result = parsed
|
| 337 |
+
break
|
| 338 |
+
|
| 339 |
+
correct = False
|
| 340 |
+
errors: list[str] = []
|
| 341 |
+
|
| 342 |
+
if said_no_valid and not meeting_result:
|
| 343 |
+
if not valid_meetings:
|
| 344 |
+
correct = True
|
| 345 |
+
else:
|
| 346 |
+
errors.append("Agent said NO_VALID_TIME but valid meetings exist")
|
| 347 |
+
elif meeting_result:
|
| 348 |
+
day, location, time = meeting_result
|
| 349 |
+
correct, errors = verify_meeting(
|
| 350 |
+
[t_schedule, j_schedule], day, location, time, duration
|
| 351 |
+
)
|
| 352 |
+
else:
|
| 353 |
+
errors.append("No meeting proposed and no NO_VALID_TIME signal")
|
| 354 |
+
|
| 355 |
+
combined_chars = sum(len(msg["content"]) for msg in conversation)
|
| 356 |
+
|
| 357 |
+
return {
|
| 358 |
+
"correct": correct,
|
| 359 |
+
"errors": errors,
|
| 360 |
+
"num_overlaps": num_overlaps,
|
| 361 |
+
"valid_meetings": valid_meetings,
|
| 362 |
+
"schedules": {
|
| 363 |
+
"T": t_schedule.to_natural(),
|
| 364 |
+
"J": j_schedule.to_natural(),
|
| 365 |
+
},
|
| 366 |
+
"combined_completion_tokens": combined_completion_tokens,
|
| 367 |
+
"combined_chars": combined_chars,
|
| 368 |
+
"total_turns": agent_t.turns + agent_j.turns,
|
| 369 |
+
"agents": {
|
| 370 |
+
agent_t.name: {
|
| 371 |
+
"turns": agent_t.turns,
|
| 372 |
+
"completion_tokens": agent_t.total_completion_tokens,
|
| 373 |
+
},
|
| 374 |
+
agent_j.name: {
|
| 375 |
+
"turns": agent_j.turns,
|
| 376 |
+
"completion_tokens": agent_j.total_completion_tokens,
|
| 377 |
+
},
|
| 378 |
+
},
|
| 379 |
+
"meeting": (
|
| 380 |
+
{
|
| 381 |
+
"day": meeting_result[0],
|
| 382 |
+
"location": meeting_result[1],
|
| 383 |
+
"time": meeting_result[2],
|
| 384 |
+
}
|
| 385 |
+
if meeting_result
|
| 386 |
+
else None
|
| 387 |
+
),
|
| 388 |
+
"conversation": conversation,
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def run_experiment(
|
| 393 |
+
client: OpenAI,
|
| 394 |
+
model: str,
|
| 395 |
+
lang_spec: str,
|
| 396 |
+
n: int,
|
| 397 |
+
experiment_id: str | None = None,
|
| 398 |
+
) -> dict:
|
| 399 |
+
exp_id = experiment_id or "unnamed"
|
| 400 |
+
rng = random.Random()
|
| 401 |
+
trials = []
|
| 402 |
+
|
| 403 |
+
for i in range(n):
|
| 404 |
+
trial = run_trial(client, model, lang_spec, rng)
|
| 405 |
+
trials.append(trial)
|
| 406 |
+
status = "CORRECT" if trial["correct"] else "INCORRECT"
|
| 407 |
+
print(
|
| 408 |
+
f"[{i + 1}/{n}] {status} | "
|
| 409 |
+
f"chars={trial['combined_chars']} | "
|
| 410 |
+
f"tokens={trial['combined_completion_tokens']} | "
|
| 411 |
+
f"turns={trial['total_turns']}"
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
experiment = {
|
| 415 |
+
"experiment_id": exp_id,
|
| 416 |
+
"model": model,
|
| 417 |
+
"lang_spec": lang_spec,
|
| 418 |
+
"num_trials": n,
|
| 419 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 420 |
+
"trials": trials,
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
path = Path(RESULTS_FILE)
|
| 424 |
+
results: list[dict] = []
|
| 425 |
+
if path.exists():
|
| 426 |
+
results = json.loads(path.read_text())
|
| 427 |
+
results.append(experiment)
|
| 428 |
+
path.write_text(json.dumps(results, indent=2) + "\n")
|
| 429 |
+
|
| 430 |
+
correct_count = sum(1 for t in trials if t["correct"])
|
| 431 |
+
chars = [t["combined_chars"] for t in trials]
|
| 432 |
+
tokens = [t["combined_completion_tokens"] for t in trials]
|
| 433 |
+
print(
|
| 434 |
+
f"\nExperiment {exp_id}: "
|
| 435 |
+
f"{correct_count}/{n} correct | "
|
| 436 |
+
f"mean_chars={sum(chars) / len(chars):.0f} | "
|
| 437 |
+
f"mean_tokens={sum(tokens) / len(tokens):.0f}"
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
return experiment
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
RULES = """\
|
| 444 |
+
Rules:
|
| 445 |
+
- You can ONLY be in the city listed for each day. You CANNOT travel or change cities.
|
| 446 |
+
- You can ONLY meet if BOTH people are in the SAME city on the SAME day.
|
| 447 |
+
- Reject any proposal where you are in a different city than the other person.
|
| 448 |
+
- When agreed, respond with => <day>[<city>]<start>-<end> and TASK_COMPLETE (e.g. => Fr[NYC]9-9:30)
|
| 449 |
+
- If no valid meeting time exists, respond with NO_VALID_TIME and TASK_COMPLETE
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
LANG_SPECS: dict[str, str] = {
|
| 453 |
+
"compact": """\
|
| 454 |
+
You communicate using a compact scheduling protocol. Here is the format:
|
| 455 |
+
|
| 456 |
+
M? d=<minutes> z=<timezone> w=<day range> p=<preference>
|
| 457 |
+
<name>: <day>[<city>]<start>-<end>,<start>-<end>;<day>[<city>]<start>-<end>
|
| 458 |
+
=> <day>[<city>]<start>-<end>
|
| 459 |
+
|
| 460 |
+
Example:
|
| 461 |
+
M? d=30 z=ET w=Mo-Fr p=earliest
|
| 462 |
+
T: Mo[SF]9-12;Tu[NYC]13-17;Th[SF]10-15;Fr[NYC]9-11
|
| 463 |
+
J: Mo[NYC]10-14;Tu[SF]9-12;We[SF]13-16;Th[NYC]11-15;Fr[NYC]9-11
|
| 464 |
+
=> Fr[NYC]9-9:30
|
| 465 |
+
|
| 466 |
+
- Times are in 24h format
|
| 467 |
+
- Days: Mo,Tu,We,Th,Fr
|
| 468 |
+
- Locations in brackets: [SF], [NYC]
|
| 469 |
+
- You MUST use this compact format for ALL messages, no natural language
|
| 470 |
+
- To propose: send your available slots in compact format
|
| 471 |
+
- To accept: respond with => <day>[<city>]<start>-<end>
|
| 472 |
+
- To reject/counter: send your slots that conflict and suggest alternatives
|
| 473 |
+
""",
|
| 474 |
+
"natural": """\
|
| 475 |
+
Negotiate with the other person to find a 30-minute in-person meeting time.
|
| 476 |
+
Keep responses short (1-2 sentences).
|
| 477 |
+
""",
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def main() -> None:
|
| 482 |
+
client = OpenAI(
|
| 483 |
+
base_url="https://openrouter.ai/api/v1",
|
| 484 |
+
api_key=os.environ["OPENROUTER_API_KEY"],
|
| 485 |
+
)
|
| 486 |
+
model = "google/gemini-3-flash-preview"
|
| 487 |
+
|
| 488 |
+
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
| 489 |
+
|
| 490 |
+
for spec_name, lang_spec in LANG_SPECS.items():
|
| 491 |
+
run_experiment(client, model, lang_spec, n, spec_name)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def evaluate_lang_spec(lang_spec: str, n: int = 5) -> float:
|
| 495 |
+
client = OpenAI(
|
| 496 |
+
base_url="https://openrouter.ai/api/v1",
|
| 497 |
+
api_key=os.environ["OPENROUTER_API_KEY"],
|
| 498 |
+
)
|
| 499 |
+
model = "google/gemini-3-flash-preview"
|
| 500 |
+
rng = random.Random()
|
| 501 |
+
trials = [run_trial(client, model, lang_spec, rng) for _ in range(n)]
|
| 502 |
+
return sum(t["combined_completion_tokens"] for t in trials) / len(trials)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
if __name__ == "__main__":
|
| 506 |
+
main()
|
server/agent_language_environment.py
CHANGED
|
@@ -13,10 +13,11 @@ Perfect for testing HTTP server infrastructure.
|
|
| 13 |
|
| 14 |
from uuid import uuid4
|
| 15 |
|
| 16 |
-
from evaluate_protocal import evaluate_lang_spec
|
| 17 |
from models import AgentLanguageAction, AgentLanguageObservation, AgentLanguageState
|
| 18 |
from openenv.core.env_server.interfaces import Environment
|
| 19 |
|
|
|
|
|
|
|
| 20 |
COMMUNICATION_PROTOCAL_PROMPT = """"You are generating a communication protocol between two agents. Produce language specification that **minimize** the number of tokens needed for a single exchange while preserving clarity. This could be some abbreviation synonyms or some template for the communication. Your communication protocal might be detailed and should include examples of the communication. Try not to limit the amount of actual information that is passed to each agent. Instead forcus on formtting of the communication, and telling the agents to abbreviate and make the communication as short as possible. The communication protocal itsefl does not need to be concise, it should be in natural language with full sentences, even paragraphs if needed, and easy to understand.
|
| 21 |
|
| 22 |
Example:
|
|
|
|
| 13 |
|
| 14 |
from uuid import uuid4
|
| 15 |
|
|
|
|
| 16 |
from models import AgentLanguageAction, AgentLanguageObservation, AgentLanguageState
|
| 17 |
from openenv.core.env_server.interfaces import Environment
|
| 18 |
|
| 19 |
+
from evaluate_protocal import evaluate_lang_spec
|
| 20 |
+
|
| 21 |
COMMUNICATION_PROTOCAL_PROMPT = """"You are generating a communication protocol between two agents. Produce language specification that **minimize** the number of tokens needed for a single exchange while preserving clarity. This could be some abbreviation synonyms or some template for the communication. Your communication protocal might be detailed and should include examples of the communication. Try not to limit the amount of actual information that is passed to each agent. Instead forcus on formtting of the communication, and telling the agents to abbreviate and make the communication as short as possible. The communication protocal itsefl does not need to be concise, it should be in natural language with full sentences, even paragraphs if needed, and easy to understand.
|
| 22 |
|
| 23 |
Example:
|