-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRegexAgentService.java
More file actions
359 lines (309 loc) · 13.8 KB
/
Copy pathRegexAgentService.java
File metadata and controls
359 lines (309 loc) · 13.8 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
package rsp.app.posts.services;
import rsp.compositions.block.Block;
import rsp.compositions.block.BlockTarget;
import rsp.compositions.block.BlockAction;
import rsp.compositions.block.BlockActionPayload;
import rsp.compositions.agent.AgentService;
import rsp.compositions.agent.BlockProfile;
import rsp.compositions.composition.StructureNode;
import rsp.util.json.JsonDataType;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Regex-based agent service — test/demo substitute for an LLM.
* <p>
* Parses natural-language prompts into agent results using simple regex matching.
* Supports CRUD operations (delete, search, update), pagination, selection,
* and navigation.
*/
public class RegexAgentService extends AgentService {
/**
* Internal state for multi-step interactions.
*/
sealed interface AgentState {
record Idle() implements AgentState {}
record PendingSave(String modification) implements AgentState {}
}
// Patterns
private static final Pattern DELETE_QUOTED_PATTERN = Pattern.compile(
"delete\\s+['\"](.+?)['\"]", Pattern.CASE_INSENSITIVE);
private static final Pattern DELETE_UNQUOTED_PATTERN = Pattern.compile(
"delete\\s+(.+)", Pattern.CASE_INSENSITIVE);
private static final Pattern SEARCH_PATTERN = Pattern.compile(
"search\\s+.*?with\\s+(\\w+)\\s*([<>=!]+)\\s*(\\w+)", Pattern.CASE_INSENSITIVE);
private static final Pattern UPDATE_PATTERN = Pattern.compile(
"update\\s+.*?(\\d+)\\s+adding\\s+['\"](.+?)['\"]", Pattern.CASE_INSENSITIVE);
private static final Pattern PAGE_PATTERN = Pattern.compile(
"(?:go to\\s+)?page\\s+(\\d+)", Pattern.CASE_INSENSITIVE);
private static final Pattern SELECT_ALL_PATTERN = Pattern.compile(
"select\\s+all", Pattern.CASE_INSENSITIVE);
private static final Pattern EDIT_SELECTED_PATTERN = Pattern.compile(
"edit\\s+selected", Pattern.CASE_INSENSITIVE);
private static final Pattern NAVIGATE_PATTERN = Pattern.compile(
"(?:show|open|go to)\\s+(.+)", Pattern.CASE_INSENSITIVE);
private AgentState state = new AgentState.Idle();
@Override
public AgentResult handlePrompt(String prompt,
BlockProfile profile,
StructureNode structureTree) {
// Detect compound commands (e.g. "show comments and go to page 2")
List<String> parts = Arrays.stream(prompt.split("\\b(?:and then|then|and)\\b"))
.map(String::trim)
.filter(s -> !s.isEmpty())
.toList();
if (parts.size() > 1) {
return new AgentResult.PlanResult(parts, "Executing " + parts.size() + " steps");
}
// Step 2 of update flow: we're waiting for the edit block to be active
if (state instanceof AgentState.PendingSave pending) {
state = new AgentState.Idle();
return handlePendingSave(pending.modification(), profile);
}
Matcher m;
// Delete by name: delete 'Post Title 1' or delete Post Title 1
m = DELETE_QUOTED_PATTERN.matcher(prompt);
if (m.find()) {
return handleDelete(m.group(1), profile);
}
// Select all rows
m = SELECT_ALL_PATTERN.matcher(prompt);
if (m.find()) {
return findActionResult("select_all", BlockActionPayload.EMPTY, profile);
}
// Edit selected item
m = EDIT_SELECTED_PATTERN.matcher(prompt);
if (m.find()) {
return handleEditSelected(profile);
}
// Search/filter: search all posts with id < 2
m = SEARCH_PATTERN.matcher(prompt);
if (m.find()) {
return handleSearch(m.group(1), m.group(2), m.group(3), profile);
}
// Update: update post 2 adding 'test'
m = UPDATE_PATTERN.matcher(prompt);
if (m.find()) {
return handleUpdate(m.group(1), m.group(2), profile);
}
// Pagination: go to page 3
m = PAGE_PATTERN.matcher(prompt);
if (m.find()) {
int page = Integer.parseInt(m.group(1));
return findActionResult("page", BlockActionPayload.of(page), profile);
}
// Navigation: show posts
m = NAVIGATE_PATTERN.matcher(prompt);
if (m.find()) {
return handleNavigate(m.group(1), structureTree);
}
// Delete without quotes (last — broad match)
m = DELETE_UNQUOTED_PATTERN.matcher(prompt);
if (m.find()) {
return handleDelete(m.group(1).trim(), profile);
}
return new AgentResult.TextReply(
"Hello, I am a regex-based LLM agent simulator.\n" +
"\n" +
"I recognise a small set of commands:\n" +
"\n" +
" • Navigate: show posts / show comments\n" +
" • Paginate: go to page 2\n" +
" • Select: select all\n" +
" • Edit: edit selected\n" +
" • Delete: delete 'Post Title 1'\n" +
" • Search: search posts with id < 2\n" +
" • Update: update post 2 adding 'draft'\n" +
"\n" +
"Chain steps with \"and\" or \"then\", e.g. \"show comments and go to page 2\".");
}
/**
* Reset the agent's internal state (e.g., after navigation changes the active block).
*/
public void reset() {
state = new AgentState.Idle();
}
// --- Action lookup helper ---
private AgentResult findActionResult(String actionName, BlockActionPayload payload, BlockProfile profile) {
for (BlockAction action : profile.actions()) {
if (action.action().equals(actionName)) {
return new AgentResult.ActionResult(action, payload);
}
}
return new AgentResult.TextReply("Action '" + actionName + "' not available.");
}
// --- Delete by name ---
private AgentResult handleDelete(String name, BlockProfile profile) {
List<Map<String, Object>> items = extractItems(profile);
for (Map<String, Object> item : items) {
if (matchesName(item, name)) {
Object id = item.get("id");
if (id != null) {
BlockActionPayload payload = new BlockActionPayload(
new JsonDataType.Array(new JsonDataType.String(String.valueOf(id))));
return findActionResult("delete", payload, profile);
}
}
}
return new AgentResult.TextReply("Item '" + name + "' not found on the current page.");
}
private boolean matchesName(Map<String, Object> item, String name) {
for (String key : List.of("title", "name", "label")) {
Object value = item.get(key);
if (value != null && String.valueOf(value).equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
// --- Edit selected ---
private AgentResult handleEditSelected(BlockProfile profile) {
if (!profile.isList()) {
return new AgentResult.TextReply("No list block active — nothing selected.");
}
return findActionResult("edit", BlockActionPayload.EMPTY, profile);
}
// --- Search/filter ---
private AgentResult handleSearch(String field, String operator, String value,
BlockProfile profile) {
List<Map<String, Object>> items = extractItems(profile);
List<Map<String, Object>> matches = new ArrayList<>();
for (Map<String, Object> item : items) {
Object fieldValue = item.get(field);
if (fieldValue != null && compareValues(String.valueOf(fieldValue), operator, value)) {
matches.add(item);
}
}
if (matches.isEmpty()) {
return new AgentResult.TextReply(
"No items found matching '" + field + " " + operator + " " + value + "'.");
}
StringBuilder sb = new StringBuilder();
sb.append("Found ").append(matches.size()).append(" item(s) matching '")
.append(field).append(" ").append(operator).append(" ").append(value).append("':\n");
for (Map<String, Object> match : matches) {
sb.append(" - ").append(formatItem(match)).append("\n");
}
return new AgentResult.TextReply(sb.toString().trim());
}
private boolean compareValues(String fieldValue, String operator, String value) {
try {
double fv = Double.parseDouble(fieldValue);
double v = Double.parseDouble(value);
return switch (operator) {
case "<" -> fv < v;
case "<=" -> fv <= v;
case ">" -> fv > v;
case ">=" -> fv >= v;
case "=", "==" -> fv == v;
case "!=", "<>" -> fv != v;
default -> false;
};
} catch (NumberFormatException e) {
int cmp = fieldValue.compareToIgnoreCase(value);
return switch (operator) {
case "=" , "==" -> cmp == 0;
case "!=", "<>" -> cmp != 0;
case "<" -> cmp < 0;
case ">" -> cmp > 0;
default -> false;
};
}
}
// --- Update (two-step) ---
private AgentResult handleUpdate(String id, String modification, BlockProfile profile) {
state = new AgentState.PendingSave(modification);
return findActionResult("edit", BlockActionPayload.of(id), profile);
}
private AgentResult handlePendingSave(String modification, BlockProfile profile) {
if (!profile.isEdit() && !profile.isForm()) {
return new AgentResult.TextReply(
"Expected edit form to be active, but current block is not a form.");
}
Map<String, Object> fieldValues = new LinkedHashMap<>(extractEntity(profile));
if (fieldValues.isEmpty()) {
return new AgentResult.TextReply("Cannot read entity from the active block.");
}
String targetField = findTextFieldForModification(fieldValues);
if (targetField != null) {
Object current = fieldValues.get(targetField);
fieldValues.put(targetField, current + " " + modification);
} else {
return new AgentResult.TextReply(
"Cannot determine which field to modify. Fields: " + fieldValues.keySet());
}
return findActionResult("save", toAgentPayload(fieldValues), profile);
}
private String findTextFieldForModification(Map<String, Object> fields) {
if (fields.containsKey("content")) return "content";
if (fields.containsKey("title")) return "title";
for (Map.Entry<String, Object> entry : fields.entrySet()) {
if (!"id".equals(entry.getKey()) && entry.getValue() instanceof String) {
return entry.getKey();
}
}
return null;
}
// --- Navigation ---
private AgentResult handleNavigate(String target, StructureNode structureTree) {
BlockTarget blockTarget = findBlockByLabel(target.trim(), structureTree);
if (blockTarget != null) {
return new AgentResult.NavigateResult(blockTarget);
}
return new AgentResult.TextReply("No block found matching '" + target + "'.");
}
@SuppressWarnings("unchecked")
private BlockTarget findBlockByLabel(String label, StructureNode node) {
if (node.label() != null && node.label().equalsIgnoreCase(label)) {
if (!node.blockTargets().isEmpty()) {
return node.blockTargets().getFirst();
}
}
for (StructureNode child : node.children()) {
BlockTarget found = findBlockByLabel(label, child);
if (found != null) return found;
}
return null;
}
// --- Metadata extraction helpers ---
@SuppressWarnings("unchecked")
private List<Map<String, Object>> extractItems(BlockProfile profile) {
if (profile.metadata() != null
&& profile.metadata().state().get("items") instanceof List<?> list) {
return (List<Map<String, Object>>) list;
}
return List.of();
}
@SuppressWarnings("unchecked")
private Map<String, Object> extractEntity(BlockProfile profile) {
if (profile.metadata() != null
&& profile.metadata().state().get("entity") instanceof Map<?, ?> map) {
return (Map<String, Object>) map;
}
return Map.of();
}
private String formatItem(Map<String, Object> item) {
String name = String.valueOf(item.getOrDefault("title",
item.getOrDefault("name",
item.getOrDefault("label", "?"))));
String id = String.valueOf(item.getOrDefault("id", "?"));
return name + " (id: " + id + ")";
}
// --- Java value to AgentPayload conversion ---
private static BlockActionPayload toAgentPayload(Map<String, Object> map) {
Map<String, JsonDataType> entries = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : map.entrySet()) {
entries.put(e.getKey(), toJsonDataType(e.getValue()));
}
return new BlockActionPayload(new JsonDataType.Object(entries));
}
private static JsonDataType toJsonDataType(Object value) {
if (value == null) return JsonDataType.Null.INSTANCE;
if (value instanceof String s) return new JsonDataType.String(s);
if (value instanceof Integer i) return JsonDataType.Number.of(i);
if (value instanceof Long l) return JsonDataType.Number.of(l);
if (value instanceof Double d) return JsonDataType.Number.of(d);
if (value instanceof Boolean b) return new JsonDataType.Boolean(b);
return new JsonDataType.String(value.toString());
}
}