-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinference-with-tools.py
More file actions
executable file
·1911 lines (1728 loc) · 70.2 KB
/
Copy pathinference-with-tools.py
File metadata and controls
executable file
·1911 lines (1728 loc) · 70.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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import ast
import base64
from datetime import datetime
import faulthandler
import json
import math
import os
import posixpath
import signal
import sys
import threading
import time
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import redirect_stdout
from dataclasses import dataclass, field
from io import BytesIO
from io import StringIO
from typing import Dict, List, Tuple
import requests
from PIL import Image
from benchmark import current_timestamp_utc, read_benchmark, write_benchmark, sort_benchmark
from execute import execute_solution
from llm_client import (
Endpoint,
ensure_model_available,
load_endpoint_file,
ollama_pull,
openai_api_check_exist,
openai_api_list,
)
from llm_model_test import complete_model_capabilities
from execute_clojure import syntax_check_clojure
from execute_java import syntax_check_java
from execute_python import syntax_check_python
from execute_rust import syntax_check_rust
faulthandler.enable(file=sys.stderr, all_threads=True)
if hasattr(signal, "SIGUSR1"):
faulthandler.register(signal.SIGUSR1, file=sys.stderr, all_threads=True)
if hasattr(signal, "SIGQUIT"):
faulthandler.register(signal.SIGQUIT, file=sys.stderr, all_threads=True)
LOG_CONTEXT = threading.local()
SYSTEM_PROMPT = (
"You are a coding agent operating in a virtual workspace. "
"You can only act by calling the provided tools. "
"Use this workflow: inspect the workspace, read files when needed, write or "
"rewrite complete files, run syntax checks, and continue until the program is ready. "
"When the task has multiple steps or you need to keep track of progress, consider "
"using update_plan to record a short plan and keep it current. "
"If it helps, you may use workspace files as temporary notes or a scratchpad via "
"write_file and read_file. "
"The final program can only be checked for syntax, not executed inside the tool loop. "
"Delivery is a blind one-shot submission of the final workspace file. "
"When the final program is ready, call deliver_code with the final workspace file path. "
"Do not end with plain text. Every assistant turn must contain a tool call. "
"If you need to explain progress, put that explanation in the assistant message that accompanies the tool call. "
"Return runnable source code with no markdown fences in delivered content."
)
TOOLS = [
{
"type": "function",
"function": {
"name": "list_files",
"description": (
"List the current virtual workspace files. Use this first when you need "
"to discover what files exist."
),
"parameters": {
"type": "object",
"properties": {},
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "read_file",
"description": (
"Read one virtual workspace file by relative path. Use this to inspect "
"existing code before editing."
),
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Virtual workspace-relative file path.",
"minLength": 1,
}
},
"required": ["path"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "write_file",
"description": (
"Create or fully replace one virtual workspace file. The content must be "
"the complete file contents, not a diff."
),
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Virtual workspace-relative file path.",
"minLength": 1,
},
"content": {
"type": "string",
"description": "Exact full file content.",
},
},
"required": ["path", "content"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "delete_file",
"description": "Delete one virtual workspace file by relative path.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Virtual workspace-relative file path.",
"minLength": 1,
}
},
"required": ["path"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "rename_file",
"description": (
"Rename or move one virtual workspace file from `source_path` to "
"`destination_path`."
),
"parameters": {
"type": "object",
"properties": {
"source_path": {
"type": "string",
"description": "Existing virtual workspace-relative file path.",
"minLength": 1,
},
"destination_path": {
"type": "string",
"description": "New virtual workspace-relative file path.",
"minLength": 1,
},
},
"required": ["source_path", "destination_path"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "syntax_check",
"description": (
"Check syntax for python, java, rust, or clojure using one virtual "
"workspace file path."
),
"parameters": {
"type": "object",
"properties": {
"language": {
"type": "string",
"description": "Language to check.",
"enum": ["python", "java", "rust", "clojure"],
},
"path": {
"type": "string",
"description": "Virtual workspace-relative file path.",
"minLength": 1,
},
},
"required": ["language", "path"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "calculator",
"description": (
"Evaluate a mathematical expression for planning or verification. "
"Use only for arithmetic, not for general code execution."
),
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Mathematical expression to evaluate.",
"minLength": 1,
}
},
"required": ["expression"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "update_plan",
"description": (
"Update the current task plan with a short explanation and a list of "
"steps. Keep the explanation and steps concise. Use this to track "
"progress across multiple tool calls."
),
"parameters": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "Optional short explanation of the current phase.",
},
"plan": {
"type": "array",
"description": "Ordered list of plan steps and their statuses.",
"minItems": 1,
"maxItems": 8,
"items": {
"type": "object",
"properties": {
"step": {
"type": "string",
"description": "Human-readable description of the step.",
"minLength": 1,
},
"status": {
"type": "string",
"description": "Current state of the step.",
"enum": ["pending", "in_progress", "completed"],
},
},
"required": ["step", "status"],
"additionalProperties": False,
},
},
},
"required": ["plan"],
"additionalProperties": False,
},
"strict": True,
},
},
{
"type": "function",
"function": {
"name": "deliver_code",
"description": (
"Finish the task and deliver the final runnable program using one virtual "
"workspace file path. Call this only when the code is complete."
),
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Virtual workspace-relative file path to deliver.",
"minLength": 1,
},
},
"required": ["path"],
"additionalProperties": False,
},
"strict": True,
},
},
]
MAX_TOOL_CALLS = 12
MAX_PRE_TOOL_STREAM_BYTES = 8192
def _sanitize_tool_schema(value):
if isinstance(value, dict):
sanitized = {}
for key, item in value.items():
# Some OpenAI-compatible servers accept basic tool schemas but hang or
# reject requests once strict JSON schema features are added.
if key in {"strict", "oneOf", "anyOf", "allOf"}:
continue
sanitized[key] = _sanitize_tool_schema(item)
return sanitized
if isinstance(value, list):
return [_sanitize_tool_schema(item) for item in value]
return value
def get_api_tools(tools: List[dict]) -> List[dict]:
return [_sanitize_tool_schema(tool) for tool in tools]
@dataclass
class State:
max_tool_calls: int = MAX_TOOL_CALLS
tool_call_counts: Dict[str, int] = field(default_factory=dict)
plan: List[Dict[str, str]] = field(default_factory=list)
plan_explanation: str = ""
@dataclass
class ToolResult:
exit_code: int
stdout: str
stderr: str
@dataclass
class DeliveryResult:
delivered: bool
content: str = ""
path: str = ""
@dataclass
class VirtualFileSystem:
files: Dict[str, str] = field(default_factory=dict)
def list_files(self) -> List[str]:
return sorted(self.files)
def read_file(self, path: str) -> str:
return self.files[path]
def write_file(self, path: str, content: str) -> None:
self.files[path] = content
def delete_file(self, path: str) -> None:
del self.files[path]
def rename_file(self, source_path: str, destination_path: str) -> None:
self.files[destination_path] = self.files.pop(source_path)
def read_template(template_path):
with open(template_path, "r", encoding="utf-8") as file:
return file.read()
def get_extension(language):
if language == "java":
return "java"
if language == "rust":
return "rs"
if language == "python":
return "py"
if language == "clojure":
return "clj"
raise Exception(f"Unsupported language: {language}")
def get_tooling_series_name(language: str, max_problem_number: int) -> str:
return f"{language}-{max_problem_number}-tool-test"
def get_tooling_score_name(language: str, max_problem_number: int) -> str:
return f"{language}-{max_problem_number}-tool"
def get_tooling_batch_bounds(args) -> Tuple[int, int, int]:
if args.n100:
return 100, 1, 100
if args.n200:
return 200, 101, 200
if args.n300:
return 300, 201, 300
if args.n400:
return 400, 301, 400
if args.nall:
return 9999, 1, 9999
return 200, 101, 200
def get_recorded_tooling_vector(store_name: str, language: str, max_problem_number: int) -> str:
benchmark = read_benchmark()
entry = benchmark.get(store_name, {})
return entry.get(get_tooling_series_name(language, max_problem_number), "")
def tooling_result_recorded(test_vector: str, problem_number: str, problem_start: int, problem_end: int) -> bool:
index = int(problem_number) - problem_start
vector_length = problem_end - problem_start + 1
if not (problem_start <= int(problem_number) <= problem_end):
return False
if len(test_vector) < vector_length:
return False
return 0 <= index < len(test_vector) and test_vector[index] in {"0", "1"}
def update_tooling_score(
store_name: str,
language: str,
max_problem_number: int,
problem_start: int,
problem_end: int,
benchmark_lock: threading.Lock,
) -> None:
with benchmark_lock:
benchmark = read_benchmark()
entry = benchmark.get(store_name, {})
tooling_series_name = get_tooling_series_name(language, max_problem_number)
vector_length = problem_end - problem_start + 1
test_vector = entry.get(tooling_series_name, "")
if len(test_vector) < vector_length:
test_vector = test_vector + ("?" * (vector_length - len(test_vector)))
current_vector = test_vector[:vector_length]
if not os.path.exists("solutions.json"):
return
with open("solutions.json", "r", encoding="utf-8") as json_file:
expected_solutions = json.load(json_file)
candidate_points = 0.0
total_count = 0
for offset, problem_number_int in enumerate(range(problem_start, problem_end + 1)):
marker = current_vector[offset]
if marker not in {"0", "1"}:
continue
problem_number = f"{problem_number_int:04d}"
expected = expected_solutions.get(problem_number)
if not expected:
continue
total_count += 1
if marker == "1":
candidate_points += expected.get("points", 0.0)
if total_count == 0:
return
entry[get_tooling_score_name(language, max_problem_number)] = round(candidate_points / total_count, 2)
entry["timestamp"] = current_timestamp_utc()
benchmark[store_name] = entry
write_benchmark(sort_benchmark(benchmark))
def record_tooling_result(
store_name: str,
language: str,
problem_number: str,
output: str,
correct: bool,
max_problem_number: int,
problem_start: int,
problem_end: int,
solutions_json_path: str,
benchmark_lock: threading.Lock,
) -> None:
t0 = time.monotonic()
with benchmark_lock:
solutions = {}
if os.path.exists(solutions_json_path):
with open(solutions_json_path, "r", encoding="utf-8") as json_file:
try:
solutions = json.load(json_file)
except json.JSONDecodeError:
solutions = {}
solutions[problem_number] = output
with open(solutions_json_path, "w", encoding="utf-8") as json_file:
json.dump(solutions, json_file, indent=4)
benchmark = read_benchmark()
entry = benchmark.get(store_name, {})
tooling_series_name = get_tooling_series_name(language, max_problem_number)
vector_length = problem_end - problem_start + 1
test_vector = list(entry.get(tooling_series_name, "?" * vector_length))
if len(test_vector) < vector_length:
test_vector.extend(["?"] * (vector_length - len(test_vector)))
index = int(problem_number) - problem_start
if 0 <= index < vector_length:
test_vector[index] = "1" if correct else "0"
entry[tooling_series_name] = "".join(test_vector)
entry["timestamp"] = current_timestamp_utc()
benchmark[store_name] = entry
write_benchmark(sort_benchmark(benchmark))
update_tooling_score(
store_name,
language,
max_problem_number,
problem_start,
problem_end,
benchmark_lock,
)
log(
f"[{problem_number}] Recorded benchmark result in {time.monotonic() - t0:.2f}s: "
f"key={get_tooling_series_name(language, max_problem_number)} value={'1' if correct else '0'}"
)
def log(message: str) -> None:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
endpoint = getattr(LOG_CONTEXT, "endpoint", "")
endpoint_text = f" endpoint={endpoint}" if endpoint else ""
print(f"[tool-inference {timestamp}{endpoint_text}] {message}", flush=True)
def set_log_endpoint(endpoint: str) -> None:
LOG_CONTEXT.endpoint = endpoint
def preview_text(text: str, limit: int = 160) -> str:
compact = " ".join(text.split())
if len(compact) <= limit:
return compact
return compact[: limit - 3] + "..."
def byte_size(text: str) -> int:
if not text:
return 0
return len(text.encode("utf-8"))
def summarize_tool_args(tool_name: str, parsed_args: dict) -> str:
if tool_name in {"read_file", "write_file", "delete_file", "deliver_code"}:
path = parsed_args.get("path")
if path:
return f"path={path}"
if tool_name == "rename_file":
source_path = parsed_args.get("source_path")
destination_path = parsed_args.get("destination_path")
if source_path and destination_path:
return f"source_path={source_path} destination_path={destination_path}"
if tool_name == "syntax_check":
language = parsed_args.get("language", "?")
path = parsed_args.get("path")
return f"language={language} path={path}" if path else f"language={language}"
if tool_name == "calculator":
expr = parsed_args.get("expression", "")
return f"expression={preview_text(expr, 80)}"
return ""
def summarize_response(response_json: dict) -> str:
message = response_json.get("choices", [{}])[0].get("message", {})
chunk = extract_text_content(message.get("content"))
tool_calls = message.get("tool_calls") or []
usage = response_json.get("usage", {}) if isinstance(response_json.get("usage", {}), dict) else {}
prompt_tokens = usage.get("prompt_tokens")
completion_tokens = usage.get("completion_tokens", usage.get("output_tokens"))
usage_summary = []
if isinstance(prompt_tokens, int):
usage_summary.append(f"prompt_tokens={prompt_tokens}")
if isinstance(completion_tokens, int):
usage_summary.append(f"completion_tokens={completion_tokens}")
usage_text = f"{', '.join(usage_summary)}; " if usage_summary else ""
if tool_calls:
first_call = tool_calls[0]
function = first_call.get("function", {})
tool_name = function.get("name") or first_call.get("name") or "unknown_tool"
raw_args = function.get("arguments", "")
try:
parsed_args = json.loads(raw_args) if raw_args else {}
except json.JSONDecodeError:
parsed_args = {}
detail = summarize_tool_args(tool_name, parsed_args)
arg_bytes = byte_size(raw_args)
content_bytes = byte_size(chunk)
if chunk and detail:
return (
f"{usage_text}model plans to {tool_name} ({detail}); "
f"arg_bytes={arg_bytes}; content_bytes={content_bytes}; "
f"note={preview_text(chunk, 120)}"
)
if detail:
return f"{usage_text}model plans to {tool_name} ({detail}); arg_bytes={arg_bytes}"
if chunk:
return f"{usage_text}model plans to {tool_name}; arg_bytes={arg_bytes}; content_bytes={content_bytes}; note={preview_text(chunk, 120)}"
return f"{usage_text}model plans to {tool_name}; arg_bytes={arg_bytes}"
if chunk:
return f"{usage_text}model replied without a tool call; content_bytes={byte_size(chunk)}; text={preview_text(chunk, 120)}"
return f"{usage_text}model returned neither tool call nor text"
def normalize_virtual_path(path: str) -> str:
if not path:
raise ValueError("Path must not be empty.")
normalized = posixpath.normpath(path.replace("\\", "/"))
if normalized in (".", ""):
raise ValueError("Path must not be empty.")
if normalized.startswith("../") or normalized == ".." or normalized.startswith("/"):
raise ValueError("Path must be workspace-relative.")
return normalized
def run_calculator(expression: str) -> ToolResult:
if not expression or not expression.strip():
return ToolResult(exit_code=1, stdout="", stderr="expression must not be empty.")
try:
parsed = ast.parse(expression, mode="eval")
except SyntaxError as exc:
return ToolResult(exit_code=1, stdout="", stderr=f"Invalid expression: {exc.msg}")
allowed_names = {name: getattr(math, name) for name in dir(math) if not name.startswith("_")}
allowed_names.update(
{
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"pow": pow,
}
)
allowed_nodes = (
ast.Expression,
ast.BinOp,
ast.UnaryOp,
ast.Call,
ast.Name,
ast.Load,
ast.Constant,
ast.Tuple,
ast.List,
ast.Add,
ast.Sub,
ast.Mult,
ast.Div,
ast.FloorDiv,
ast.Mod,
ast.Pow,
ast.USub,
ast.UAdd,
)
for node in ast.walk(parsed):
if not isinstance(node, allowed_nodes):
return ToolResult(
exit_code=1,
stdout="",
stderr=f"Unsupported expression element: {type(node).__name__}",
)
if isinstance(node, ast.Call):
if not isinstance(node.func, ast.Name) or node.func.id not in allowed_names:
return ToolResult(exit_code=1, stdout="", stderr="Unsupported function call.")
if isinstance(node, ast.Name) and node.id not in allowed_names:
return ToolResult(exit_code=1, stdout="", stderr=f"Unknown name: {node.id}")
try:
value = eval(compile(parsed, "<calculator>", "eval"), {"__builtins__": {}}, allowed_names)
except Exception as exc:
return ToolResult(exit_code=1, stdout="", stderr=f"Calculation error: {exc}")
return ToolResult(exit_code=0, stdout=str(value), stderr="")
def run_syntax_check(vfs: VirtualFileSystem, parsed_args: dict) -> ToolResult:
language = (parsed_args.get("language") or "").strip().lower()
if language not in {"python", "java", "rust", "clojure"}:
return ToolResult(
exit_code=1,
stdout="",
stderr="language must be one of: python, java, rust, clojure.",
)
try:
filename = normalize_virtual_path(parsed_args.get("path", ""))
except ValueError as exc:
return ToolResult(exit_code=1, stdout="", stderr=str(exc))
if filename not in vfs.files:
return ToolResult(exit_code=1, stdout="", stderr=f"File not found: {filename}")
code = vfs.read_file(filename)
if language == "python":
exit_code, stdout, stderr = syntax_check_python(code, filename)
return ToolResult(exit_code=exit_code, stdout=stdout, stderr=stderr)
if language == "java":
exit_code, stdout, stderr = syntax_check_java(code)
return ToolResult(exit_code=exit_code, stdout=stdout, stderr=stderr)
if language == "rust":
exit_code, stdout, stderr = syntax_check_rust(code)
return ToolResult(exit_code=exit_code, stdout=stdout, stderr=stderr)
exit_code, stdout, stderr = syntax_check_clojure(code)
return ToolResult(exit_code=exit_code, stdout=stdout, stderr=stderr)
def extract_text_content(content) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text", ""))
return "".join(parts)
return ""
def extract_response_fields(response_json: dict) -> Tuple[str, str, str, str]:
message = response_json.get("choices", [{}])[0].get("message", {})
chunk = extract_text_content(message.get("content"))
tool_calls = message.get("tool_calls") or []
if not tool_calls:
return chunk, "", "", ""
first_call = tool_calls[0]
function = first_call.get("function", {})
tool_name = function.get("name") or first_call.get("name") or ""
tool_id = first_call.get("id", "")
raw_args = function.get("arguments", "")
return chunk, tool_name, tool_id, raw_args
def raise_for_status_with_body(response, context: str) -> None:
try:
response.raise_for_status()
except requests.HTTPError as exc:
body = ""
try:
body = response.text or ""
except Exception:
body = ""
body_preview = preview_text(body, 800) if body else "<empty body>"
log(
f"{context}: HTTP {response.status_code} from backend; "
f"response_body={body_preview}"
)
raise exc
def _extract_delta_text(delta_value) -> str:
if isinstance(delta_value, str):
return delta_value
if isinstance(delta_value, list):
parts = []
for item in delta_value:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
text = item.get("text")
if isinstance(text, str):
parts.append(text)
return "".join(parts)
if isinstance(delta_value, dict):
text = delta_value.get("text")
if isinstance(text, str):
return text
return ""
def consume_streaming_tool_response(response, problem_number: str, turn: int) -> dict:
usage = {}
content_parts: List[str] = []
reasoning_parts: List[str] = []
tool_calls_by_index: Dict[int, dict] = {}
args_bytes_logged: Dict[int, int] = {}
current_stream_kind = ""
pre_tool_text_bytes = 0
pre_tool_reasoning_bytes = 0
def ensure_stream_prefix(stream_kind: str) -> None:
nonlocal current_stream_kind
if current_stream_kind == stream_kind:
return
if current_stream_kind:
sys.stdout.write("\n")
current_stream_kind = stream_kind
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
endpoint = getattr(LOG_CONTEXT, "endpoint", "")
endpoint_text = f" endpoint={endpoint}" if endpoint else ""
sys.stdout.write(
f"[tool-inference {timestamp}{endpoint_text}] "
f"[{problem_number}] Turn {turn}: stream {stream_kind}: "
)
sys.stdout.flush()
def close_stream_prefix() -> None:
nonlocal current_stream_kind
if current_stream_kind:
sys.stdout.write("\n")
sys.stdout.flush()
current_stream_kind = ""
for raw_line in response.iter_lines(decode_unicode=True):
if not raw_line:
continue
if not raw_line.startswith("data: "):
continue
payload_line = raw_line[len("data: "):].strip()
if payload_line == "[DONE]":
close_stream_prefix()
break
try:
event = json.loads(payload_line)
except json.JSONDecodeError:
close_stream_prefix()
log(f"[{problem_number}] Turn {turn}: stream event was not valid JSON.")
continue
event_usage = event.get("usage")
if isinstance(event_usage, dict):
usage = event_usage
choices = event.get("choices", [])
if not choices:
continue
delta = choices[0].get("delta", {})
text_delta = _extract_delta_text(delta.get("content"))
if text_delta:
content_parts.append(text_delta)
ensure_stream_prefix("text")
sys.stdout.write(text_delta)
sys.stdout.flush()
if not tool_calls_by_index:
pre_tool_text_bytes += len(text_delta.encode("utf-8"))
if pre_tool_text_bytes > MAX_PRE_TOOL_STREAM_BYTES:
close_stream_prefix()
raise RuntimeError(
f"Model exceeded pre-tool text budget of {MAX_PRE_TOOL_STREAM_BYTES} bytes "
f"without calling a tool on turn {turn}."
)
reasoning_delta = _extract_delta_text(delta.get("reasoning"))
if reasoning_delta:
reasoning_parts.append(reasoning_delta)
ensure_stream_prefix("reasoning")
sys.stdout.write(reasoning_delta)
sys.stdout.flush()
if not tool_calls_by_index:
pre_tool_reasoning_bytes += len(reasoning_delta.encode("utf-8"))
if pre_tool_reasoning_bytes > MAX_PRE_TOOL_STREAM_BYTES:
close_stream_prefix()
raise RuntimeError(
f"Model exceeded pre-tool reasoning budget of {MAX_PRE_TOOL_STREAM_BYTES} bytes "
f"without calling a tool on turn {turn}."
)
for tool_call in delta.get("tool_calls") or []:
close_stream_prefix()
index = tool_call.get("index", 0)
current = tool_calls_by_index.setdefault(
index,
{
"id": "",
"type": "function",
"function": {"name": "", "arguments": ""},
},
)
if tool_call.get("id"):
current["id"] = tool_call["id"]
if tool_call.get("type"):
current["type"] = tool_call["type"]
function = tool_call.get("function", {})
if function.get("name"):
current["function"]["name"] += function["name"]
log(
f"[{problem_number}] Turn {turn}: stream tool name[{index}]="
f"{current['function']['name']}"
)
if function.get("arguments"):
current["function"]["arguments"] += function["arguments"]
args_text = current["function"]["arguments"]
args_bytes = len(args_text.encode("utf-8"))
previous_bytes = args_bytes_logged.get(index, 0)
if args_bytes > previous_bytes:
args_bytes_logged[index] = args_bytes
log(
f"[{problem_number}] Turn {turn}: stream tool args[{index}] "
f"total {args_bytes}B: {preview_text(args_text, 120)}"
)
close_stream_prefix()
tool_calls = [tool_calls_by_index[index] for index in sorted(tool_calls_by_index)]
message = {}
if content_parts:
message["content"] = "".join(content_parts)
else:
message["content"] = ""
if reasoning_parts:
message["reasoning"] = "".join(reasoning_parts)
if tool_calls:
message["tool_calls"] = tool_calls
return {
"choices": [{"message": message}],
"usage": usage,
}
def tool_result_json(tool_name: str, result: ToolResult) -> str:
return json.dumps(
{
"tool": tool_name,
"exit_code": result.exit_code,
"stdout": result.stdout,
"stderr": result.stderr,
}
)
def log_plan_update(problem_number: str, parsed_args: dict, label: str = "Plan updated") -> None:
plan = parsed_args.get("plan") or []
explanation = parsed_args.get("explanation", "")
lines = [f"[{problem_number}] {label}:"]
if explanation:
lines.append(f"[{problem_number}] explanation: {preview_text(explanation, 200)}")
for index, item in enumerate(plan, start=1):
if not isinstance(item, dict):
continue
step = item.get("step", "")
status = item.get("status", "?")
lines.append(f"[{problem_number}] {index}. [{status}] {preview_text(step, 200)}")
if len(lines) == 1:
lines.append(f"[{problem_number}] empty plan")
for line in lines:
log(line)
def get_visible_tools(state: State) -> List[dict]:
visible_tools = []
for tool in TOOLS:
tool_name = tool["function"]["name"]
if state.tool_call_counts.get(tool_name, 0) < state.max_tool_calls:
visible_tools.append(tool)
return visible_tools
def run_update_plan(state: State, parsed_args: dict) -> ToolResult:
plan = parsed_args.get("plan")
if not isinstance(plan, list):
return ToolResult(exit_code=1, stdout="", stderr="plan must be an array.")
if not plan:
return ToolResult(exit_code=1, stdout="", stderr="plan must contain at least one step.")
if len(plan) > 8:
return ToolResult(exit_code=1, stdout="", stderr="plan must contain at most 8 steps.")
normalized_plan: List[Dict[str, str]] = []
in_progress_count = 0
completed_count = 0
warnings: List[str] = []
seen_steps = set()
for index, item in enumerate(plan):
if not isinstance(item, dict):
return ToolResult(
exit_code=1,
stdout="",
stderr=f"plan[{index}] must be an object.",
)
step = item.get("step")
status = item.get("status")
if not isinstance(step, str) or not step.strip():
return ToolResult(
exit_code=1,
stdout="",
stderr=f"plan[{index}].step must be a non-empty string.",
)
if status not in {"pending", "in_progress", "completed"}:
return ToolResult(
exit_code=1,
stdout="",
stderr=(
f"plan[{index}].status must be one of: pending, in_progress, completed."
),
)
if status == "in_progress":
in_progress_count += 1
if status == "completed":
completed_count += 1
normalized_step = step.strip()
if normalized_step.lower() in seen_steps:
warnings.append(f"Duplicate step text: {normalized_step}")
seen_steps.add(normalized_step.lower())