-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathextra_parser.py
More file actions
423 lines (384 loc) · 14.2 KB
/
extra_parser.py
File metadata and controls
423 lines (384 loc) · 14.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
import copy
import json
import re
from abc import ABC, abstractmethod
from mcp_parser import build_mcp_tool_schema, extract_mcp_section, parse_mcp_sections
from model import JsonObj
from parser import extract_block_after_label
class ExtraParserIF(ABC):
tool_name: str
@staticmethod
@abstractmethod
def search_patterns(text: str) -> list[dict[str, str]]:
raise NotImplementedError
@staticmethod
@abstractmethod
def get_schema(
doc: str, original_schema: JsonObj, system_prompt: str
) -> tuple[JsonObj | list[JsonObj] | None, dict[str, str]]:
raise NotImplementedError
@staticmethod
@abstractmethod
def postconvert_to_tool_call(
tool_name: str, arguments: JsonObj
) -> tuple[str, JsonObj]:
raise NotImplementedError
@staticmethod
@abstractmethod
def preconvert_to_xml(tool_name: str, arguments: JsonObj) -> tuple[str, JsonObj]:
raise NotImplementedError
class ReplaceInFileParser(ExtraParserIF):
tool_name = "replace_in_file"
@staticmethod
def search_patterns(text: str) -> list[dict[str, str]]:
pattern = re.compile(
r"(?P<indent>[ \t]*)------- SEARCH\n(?P<search>.*?)\n"
r"(?P=indent)=======\n(?P<replace>.*?)\n"
r"(?P=indent)\+\+\+\+\+\+\+ REPLACE",
re.DOTALL,
)
results = []
for m in pattern.finditer(text):
results.append(
{
"matched": m.group(0),
"search": m.group("search"),
"replace": m.group("replace"),
}
)
return results
@staticmethod
def get_schema(
doc: str, original_schema: JsonObj, system_prompt: str
) -> tuple[JsonObj | None, dict[str, str]]:
if original_schema["function"]["name"] != ReplaceInFileParser.tool_name:
return None, {}
block = extract_block_after_label(doc, "Parameters:")
params = ReplaceInFileParser.search_patterns(block)
if not params:
return None, {}
original_schema = copy.deepcopy(original_schema)
if diff := original_schema["function"]["parameters"]["properties"].get(
"diff", {}
):
diff["type"] = "array"
diff["items"] = {
"type": "object",
"properties": {
"SEARCH": {
"type": "string",
"description": params[0]["search"],
},
"REPLACE": {
"type": "string",
"description": params[0]["replace"],
},
},
"required": ["SEARCH", "REPLACE"],
}
return original_schema, {}
else:
return None, {}
@staticmethod
def postconvert_to_tool_call(
tool_name: str, arguments: JsonObj
) -> tuple[str, JsonObj]:
if tool_name != ReplaceInFileParser.tool_name:
return tool_name, arguments
diff = arguments.get("diff")
if not isinstance(diff, str):
# fallback
return tool_name, arguments
patterns = ReplaceInFileParser.search_patterns(diff)
if not patterns:
# fallback
return tool_name, arguments
arguments = copy.deepcopy(arguments)
arguments["diff"] = patterns
return tool_name, arguments
@staticmethod
def preconvert_to_xml(tool_name: str, arguments: JsonObj) -> tuple[str, JsonObj]:
if (
tool_name != ReplaceInFileParser.tool_name
or "diff" not in arguments
or isinstance(arguments["diff"], str)
):
return tool_name, arguments
elif not isinstance(arguments["diff"], list):
org_diffs = [arguments["diff"]]
else:
org_diffs = arguments["diff"]
diffs = []
for diff in org_diffs:
if isinstance(diff, dict):
search = diff.get("SEARCH", "")
replace = diff.get("REPLACE", "")
diffs.append(
f"------- SEARCH\n{search}\n=======\n{replace}\n+++++++ REPLACE"
)
arguments = copy.deepcopy(arguments)
arguments["diff"] = "\n".join(diffs)
return tool_name, arguments
class ApplyDiffParser(ExtraParserIF):
tool_name = "apply_diff"
@staticmethod
def search_patterns(text: str) -> list[dict[str, str]]:
pattern = re.compile(
r"<<<<<<< SEARCH\n"
r":start_line:\s*(?P<start_line>.*?)\n"
r"-------\n(?P<search>.*?)\n"
r"=======\n(?P<replace>.*?)\n"
r">>>>>>> REPLACE",
re.DOTALL,
)
results = []
for m in pattern.finditer(text):
results.append(
{
"matched": m.group(0),
"start_line": m.group("start_line"),
"search": m.group("search"),
"replace": m.group("replace"),
}
)
return results
@staticmethod
def get_schema(
doc: str, original_schema: JsonObj, system_prompt: str
) -> tuple[JsonObj | None | dict[str, str]]:
if original_schema["function"]["name"] != ApplyDiffParser.tool_name:
return None, {}
block = extract_block_after_label(doc, "Diff format:")
params = ApplyDiffParser.search_patterns(block)
if not params:
return None, {}
original_schema = copy.deepcopy(original_schema)
if diff := original_schema["function"]["parameters"]["properties"].get(
"diff", {}
):
diff["type"] = "array"
diff["items"] = {
"type": "object",
"properties": {
"start_line": {
"type": "string",
"description": params[0]["start_line"],
},
"SEARCH": {
"type": "string",
"description": params[0]["search"],
},
"REPLACE": {
"type": "string",
"description": params[0]["replace"],
},
},
"required": ["start_line", "SEARCH", "REPLACE"],
}
return original_schema, {}
else:
return None, {}
@staticmethod
def postconvert_to_tool_call(
tool_name: str, arguments: JsonObj
) -> tuple[str, JsonObj]:
if tool_name != ApplyDiffParser.tool_name:
return tool_name, arguments
diff = arguments.get("diff")
if not isinstance(diff, str):
# fallback
return tool_name, arguments
patterns = ApplyDiffParser.search_patterns(diff)
if not patterns:
# fallback
return tool_name, arguments
arguments = copy.deepcopy(arguments)
arguments["diff"] = patterns
return tool_name, arguments
@staticmethod
def preconvert_to_xml(tool_name: str, arguments: JsonObj) -> tuple[str, JsonObj]:
if (
tool_name != ApplyDiffParser.tool_name
or "diff" not in arguments
or isinstance(arguments["diff"], str)
):
return tool_name, arguments
elif not isinstance(arguments["diff"], list):
org_diffs = [arguments["diff"]]
else:
org_diffs = arguments["diff"]
diffs = []
for diff in org_diffs:
if isinstance(diff, dict):
search = re.sub(
r"^(<<<<<<< SEARCH|=======|>>>>>>> REPLACE)$",
r"\\\1",
diff.get("SEARCH", ""),
flags=re.MULTILINE,
)
replace = re.sub(
r"^(<<<<<<< SEARCH|=======|>>>>>>> REPLACE)$",
r"\\\1",
diff.get("REPLACE", ""),
flags=re.MULTILINE,
)
diffs.append(
f"<<<<<<< SEARCH\n"
f":start_line:{diff.get('start_line', 0)}\n"
f"-------\n{search}\n"
f"=======\n{replace}\n"
f">>>>>>> REPLACE"
)
arguments = copy.deepcopy(arguments)
arguments["diff"] = "\n".join(diffs)
return tool_name, arguments
class UpdateTodoListParser(ExtraParserIF):
tool_name = "update_todo_list"
@staticmethod
def search_patterns(text: str) -> list[dict[str, str]]:
pattern = re.compile(r"^\[(?P<status>[^\]]+)\]\s*(?P<todo>.+?)$", re.MULTILINE)
results = []
for m in pattern.finditer(text):
results.append(
{
"todo": m.group("todo"),
"status": m.group("status"),
# "matched": m.group(0),
}
)
return results
@staticmethod
def get_schema(
doc: str, original_schema: JsonObj, system_prompt: str
) -> tuple[JsonObj | None, dict[str, str]]:
if original_schema["function"]["name"] != UpdateTodoListParser.tool_name:
return None, {}
for block_name in ("Usage Example:", "Usage:", "Example:"):
block = extract_block_after_label(doc, block_name)
params = UpdateTodoListParser.search_patterns(block)
if params:
break
else:
return None, {}
original_schema = copy.deepcopy(original_schema)
if todos := original_schema["function"]["parameters"]["properties"].get(
"todos", {}
):
todos["type"] = "array"
todos["items"] = {
"type": "object",
"properties": {
"todo": {
"type": "string",
"description": params[0]["todo"],
},
"status": {
"type": "string",
"description": params[0]["status"],
},
},
"required": ["todo", "status"],
}
required = original_schema["function"]["parameters"].get("required") or []
required.append("todos")
original_schema["function"]["parameters"]["required"] = required
return original_schema, {}
else:
return None, {}
@staticmethod
def postconvert_to_tool_call(
tool_name: str, arguments: JsonObj
) -> tuple[str, JsonObj]:
if tool_name != UpdateTodoListParser.tool_name:
return tool_name, arguments
todos = arguments.get("todos")
if not isinstance(todos, str):
# fallback
return tool_name, arguments
patterns = UpdateTodoListParser.search_patterns(todos)
if not patterns:
# fallback
return tool_name, arguments
arguments = copy.deepcopy(arguments)
arguments["todos"] = patterns
return tool_name, arguments
@staticmethod
def preconvert_to_xml(tool_name: str, arguments: JsonObj) -> tuple[str, JsonObj]:
if (
tool_name != UpdateTodoListParser.tool_name
or "todos" not in arguments
or isinstance(arguments["todos"], str)
):
return tool_name, arguments
elif not isinstance(arguments["todos"], list):
org_todos = [arguments["todos"]]
else:
org_todos = arguments["todos"]
todos = []
for todo in org_todos:
if isinstance(todo, dict):
status = (
re.match(
r"^(\[)?(?P<status>.*?)(\])?$", todo.get("status", " ")
).group("status")
or " "
)
todos.append(f"[{status}] {todo.get('todo', '').replace('\n', ' ')}")
arguments = copy.deepcopy(arguments)
arguments["todos"] = "\n".join(todos)
return tool_name, arguments
class UseMcpToolParser(ExtraParserIF):
tool_name = "use_mcp_tool"
@staticmethod
def search_patterns(text: str) -> list[dict[str, str]]:
raise NotImplementedError
@staticmethod
def get_schema(
doc: str, original_schema: JsonObj, system_prompt: str
) -> tuple[list[JsonObj] | None, dict[str, str]]:
if original_schema["function"]["name"] != UseMcpToolParser.tool_name:
return None, {}
mcp_doc = extract_mcp_section(system_prompt)
tool_docs, remove_pattern = parse_mcp_sections(mcp_doc)
try:
schemas = [build_mcp_tool_schema(tool_doc) for tool_doc in tool_docs]
if schemas:
return schemas, remove_pattern
except Exception:
pass
return None, {}
@staticmethod
def postconvert_to_tool_call(
tool_name: str, arguments: JsonObj
) -> tuple[str, JsonObj]:
if tool_name != UseMcpToolParser.tool_name:
return tool_name, arguments
server_name = arguments.get("server_name")
mcp_tool_name = arguments.get("tool_name")
inner_arguments = arguments.get("arguments")
if server_name is None or inner_arguments is None or mcp_tool_name is None:
# fallback
return tool_name, arguments
try:
inner_argument_obj = json.loads(inner_arguments.strip())
except Exception:
# fallback
return tool_name, arguments
return (
f"{UseMcpToolParser.tool_name}.{server_name}.{mcp_tool_name}",
inner_argument_obj,
)
@staticmethod
def preconvert_to_xml(tool_name: str, arguments: JsonObj) -> tuple[str, JsonObj]:
match = re.match(
rf"^{UseMcpToolParser.tool_name}\.(?P<server_name>[^\.]+)\.(?P<tool_name>.+)$",
tool_name,
)
if not match:
return tool_name, arguments
new_arguments = {
"server_name": match.group("server_name"),
"tool_name": match.group("tool_name"),
"arguments": json.dumps(arguments, ensure_ascii=False),
}
return UseMcpToolParser.tool_name, new_arguments