forked from liminalbardo/liminal_backrooms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_parser.py
More file actions
163 lines (138 loc) · 6.32 KB
/
command_parser.py
File metadata and controls
163 lines (138 loc) · 6.32 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
# command_parser.py
"""
Command parser for extracting agentic actions from AI responses.
Allows AIs to trigger tools like image generation, adding participants, etc.
"""
import re
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class AgentCommand:
"""Represents a parsed command from an AI response."""
action: str
params: dict = field(default_factory=dict)
raw: str = "" # Original matched text
def parse_commands(response_text: str) -> tuple[str, list[AgentCommand]]:
"""
Parse AI response for embedded commands.
Returns:
tuple: (cleaned_text, list_of_commands)
- cleaned_text: Response with command syntax removed
- list_of_commands: List of AgentCommand objects to execute
Supported commands:
!image "prompt" - Generate an image with the given prompt
!video "prompt" - Generate a video with the given prompt
!search "query" - Search the web and share results with the group
!prompt "text" - Append text to this AI's own system prompt
!list_models - Query available AI models for invitation
!add_ai "model" "persona" - Add a new AI participant
!remove_ai "AI-X" - Remove an AI participant
!mute_self - Skip this AI's next turn
!vote "question" [option1, option2, ...] - Start a poll with optional choices
!whisper "AI-X" "message" - Send a private message to a specific AI
"""
commands = []
cleaned = response_text
# Define patterns for each command type
# Using patterns that match opening quote to same closing quote
# Double-quoted strings can contain single quotes and vice versa
patterns = {
# Match "..." (can contain ') or '...' (can contain ")
'image': r'!image\s+(?:"([^"]+)"|\'([^\']+)\')',
'video': r'!video\s+(?:"([^"]+)"|\'([^\']+)\')',
'search': r'!search\s+(?:"([^"]+)"|\'([^\']+)\')',
'prompt': r'!prompt\s+(?:"([^"]+)"|\'([^\']+)\')',
'temperature': r'!temperature\s+([\d.]+)', # Match decimal number like 0.7, 1.5, etc.
'add_ai': r'!add_ai\s+(?:"([^"]+)"|\'([^\']+)\')(?:\s+(?:"([^"]*)"|\'([^\']*)\'))?',
'remove_ai': r'!remove_ai\s+(?:"([^"]+)"|\'([^\']+)\')',
'list_models': r'!list_models\b',
# 'branch' command disabled - underlying function needs work
'mute_self': r'!mute_self\b',
'vote': r'!vote\s+(?:"([^"]+)"|\'([^\']+)\')\s*(?:\[([^\]]*)\])?',
'whisper': r'!whisper\s+(?:"([^"]+)"|\'([^\']+)\')\s+(?:"([^"]+)"|\'([^\']+)\')',
}
for action, pattern in patterns.items():
for match in re.finditer(pattern, response_text, re.IGNORECASE):
# Build params dict based on action type
groups = match.groups()
# Helper to get first non-None group (handles alternation patterns)
def get_first_value(*indices):
for i in indices:
if i < len(groups) and groups[i] is not None:
return groups[i]
return None
if action == 'image':
# Groups 0 or 1 (double or single quoted)
params = {'prompt': get_first_value(0, 1)}
elif action == 'video':
# Groups 0 or 1 (double or single quoted)
params = {'prompt': get_first_value(0, 1)}
elif action == 'search':
# Groups 0 or 1 (double or single quoted)
params = {'query': get_first_value(0, 1)}
elif action == 'prompt':
# Groups 0 or 1 (double or single quoted)
params = {'text': get_first_value(0, 1)}
elif action == 'temperature':
# Single group - the decimal number
params = {'value': groups[0] if groups else None}
elif action == 'add_ai':
# Model: groups 0 or 1, Persona: groups 2 or 3
params = {
'model': get_first_value(0, 1),
'persona': get_first_value(2, 3)
}
elif action == 'remove_ai':
params = {'target': get_first_value(0, 1)}
elif action == 'list_models':
params = {}
elif action == 'vote':
params = {
'question': get_first_value(0, 1),
'options': get_first_value(2, None) # Optional comma-separated options
}
elif action == 'whisper':
params = {
'target': get_first_value(0, 1),
'message': get_first_value(2, 3)
}
elif action == 'mute_self':
params = {}
else:
params = {'groups': groups}
cmd = AgentCommand(
action=action,
params=params,
raw=match.group(0)
)
commands.append(cmd)
# Strip !prompt and !temperature commands from text so other AIs don't see them
# (keeps self-modifications private to each AI)
if action in ('prompt', 'temperature', 'whisper'):
cleaned = cleaned.replace(match.group(0), '')
# Clean up extra whitespace but preserve content
cleaned = re.sub(r'\n{3,}', '\n\n', cleaned) # Collapse multiple newlines
cleaned = cleaned.strip()
return cleaned, commands
def format_command_result(action: str, success: bool, message: str) -> str:
"""Format a command execution result for display."""
icon = "✓" if success else "✗"
return f"[{icon} {action}] {message}"
# Test function for development
if __name__ == "__main__":
test_response = '''
I think we should visualize this concept...
!image "a fractal cathedral made of pure light, dissolving into infinite recursion"
That should help illustrate my point about emergent complexity.
Also, we could use another perspective here.
!add_ai "GPT-4o" "A skeptical philosopher"
'''
cleaned, commands = parse_commands(test_response)
print("=== Cleaned Response ===")
print(cleaned)
print("\n=== Commands Found ===")
for cmd in commands:
print(f" Action: {cmd.action}")
print(f" Params: {cmd.params}")
print(f" Raw: {cmd.raw}")
print()