-
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathai_shell_machine.py
More file actions
568 lines (462 loc) · 18.2 KB
/
ai_shell_machine.py
File metadata and controls
568 lines (462 loc) · 18.2 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""
AI Shell -- coding assistant
=============================
A feature-rich coding assistant powered by python-statemachine.
A standalone interactive CLI that uses the OpenAI SDK for LLM calls with
tool_use. Demonstrates **parallel states**, **compound states**,
**HistoryState**, **eventless transitions**, **In() guards**,
**done.state**, **error.execution**, **invoke**, and **raise_()** — all
working together in a practical application.
.. warning::
This example grants an LLM the ability to read files, list directories,
and execute shell commands — which can be very useful for exploring a
codebase, running tests, or automating tasks. However, the actual behavior
depends on the prompts you send and the model you use, and unintended
actions (e.g., deleting files or exposing credentials) are possible.
**Use at your own risk.** This code is provided for educational and
demonstration purposes only. The authors and contributors of
python-statemachine accept no liability for any damage or data loss.
Consider running it in an isolated environment (e.g., a container or
virtual machine) and avoid using elevated privileges.
Usage::
# Standalone (installs deps from PyPI)
OPENAI_API_KEY=sk-... uv run examples/ai_shell.py
# From the repo (uses local statemachine)
OPENAI_API_KEY=sk-... uv run --with openai python examples/ai_shell.py
# Debug mode — shows engine macro/micro step log on stderr
OPENAI_API_KEY=sk-... uv run --with openai python examples/ai_shell.py -v
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "openai",
# "python-statemachine",
# ]
# ///
import itertools
import json
import logging
import os
import random
import subprocess
import sys
import threading
from statemachine import HistoryState
from statemachine import State
from statemachine import StateChart
if "-v" in sys.argv or "--verbose" in sys.argv:
logging.basicConfig(level=logging.DEBUG, format="%(name)s %(message)s", stream=sys.stderr)
# ---------------------------------------------------------------------------
# Tool definitions (OpenAI function calling format)
# ---------------------------------------------------------------------------
TOOLS = [
{
"type": "function",
"function": {
"name": "read_file",
"description": (
"Read the contents of a file at the given path. "
"Returns the file contents (truncated to 10 000 characters)."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Absolute or relative file path."},
},
"required": ["path"],
},
},
},
{
"type": "function",
"function": {
"name": "list_files",
"description": "List files and directories at the given path.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path. Defaults to '.' (current directory).",
},
},
},
},
},
{
"type": "function",
"function": {
"name": "run_command",
"description": (
"Run a shell command and return its stdout and stderr. "
"Commands are executed with a 30-second timeout."
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell command to execute.",
},
},
"required": ["command"],
},
},
},
]
SYSTEM_PROMPT = (
"You are a helpful coding assistant. You can read files, list directory contents, "
"and run shell commands to help the user with their tasks. Be concise and practical. "
"You also have tools to introspect the state machine that powers this shell — use them "
"when the user asks about the current state, allowed transitions, or other metadata."
)
MAX_FILE_CHARS = 10_000
COMMAND_TIMEOUT = 30
MAX_RETRIES = 3
# ---------------------------------------------------------------------------
# Spinner animation
# ---------------------------------------------------------------------------
SPINNER_CHARS = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
SPINNER_MESSAGES = [
"thinking...",
"contemplating...",
"cooking something up...",
"making something special...",
"crunching the data...",
"pondering...",
"culminating...",
"brewing ideas...",
"connecting the dots...",
"almost there...",
]
class Spinner:
"""Animated terminal spinner shown while the LLM is working."""
def __init__(self):
self._stop = threading.Event()
self._thread: "threading.Thread | None" = None
def __enter__(self):
self._stop.clear()
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
return self
def __exit__(self, *args):
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=2)
def _run(self):
messages = SPINNER_MESSAGES[:]
random.shuffle(messages)
msg_cycle = itertools.cycle(messages)
char_cycle = itertools.cycle(SPINNER_CHARS)
msg = next(msg_cycle)
tick = 0
while not self._stop.wait(timeout=0.08):
char = next(char_cycle)
if tick > 0 and tick % 30 == 0:
msg = next(msg_cycle)
line = f" {char} {msg}"
print(f"\r{line:<50}", end="", flush=True)
tick += 1
print(f"\r{'':50}\r", end="", flush=True)
# ---------------------------------------------------------------------------
# Tool execution
# ---------------------------------------------------------------------------
def _tool_read_file(input_data: dict) -> str:
path = input_data["path"]
try:
with open(path) as f:
content = f.read(MAX_FILE_CHARS + 1)
if len(content) > MAX_FILE_CHARS:
content = content[:MAX_FILE_CHARS] + "\n... (truncated)"
return content
except OSError as e:
return f"Error reading file: {e}"
def _tool_list_files(input_data: dict) -> str:
path = input_data.get("path", ".")
try:
entries = sorted(os.listdir(path))
return "\n".join(entries)
except OSError as e:
return f"Error listing directory: {e}"
def _tool_run_command(input_data: dict) -> str:
command = input_data["command"]
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=COMMAND_TIMEOUT,
)
output = ""
if result.stdout:
output += result.stdout
if result.stderr:
output += ("" if not output else "\n") + f"stderr: {result.stderr}"
if result.returncode != 0:
output += f"\n(exit code {result.returncode})"
return output or "(no output)"
except subprocess.TimeoutExpired:
return f"Error: command timed out after {COMMAND_TIMEOUT}s"
except OSError as e:
return f"Error running command: {e}"
TOOL_HANDLERS = {
"read_file": _tool_read_file,
"list_files": _tool_list_files,
"run_command": _tool_run_command,
}
# ---------------------------------------------------------------------------
# State machine introspection tools
# ---------------------------------------------------------------------------
def _tool_sm_configuration(sm, input_data: dict) -> str:
states = sorted(sm.configuration_values)
return json.dumps({"active_states": states})
def _tool_sm_enabled_events(sm, input_data: dict) -> str:
events = sorted({e.name for e in sm.enabled_events()})
return json.dumps({"enabled_events": events})
def _tool_sm_macrostep_count(sm, input_data: dict) -> str:
return json.dumps({"macrostep_count": sm._engine._macrostep_count})
def _tool_sm_states(sm, input_data: dict) -> str:
all_states = sorted(sm.states_map.keys())
return json.dumps({"all_states": all_states})
SM_TOOL_HANDLERS = {
"sm_configuration": _tool_sm_configuration,
"sm_enabled_events": _tool_sm_enabled_events,
"sm_macrostep_count": _tool_sm_macrostep_count,
"sm_states": _tool_sm_states,
}
SM_TOOLS = [
{
"type": "function",
"function": {
"name": "sm_configuration",
"description": (
"Get the current active states (configuration) of the state machine. "
"Returns which states are currently active."
),
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "sm_enabled_events",
"description": (
"List events (transitions) that can be triggered from the current "
"state machine configuration, considering guard conditions."
),
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "sm_macrostep_count",
"description": (
"Get the current macrostep counter of the state machine engine. "
"A macrostep is the full processing cycle for one external event."
),
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "sm_states",
"description": (
"List all states defined in the state machine, including nested states "
"inside compound and parallel states."
),
"parameters": {"type": "object", "properties": {}},
},
},
]
def execute_tool(name: str, input_data: dict, sm=None) -> str:
sm_handler = SM_TOOL_HANDLERS.get(name)
if sm_handler is not None:
return sm_handler(sm, input_data)
handler = TOOL_HANDLERS.get(name)
if handler is None:
return f"Unknown tool: {name}"
return handler(input_data)
# ---------------------------------------------------------------------------
# State machine
# ---------------------------------------------------------------------------
GOODBYE_WORDS = {"bye", "exit", "quit"}
class AIShell(StateChart):
"""An agentic coding assistant as a StateChart.
Demonstrates parallel states, compound states, HistoryState, eventless
transitions, In() guards, done.state, error.execution, invoke, and
raise_() — all in a practical application.
States::
session (Parallel)
├── conversation (Compound)
│ ├── idle (initial)
│ ├── processing (Compound)
│ │ ├── thinking (initial, invoke) ← API call + spinner
│ │ ├── using_tool (invoke) ← tool execution
│ │ ├── done (final)
│ │ └── h = HistoryState(deep) ← for error retry
│ ├── responding
│ ├── recovering ← error.execution handler
│ └── conversation_ended (final)
└── context_tracker (Compound)
├── fresh (initial)
├── active (≥4 messages)
├── deep (≥20 messages, shows warning)
└── tracker_done (final)
"""
catch_errors_as_events = True
# --- Top-level parallel state: two independent regions ---
class session(State.Parallel):
class conversation(State.Compound):
idle = State("Idle", initial=True)
class processing(State.Compound):
thinking = State("Thinking", initial=True)
using_tool = State("Using Tool")
done = State("Done", final=True)
h = HistoryState(type="deep")
# Invoke results route automatically
done_invoke_thinking = thinking.to(
using_tool, cond="has_tool_calls"
) | thinking.to(done)
done_invoke_using_tool = using_tool.to(thinking)
responding = State("Responding")
recovering = State("Recovering")
conversation_ended = State("Ended", final=True)
# Named events
user_message = idle.to(processing, cond="is_not_goodbye") | idle.to(
conversation_ended, cond="is_goodbye"
)
done_state_processing = processing.to(responding)
error_execution = processing.to(recovering)
# Eventless transitions
responding.to(idle)
recovering.to(processing.h, cond="can_retry")
recovering.to(idle, cond="cannot_retry")
class context_tracker(State.Compound):
fresh = State("Fresh", initial=True)
active = State("Active")
deep = State("Deep")
tracker_done = State(final=True)
# Eventless: track conversation depth
fresh.to(active, cond="is_active_context")
active.to(deep, cond="is_deep_context")
# Eventless + In() guard: follow conversation end
fresh.to(tracker_done, cond="In('conversation_ended')")
active.to(tracker_done, cond="In('conversation_ended')")
deep.to(tracker_done, cond="In('conversation_ended')")
# --- Initialization ---
def __init__(self):
from openai import OpenAI # type: ignore[import-not-found]
self.client = OpenAI()
self.messages: list = [{"role": "system", "content": SYSTEM_PROMPT}]
self._last_text: str = ""
self._retries: int = 0
self._ready = threading.Event()
super().__init__()
# --- Guards ---
def is_goodbye(self, text="", **kwargs) -> bool:
return text.strip().lower() in GOODBYE_WORDS
def is_not_goodbye(self, text="", **kwargs) -> bool:
return not self.is_goodbye(text=text)
def can_retry(self, **kwargs) -> bool:
return self._retries < MAX_RETRIES
def cannot_retry(self, **kwargs) -> bool:
return not self.can_retry()
def is_active_context(self, **kwargs) -> bool:
return len(self.messages) >= 5
def is_deep_context(self, **kwargs) -> bool:
return len(self.messages) >= 20
# --- Callbacks ---
def on_user_message(self, text, **kwargs):
"""Append the user's message to conversation history."""
self.messages.append({"role": "user", "content": text})
def has_tool_calls(self, data=None, **kwargs) -> bool:
"""Guard: check if the API response contains tool calls."""
return bool(getattr(data, "tool_calls", None))
def on_invoke_thinking(self, **kwargs):
"""Call the OpenAI API with a spinner animation. Returns the message."""
with Spinner():
response = self.client.chat.completions.create(
model="gpt-4o-mini",
messages=self.messages,
tools=TOOLS + SM_TOOLS,
)
message = response.choices[0].message
self.messages.append(message)
if not message.tool_calls:
self._last_text = message.content or ""
return message
def on_invoke_using_tool(self, data, **kwargs):
"""Execute tool calls from the API response."""
for call in data.tool_calls:
args = json.loads(call.function.arguments)
print(f" [tool] {call.function.name}({json.dumps(args)})")
result = execute_tool(call.function.name, args, sm=self)
self.messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": result,
}
)
def on_enter_responding(self, **kwargs):
"""Print the assistant's text response."""
if self._last_text:
print(f"\n{self._last_text}")
self._last_text = ""
def on_enter_idle(self, **kwargs):
"""Reset retry counter and signal readiness when returning to idle."""
self._retries = 0
self._ready.set()
def on_enter_recovering(self, **kwargs):
"""Handle API errors with retry logic (via error.execution)."""
self._retries += 1
if self._retries < MAX_RETRIES:
print(f"\n [error] API call failed, retrying ({self._retries}/{MAX_RETRIES})...")
else:
print(f"\n [error] API call failed after {MAX_RETRIES} attempts. Giving up.")
def on_enter_deep(self, **kwargs):
"""Warn when conversation context is getting long."""
print(" [context] Conversation is getting long — responses may degrade.")
def on_enter_conversation_ended(self, **kwargs):
print("\nGoodbye!")
# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------
def _check_openai():
"""Return True if the openai package is available."""
try:
import openai # noqa: F401
return True
except ImportError:
return False
def main():
if not _check_openai():
print("This example requires the 'openai' package.")
print("Install it with: pip install openai")
return
print("AI Shell")
print("A coding assistant powered by python-statemachine + OpenAI.")
print("Type 'bye', 'exit', or 'quit' to end. Ctrl+C to interrupt.")
if "-v" in sys.argv or "--verbose" in sys.argv:
print("Debug mode enabled — engine log is written to stderr.\n")
else:
print("Tip: run with -v to see engine macro/micro step debug log.\n")
try:
sm = AIShell()
except Exception as e:
sys.exit(f"Error initializing: {e}")
while not sm.is_terminated:
sm._ready.wait()
sm._ready.clear()
try:
text = input("> ")
except (EOFError, KeyboardInterrupt):
print()
break
if text.strip():
sm.send("user_message", text=text)
if __name__ == "__main__" and "sphinx" not in sys.modules: # pragma: no cover
main()