ShinnosukeU commited on
Commit
734b153
·
verified ·
1 Parent(s): 1495b72

Upload folder using huggingface_hub

Browse files
frontend/index.html ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Agent Language Environment</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+
10
+ body {
11
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
12
+ background: #f5f5f7;
13
+ color: #1a1a1a;
14
+ min-height: 100vh;
15
+ padding: 24px;
16
+ }
17
+
18
+ .layout {
19
+ display: grid;
20
+ grid-template-columns: 1fr 1fr;
21
+ gap: 16px;
22
+ max-width: 1200px;
23
+ margin: 0 auto;
24
+ }
25
+
26
+ .left-col, .right-col {
27
+ display: flex;
28
+ flex-direction: column;
29
+ gap: 16px;
30
+ }
31
+
32
+ .card {
33
+ background: #fff;
34
+ border: 1px solid #e0e0e0;
35
+ border-radius: 8px;
36
+ padding: 20px;
37
+ }
38
+
39
+ .card h2 {
40
+ font-size: 1rem;
41
+ font-weight: 700;
42
+ margin-bottom: 12px;
43
+ }
44
+
45
+ label {
46
+ display: block;
47
+ font-size: 0.875rem;
48
+ margin-bottom: 6px;
49
+ }
50
+
51
+ label .required {
52
+ color: #e53e3e;
53
+ }
54
+
55
+ textarea {
56
+ width: 100%;
57
+ min-height: 90px;
58
+ padding: 10px 12px;
59
+ border: 2px solid #4a90d9;
60
+ border-radius: 6px;
61
+ font-size: 0.875rem;
62
+ font-family: inherit;
63
+ resize: vertical;
64
+ outline: none;
65
+ color: #555;
66
+ }
67
+
68
+ textarea:focus {
69
+ border-color: #2563eb;
70
+ }
71
+
72
+ .field-hint {
73
+ font-size: 0.75rem;
74
+ color: #888;
75
+ margin-top: 4px;
76
+ font-style: italic;
77
+ }
78
+
79
+ .btn {
80
+ display: inline-block;
81
+ padding: 8px 20px;
82
+ border: none;
83
+ border-radius: 6px;
84
+ font-size: 0.875rem;
85
+ font-weight: 500;
86
+ cursor: pointer;
87
+ transition: opacity 0.15s;
88
+ }
89
+
90
+ .btn:hover { opacity: 0.85; }
91
+ .btn:active { opacity: 0.7; }
92
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
93
+
94
+ .btn-primary { background: #4a7fd4; color: #fff; }
95
+ .btn-secondary { background: #5a6472; color: #fff; }
96
+
97
+ .btn-row {
98
+ display: flex;
99
+ gap: 10px;
100
+ }
101
+
102
+ .state-card .state-row {
103
+ font-size: 0.875rem;
104
+ color: #555;
105
+ margin-bottom: 6px;
106
+ }
107
+
108
+ .state-card .state-row strong {
109
+ color: #1a1a1a;
110
+ }
111
+
112
+ .obs-pre {
113
+ background: #f7f8fa;
114
+ border-radius: 4px;
115
+ padding: 12px;
116
+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
117
+ font-size: 0.8rem;
118
+ white-space: pre;
119
+ overflow-x: auto;
120
+ line-height: 1.6;
121
+ }
122
+
123
+ .history-empty {
124
+ font-size: 0.875rem;
125
+ color: #555;
126
+ }
127
+
128
+ .history-list {
129
+ display: flex;
130
+ flex-direction: column;
131
+ gap: 10px;
132
+ max-height: 400px;
133
+ overflow-y: auto;
134
+ }
135
+
136
+ .history-item {
137
+ background: #f7f8fa;
138
+ border-radius: 6px;
139
+ padding: 10px 12px;
140
+ font-size: 0.8rem;
141
+ }
142
+
143
+ .history-item .hi-step {
144
+ font-weight: 600;
145
+ margin-bottom: 4px;
146
+ color: #333;
147
+ }
148
+
149
+ .history-item .hi-action {
150
+ color: #555;
151
+ margin-bottom: 2px;
152
+ }
153
+
154
+ .history-item .hi-reward {
155
+ color: #2563eb;
156
+ font-size: 0.75rem;
157
+ }
158
+
159
+ .error-msg {
160
+ color: #c53030;
161
+ font-size: 0.8rem;
162
+ margin-top: 8px;
163
+ }
164
+ </style>
165
+ </head>
166
+ <body>
167
+ <div class="layout">
168
+ <!-- LEFT COLUMN -->
169
+ <div class="left-col">
170
+ <!-- Take Action Card -->
171
+ <div class="card">
172
+ <h2>Take Action</h2>
173
+ <label>Language Specification <span class="required">*</span>:</label>
174
+ <textarea id="messageInput" placeholder="Enter language specification..."></textarea>
175
+ <div class="field-hint">Language Specification</div>
176
+ <div id="stepError" class="error-msg" style="display:none;"></div>
177
+ <div style="margin-top:12px;">
178
+ <button class="btn btn-primary" id="stepBtn" onclick="doStep()">Step</button>
179
+ </div>
180
+ </div>
181
+
182
+ <!-- Env Controls -->
183
+ <div class="btn-row">
184
+ <button class="btn btn-secondary" id="resetBtn" onclick="doReset()">Reset Environment</button>
185
+ <button class="btn btn-secondary" id="stateBtn" onclick="doGetState()">Get State</button>
186
+ </div>
187
+
188
+ <!-- Current State Card -->
189
+ <div class="card state-card">
190
+ <h2>Current State</h2>
191
+ <div class="state-row">Status: <strong id="stateStatus">—</strong></div>
192
+ <div class="state-row">Episode ID: <strong id="stateEpisodeId">—</strong></div>
193
+ <div class="state-row">Step Count: <strong id="stateStepCount">—</strong></div>
194
+ <div id="stateError" class="error-msg" style="display:none;"></div>
195
+ </div>
196
+ </div>
197
+
198
+ <!-- RIGHT COLUMN -->
199
+ <div class="right-col">
200
+ <!-- Current Observation Card -->
201
+ <div class="card">
202
+ <h2>Current Observation</h2>
203
+ <div class="obs-pre" id="obsDisplay">—</div>
204
+ </div>
205
+
206
+ <!-- Action History Card -->
207
+ <div class="card">
208
+ <h2>Action History</h2>
209
+ <div id="historyContainer">
210
+ <div class="history-empty" id="historyEmpty">No actions taken yet</div>
211
+ <div class="history-list" id="historyList" style="display:none;"></div>
212
+ </div>
213
+ </div>
214
+ </div>
215
+ </div>
216
+
217
+ <script>
218
+ const BASE_URL = 'http://localhost:8000';
219
+
220
+ const actionHistory = [];
221
+
222
+ function setButtons(disabled) {
223
+ ['stepBtn', 'resetBtn', 'stateBtn'].forEach(id => {
224
+ document.getElementById(id).disabled = disabled;
225
+ });
226
+ }
227
+
228
+ function showError(elemId, msg) {
229
+ const el = document.getElementById(elemId);
230
+ el.textContent = msg;
231
+ el.style.display = 'block';
232
+ }
233
+
234
+ function clearError(elemId) {
235
+ const el = document.getElementById(elemId);
236
+ el.textContent = '';
237
+ el.style.display = 'none';
238
+ }
239
+
240
+ function updateStateDisplay(data) {
241
+ document.getElementById('stateStatus').textContent = data.status ?? '—';
242
+ document.getElementById('stateEpisodeId').textContent = data.episode_id ?? '—';
243
+ document.getElementById('stateStepCount').textContent = data.step_count ?? '—';
244
+ }
245
+
246
+ function updateObsDisplay(obs) {
247
+ // Show obs as pretty JSON, excluding internal fields if desired
248
+ const display = {};
249
+ for (const [k, v] of Object.entries(obs)) {
250
+ if (!['done', 'reward', 'metadata'].includes(k)) {
251
+ display[k] = v;
252
+ }
253
+ }
254
+ document.getElementById('obsDisplay').textContent = JSON.stringify(display, null, 2);
255
+ }
256
+
257
+ function addToHistory(stepNum, message, reward) {
258
+ actionHistory.push({ stepNum, message, reward });
259
+ renderHistory();
260
+ }
261
+
262
+ function renderHistory() {
263
+ const empty = document.getElementById('historyEmpty');
264
+ const list = document.getElementById('historyList');
265
+ if (actionHistory.length === 0) {
266
+ empty.style.display = '';
267
+ list.style.display = 'none';
268
+ return;
269
+ }
270
+ empty.style.display = 'none';
271
+ list.style.display = 'flex';
272
+ list.innerHTML = actionHistory.slice().reverse().map(item => `
273
+ <div class="history-item">
274
+ <div class="hi-step">Step ${item.stepNum}</div>
275
+ <div class="hi-action">Spec: "${item.message}"</div>
276
+ <div class="hi-reward">Reward: ${item.reward.toFixed(2)}</div>
277
+ </div>
278
+ `).join('');
279
+ }
280
+
281
+ async function doReset() {
282
+ clearError('stateError');
283
+ setButtons(true);
284
+ try {
285
+ const res = await fetch(`${BASE_URL}/reset`, { method: 'POST' });
286
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
287
+ const data = await res.json();
288
+ // data contains observation + state
289
+ if (data.observation) updateObsDisplay(data.observation);
290
+ if (data.state) updateStateDisplay({ ...data.state, status: 'Reset' });
291
+ // Clear history on reset
292
+ actionHistory.length = 0;
293
+ renderHistory();
294
+ } catch (e) {
295
+ showError('stateError', `Reset failed: ${e.message}`);
296
+ } finally {
297
+ setButtons(false);
298
+ }
299
+ }
300
+
301
+ async function doGetState() {
302
+ clearError('stateError');
303
+ setButtons(true);
304
+ try {
305
+ const res = await fetch(`${BASE_URL}/state`);
306
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
307
+ const data = await res.json();
308
+ updateStateDisplay(data);
309
+ } catch (e) {
310
+ showError('stateError', `Get state failed: ${e.message}`);
311
+ } finally {
312
+ setButtons(false);
313
+ }
314
+ }
315
+
316
+ async function doStep() {
317
+ clearError('stepError');
318
+ const message = document.getElementById('messageInput').value.trim();
319
+ if (!message) {
320
+ showError('stepError', 'Language Specification is required.');
321
+ return;
322
+ }
323
+ setButtons(true);
324
+ try {
325
+ const res = await fetch(`${BASE_URL}/step`, {
326
+ method: 'POST',
327
+ headers: { 'Content-Type': 'application/json' },
328
+ body: JSON.stringify({ language_specification: message }),
329
+ });
330
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
331
+ const data = await res.json();
332
+ const obs = data.observation ?? data;
333
+ updateObsDisplay(obs);
334
+ if (data.state) {
335
+ updateStateDisplay({ ...data.state, status: 'Running' });
336
+ addToHistory(data.state.step_count, message, obs.reward ?? 0);
337
+ } else {
338
+ addToHistory(actionHistory.length + 1, message, obs.reward ?? 0);
339
+ }
340
+ document.getElementById('messageInput').value = '';
341
+ } catch (e) {
342
+ showError('stepError', `Step failed: ${e.message}`);
343
+ } finally {
344
+ setButtons(false);
345
+ }
346
+ }
347
+
348
+ // Load initial state on page load
349
+ (async () => {
350
+ try {
351
+ const res = await fetch(`${BASE_URL}/state`);
352
+ if (res.ok) {
353
+ const data = await res.json();
354
+ updateStateDisplay(data);
355
+ }
356
+ } catch (_) {}
357
+ })();
358
+ </script>
359
+ </body>
360
+ </html>
models.py CHANGED
@@ -10,19 +10,20 @@ Data models for the Agent Language Environment.
10
  The agent_language environment is a simple test environment that echoes back messages.
11
  """
12
 
 
13
  from pydantic import Field
14
 
15
- from openenv.core.env_server.types import Action, Observation
16
-
17
 
18
  class AgentLanguageAction(Action):
19
  """Action for the Agent Language environment - just a message to echo."""
20
 
21
- message: str = Field(..., description="Message to echo back")
22
 
23
 
24
  class AgentLanguageObservation(Observation):
25
  """Observation from the Agent Language environment - the echoed message."""
26
 
27
- echoed_message: str = Field(default="", description="The echoed message")
28
- message_length: int = Field(default=0, description="Length of the echoed message")
 
 
 
10
  The agent_language environment is a simple test environment that echoes back messages.
11
  """
12
 
13
+ from openenv.core.env_server.types import Action, Observation, State
14
  from pydantic import Field
15
 
 
 
16
 
17
  class AgentLanguageAction(Action):
18
  """Action for the Agent Language environment - just a message to echo."""
19
 
20
+ language_specification: str = Field(..., description="Language Specification")
21
 
22
 
23
  class AgentLanguageObservation(Observation):
24
  """Observation from the Agent Language environment - the echoed message."""
25
 
26
+ message: str = Field(default="", description="Scenario")
27
+
28
+ class AgentLanguageState(State):
29
+ """Custom state fields."""
openenv_agent_language.egg-info/PKG-INFO CHANGED
@@ -3,6 +3,7 @@ Name: openenv-agent_language
3
  Version: 0.1.0
4
  Summary: Agent Language environment for OpenEnv
5
  Requires-Python: >=3.10
 
6
  Requires-Dist: openenv-core[core]>=0.2.0
7
  Provides-Extra: dev
8
  Requires-Dist: pytest>=8.0.0; extra == "dev"
 
3
  Version: 0.1.0
4
  Summary: Agent Language environment for OpenEnv
5
  Requires-Python: >=3.10
6
+ Requires-Dist: openai>=2.26.0
7
  Requires-Dist: openenv-core[core]>=0.2.0
8
  Provides-Extra: dev
9
  Requires-Dist: pytest>=8.0.0; extra == "dev"
openenv_agent_language.egg-info/SOURCES.txt CHANGED
@@ -1,4 +1,7 @@
1
  README.md
 
 
 
2
  pyproject.toml
3
  ./__init__.py
4
  ./client.py
@@ -11,4 +14,5 @@ openenv_agent_language.egg-info/requires.txt
11
  openenv_agent_language.egg-info/top_level.txt
12
  server/__init__.py
13
  server/agent_language_environment.py
14
- server/app.py
 
 
1
  README.md
2
+ __init__.py
3
+ client.py
4
+ models.py
5
  pyproject.toml
6
  ./__init__.py
7
  ./client.py
 
14
  openenv_agent_language.egg-info/top_level.txt
15
  server/__init__.py
16
  server/agent_language_environment.py
17
+ server/app.py
18
+ server/evaluate_protocal.py
openenv_agent_language.egg-info/requires.txt CHANGED
@@ -1,3 +1,4 @@
 
1
  openenv-core[core]>=0.2.0
2
 
3
  [dev]
 
1
+ openai>=2.26.0
2
  openenv-core[core]>=0.2.0
3
 
4
  [dev]
pyproject.toml CHANGED
@@ -14,6 +14,7 @@ version = "0.1.0"
14
  description = "Agent Language environment for OpenEnv"
15
  requires-python = ">=3.10"
16
  dependencies = [
 
17
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
18
  # install from github
19
  # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
@@ -42,4 +43,4 @@ server = "agent_language.server.app:main"
42
  [tool.setuptools]
43
  include-package-data = true
44
  packages = ["agent_language", "agent_language.server"]
45
- package-dir = { "agent_language" = ".", "agent_language.server" = "server" }
 
14
  description = "Agent Language environment for OpenEnv"
15
  requires-python = ">=3.10"
16
  dependencies = [
17
+ "openai>=2.26.0",
18
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
19
  # install from github
20
  # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
 
43
  [tool.setuptools]
44
  include-package-data = true
45
  packages = ["agent_language", "agent_language.server"]
46
+ package-dir = { "agent_language" = ".", "agent_language.server" = "server" }
server/agent_language_environment.py CHANGED
@@ -13,11 +13,15 @@ Perfect for testing HTTP server infrastructure.
13
 
14
  from uuid import uuid4
15
 
 
 
16
  from openenv.core.env_server.interfaces import Environment
17
- from openenv.core.env_server.types import State
18
 
19
- from models import AgentLanguageAction, AgentLanguageObservation
20
 
 
 
 
21
 
22
  class AgentLanguageEnvironment(Environment):
23
  """
@@ -42,23 +46,26 @@ class AgentLanguageEnvironment(Environment):
42
  # getting their own environment instance (when using factory mode in app.py).
43
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
44
 
45
- def __init__(self):
46
  """Initialize the agent_language environment."""
47
- self._state = State(episode_id=str(uuid4()), step_count=0)
48
  self._reset_count = 0
 
49
 
50
- def reset(self) -> AgentLanguageObservation:
51
  """
52
  Reset the environment.
53
 
54
  Returns:
55
  AgentLanguageObservation with a ready message
56
  """
57
- self._state = State(episode_id=str(uuid4()), step_count=0)
58
  self._reset_count += 1
59
 
 
 
60
  return AgentLanguageObservation(
61
- echoed_message="Agent Language environment ready!",
62
  message_length=0,
63
  done=False,
64
  reward=0.0,
@@ -75,23 +82,17 @@ class AgentLanguageEnvironment(Environment):
75
  AgentLanguageObservation with the echoed message and its length
76
  """
77
  self._state.step_count += 1
78
-
79
  message = action.message
80
- length = len(message)
81
-
82
- # Simple reward: longer messages get higher rewards
83
- reward = length * 0.1
84
-
85
  return AgentLanguageObservation(
86
  echoed_message=message,
87
- message_length=length,
88
- done=False,
89
  reward=reward,
90
- metadata={"original_message": message, "step": self._state.step_count},
91
  )
92
 
93
  @property
94
- def state(self) -> State:
95
  """
96
  Get the current environment state.
97
 
 
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:
23
+ When you communicate, avoid extra greetings.
24
+ """
25
 
26
  class AgentLanguageEnvironment(Environment):
27
  """
 
46
  # getting their own environment instance (when using factory mode in app.py).
47
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
48
 
49
+ def __init__(self, seed):
50
  """Initialize the agent_language environment."""
51
+ self._state = AgentLanguageState(episode_id=str(uuid4()), step_count=0)
52
  self._reset_count = 0
53
+ self.seed = seed
54
 
55
+ def reset(self, seed) -> AgentLanguageObservation:
56
  """
57
  Reset the environment.
58
 
59
  Returns:
60
  AgentLanguageObservation with a ready message
61
  """
62
+ self._state = AgentLanguageState(episode_id=str(uuid4()), step_count=0)
63
  self._reset_count += 1
64
 
65
+ message = COMMUNICATION_PROTOCAL_PROMPT + "\n\n Design a communication protocal for two agents scheduling a meeting time."
66
+
67
  return AgentLanguageObservation(
68
+ message=message,
69
  message_length=0,
70
  done=False,
71
  reward=0.0,
 
82
  AgentLanguageObservation with the echoed message and its length
83
  """
84
  self._state.step_count += 1
 
85
  message = action.message
86
+ reward = evaluate_lang_spec(message)
 
 
 
 
87
  return AgentLanguageObservation(
88
  echoed_message=message,
89
+ done=True,
 
90
  reward=reward,
91
+ #metadata={"original_message": message, "step": self._state.step_count},
92
  )
93
 
94
  @property
95
+ def state(self) -> AgentLanguageState:
96
  """
97
  Get the current environment state.
98
 
server/app.py CHANGED
@@ -35,6 +35,8 @@ except Exception as e: # pragma: no cover
35
  "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
  ) from e
37
 
 
 
38
  # Import from local models.py (PYTHONPATH includes /app/env in Docker)
39
  from models import AgentLanguageAction, AgentLanguageObservation
40
  from .agent_language_environment import AgentLanguageEnvironment
@@ -49,6 +51,13 @@ app = create_app(
49
  max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
50
  )
51
 
 
 
 
 
 
 
 
52
 
53
  def main(host: str = "0.0.0.0", port: int = 8000):
54
  """
 
35
  "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
  ) from e
37
 
38
+ from fastapi.middleware.cors import CORSMiddleware
39
+
40
  # Import from local models.py (PYTHONPATH includes /app/env in Docker)
41
  from models import AgentLanguageAction, AgentLanguageObservation
42
  from .agent_language_environment import AgentLanguageEnvironment
 
51
  max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
52
  )
53
 
54
+ app.add_middleware(
55
+ CORSMiddleware,
56
+ allow_origins=["*"],
57
+ allow_methods=["*"],
58
+ allow_headers=["*"],
59
+ )
60
+
61
 
62
  def main(host: str = "0.0.0.0", port: int = 8000):
63
  """
server/evaluate_protocal.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
uv.lock CHANGED
@@ -1075,6 +1075,7 @@ name = "openenv-agent-language"
1075
  version = "0.1.0"
1076
  source = { editable = "." }
1077
  dependencies = [
 
1078
  { name = "openenv-core", extra = ["core"] },
1079
  ]
1080
 
@@ -1086,6 +1087,7 @@ dev = [
1086
 
1087
  [package.metadata]
1088
  requires-dist = [
 
1089
  { name = "openenv-core", extras = ["core"], specifier = ">=0.2.0" },
1090
  { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
1091
  { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0.0" },
 
1075
  version = "0.1.0"
1076
  source = { editable = "." }
1077
  dependencies = [
1078
+ { name = "openai" },
1079
  { name = "openenv-core", extra = ["core"] },
1080
  ]
1081
 
 
1087
 
1088
  [package.metadata]
1089
  requires-dist = [
1090
+ { name = "openai", specifier = ">=2.26.0" },
1091
  { name = "openenv-core", extras = ["core"], specifier = ">=0.2.0" },
1092
  { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
1093
  { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0.0" },