-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
1950 lines (1660 loc) · 70.2 KB
/
tools.py
File metadata and controls
1950 lines (1660 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import asyncio
import json
import os
import queue
import re
import subprocess
import sys
import tempfile
import threading
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from typing import Any, Protocol, TextIO
import torch
from tensordict import lazy_stack, TensorDictBase
from torchrl._utils import logger as torchrl_logger
from torchrl.data.llm import History
from torchrl.envs import Transform
from typing_extensions import TypedDict
# --- Base Class for Tool Transforms ---
class ToolTransformBase(Transform):
"""Base class for tool transforms that parse and execute tools from LLM output.
This class handles all the common boilerplate for tool transforms:
- History extraction and validation
- Batch dimension flattening
- Result collection and padding
- History extension with tool results
Subclasses only need to implement:
- :meth:`_process_batch_item`: Extract and execute tools from one response
- :meth:`_format_result`: Format one tool result as string (optional)
Attributes:
use_step (bool): Whether to use _step() vs _call(). Defaults to True.
tool_role (str): Role name for results in history. Defaults to "tool".
Examples:
>>> class SimpleCalculator(ToolTransformBase):
... tool_role = "calculator"
...
... def _process_batch_item(self, content: str, index: int):
... # Extract math expressions and evaluate
... if "2+2" in content:
... return ["2+2=4"]
... return None
"""
use_step: bool = True # Use _step() vs _call()
tool_role: str = "tool" # Role name for results in history
def _validate_and_extract_history(
self, next_tensordict: TensorDictBase
) -> tuple[History, History]:
"""Validate environment and extract history.
Args:
next_tensordict: The tensordict containing history.
Returns:
tuple: (full_history, local_history) where local_history is the last message.
Raises:
RuntimeError: If parent env doesn't exist or isn't in history mode.
"""
# Check that base_env is in history mode
parent = self.parent
if parent is None:
raise RuntimeError(f"{self.__class__.__name__} must be used with a ChatEnv")
base_env = parent.base_env
if base_env.input_mode != "history":
raise RuntimeError(
f"{self.__class__.__name__} must be used with a ChatEnv in history mode"
)
# Get history and isolate last element (the LLM's response)
history = next_tensordict["history"].prompt
local_history = history[..., -1]
return history, local_history
def _process_batch_item(self, content: str, index: int) -> list[str] | None:
"""Process one item in the batch to extract and execute tools.
This is the main method subclasses must implement.
Args:
content: The text content from the LLM response.
index: The index of this item in the batch.
Returns:
list[str] or None: List of result strings for each tool executed,
or None if no tools were found/executed.
"""
raise NotImplementedError(
f"{self.__class__.__name__} must implement _process_batch_item()"
)
def _format_result(self, result: str) -> str:
"""Format a single result string.
Override this to customize result formatting. Default is identity.
Args:
result: Raw result string from tool execution.
Returns:
str: Formatted result string.
"""
return result
def _inject_results_to_history(
self,
history: History,
results: list[list[str] | None],
next_tensordict: TensorDictBase,
) -> TensorDictBase:
"""Inject tool results back into history with proper batching.
Args:
history: The full conversation history.
results: List of results per batch item (can contain None).
next_tensordict: The tensordict to update.
Returns:
TensorDictBase: Updated tensordict with results in history.
"""
# Convert string results to History objects
procs = []
for batch_results in results:
if batch_results is None or len(batch_results) == 0:
procs.append(None)
else:
formatted_results = [self._format_result(r) for r in batch_results]
procs.append(
[
History(role=self.tool_role, content=result)
for result in formatted_results
]
)
# If there are no tool responses, skip
if all(p is None for p in procs):
return next_tensordict
# Fill None entries with empty lists for consistent batching
if any(p is None for p in procs):
procs = [p if p is not None else [] for p in procs]
# Pad all results to same length (required for batching)
if len(procs) > 1 and not all(len(p) == len(procs[0]) for p in procs):
def fill_procs(proc: list[History], max_len: int) -> list[History]:
if len(proc) == max_len:
return proc
return proc + [History(role="<none>", content="")] * (
max_len - len(proc)
)
max_len = max(len(p) for p in procs)
procs = [fill_procs(p, max_len) for p in procs]
# Stack and extend history
procs = lazy_stack([lazy_stack(p) for p in procs])
history.extend(procs, dim=-1)
next_tensordict["history"].prompt = history
return next_tensordict
def _process_tensordict(self, next_tensordict: TensorDictBase) -> TensorDictBase:
"""Main processing logic for tool transforms.
Handles batch flattening, history extraction, tool processing, and result injection.
Args:
next_tensordict: The tensordict to process.
Returns:
TensorDictBase: Updated tensordict with tool results.
"""
# Flatten batch dimensions if needed
if next_tensordict.batch_dims > 1:
with next_tensordict.view(-1) as next_tensordict_flat:
next_tensordict_flat = self._process_tensordict(next_tensordict_flat)
return next_tensordict
# Extract and validate history
history, local_history = self._validate_and_extract_history(next_tensordict)
# Handle content as string or list
content = local_history.content
if isinstance(content, str):
content = [content]
# Process each batch item
results = []
for i, text in enumerate(content):
batch_results = self._process_batch_item(text, i)
results.append(batch_results)
# Inject results back into history
return self._inject_results_to_history(history, results, next_tensordict)
def _step(
self, tensordict: TensorDictBase, next_tensordict: TensorDictBase
) -> TensorDictBase:
"""Handle step with tool processing.
Args:
tensordict: Input tensordict.
next_tensordict: Output tensordict.
Returns:
TensorDictBase: Updated next_tensordict.
"""
if not self.use_step:
raise RuntimeError(
f"{self.__class__.__name__} uses _call(), not _step(). Set use_step=False."
)
return self._process_tensordict(next_tensordict)
def _call(self, next_tensordict: TensorDictBase) -> TensorDictBase:
"""Handle call with tool processing.
Args:
next_tensordict: The tensordict to process.
Returns:
TensorDictBase: Updated tensordict.
"""
if self.use_step:
raise RuntimeError(
f"{self.__class__.__name__} uses _step(), not _call(). Set use_step=True."
)
return self._process_tensordict(next_tensordict)
def _reset(
self, tensordict: TensorDictBase, tensordict_reset: TensorDictBase
) -> TensorDictBase:
"""Handle reset (no-op for base class).
Args:
tensordict (TensorDictBase): Input tensordict.
tensordict_reset (TensorDictBase): Reset tensordict.
Returns:
TensorDictBase: Unchanged reset tensordict.
"""
return tensordict_reset
# --- Tool Service Library: Pluggable Services & Parsers ---
class ToolService(Protocol):
"""Protocol for side-effecting service callable with structured IO.
A tool service is a callable that can be invoked with keyword arguments
and returns a dictionary of results. It has a name and input/output schemas.
Attributes:
name (str): The name of the tool service.
schema_in (dict[str, Any]): Input schema describing expected parameters.
schema_out (dict[str, Any]): Output schema describing returned data.
"""
name: str
schema_in: dict[str, Any]
schema_out: dict[str, Any]
def __call__(self, **kwargs) -> dict[str, Any]:
"""Execute the tool service.
Args:
**kwargs: Keyword arguments matching the input schema.
Returns:
dict[str, Any]: Results matching the output schema.
"""
...
class ToolRegistry:
"""Registry for managing available tool services.
This class maintains a collection of tool services that can be looked up
by name for execution.
Args:
services (Sequence[ToolService], optional): Initial services to register.
Defaults to an empty sequence.
Examples:
>>> class AddService:
... name = "add"
... schema_in = {"a": int, "b": int}
... schema_out = {"result": int}
... def __call__(self, a, b, **kwargs):
... return {"result": a + b}
>>> registry = ToolRegistry([AddService()])
>>> service = registry.get("add")
>>> result = service(a=1, b=2)
>>> print(result)
{"result": 3}
"""
def __init__(self, services: Sequence[ToolService] = ()):
self._svc: dict[str, ToolService] = {s.name: s for s in services}
def register(self, service: ToolService) -> None:
"""Register a new service.
Args:
service (ToolService): The service to register.
"""
self._svc[service.name] = service
def get(self, name: str) -> ToolService:
"""Retrieve a service by name.
Args:
name (str): The name of the service to retrieve.
Returns:
ToolService: The requested service.
Raises:
KeyError: If the service is not found.
"""
if name not in self._svc:
raise KeyError(f"Unknown tool: {name}")
return self._svc[name]
def __contains__(self, name: str) -> bool:
"""Check if a service is registered.
Args:
name (str): The name to check.
Returns:
bool: True if the service exists, False otherwise.
"""
return name in self._svc
@dataclass
class ToolCall:
"""Representation of a parsed tool call from LLM output.
Attributes:
tool (str): The name of the tool to call.
args (dict[str, Any]): Arguments to pass to the tool.
tag (str | None): Optional user-visible label or correlation ID.
"""
tool: str
args: dict[str, Any]
tag: str | None = None
class ParseResult(TypedDict):
"""Result of parsing an LLM response for tool calls.
This is a TypedDict-style class that contains:
text (str): The final message to user (post tool blocks removal).
calls (list[ToolCall]): Ordered tool calls as they appear.
meta (dict[str, Any]): Optional parser metadata.
"""
text: str
calls: list[ToolCall]
meta: dict[str, Any]
class LLMToolParser(Protocol):
"""Protocol for parsing LLM responses into ordered tool calls.
A tool parser takes the LLM's response (as string or structured data)
and extracts ordered tool calls, along with the cleaned user-facing text.
"""
def __call__(self, response: str | dict[str, Any]) -> ParseResult:
"""Parse an LLM response.
Args:
response (str | dict[str, Any]): The LLM's response to parse.
Returns:
ParseResult: Parsed result with text, calls, and metadata.
"""
...
class XMLBlockParser:
r"""Parser for XML-style tool blocks in LLM responses.
Parses tool calls in the format:
<tool name="tool_name" tag="optional_tag">{"arg": "value"}</tool>
Examples:
>>> parser = XMLBlockParser()
>>> response = '<tool name="search" tag="A">{"query": "torchrl"}</tool>\\nSome text.'
>>> result = parser(response)
>>> print(result["text"])
Some text.
>>> print(result["calls"][0].tool)
search
>>> print(result["calls"][0].args)
{"query": "torchrl"}
"""
_re = re.compile(
r'<tool\s+name="(?P<name>[^"]+)"(?:\s+tag="(?P<tag>[^"]+)")?\s*>\s*(?P<body>.*?)\s*</tool>',
re.DOTALL,
)
def __call__(self, response: str | dict[str, Any]) -> ParseResult:
"""Parse XML-style tool blocks from response.
Args:
response (str | dict[str, Any]): The response to parse.
Returns:
ParseResult: Parsed result with cleaned text and tool calls.
"""
text = response if isinstance(response, str) else response.get("text", "")
calls: list[ToolCall] = []
def repl(m: re.Match) -> str:
name = m.group("name")
tag = m.group("tag")
body = m.group("body")
try:
args = json.loads(body) if body.strip() else {}
except json.JSONDecodeError:
# If JSON parsing fails, pass the raw body as a "raw" argument
args = {"raw": body}
calls.append(ToolCall(tool=name, args=args, tag=tag))
return "" # Remove block from final user-visible message
cleaned = self._re.sub(repl, text).strip()
result = ParseResult()
result["text"] = cleaned
result["calls"] = calls
result["meta"] = {"count": len(calls)}
return result
class JSONCallParser:
"""Parser for JSON-style function-calling responses.
Expects responses in the format:
{
"message": "...",
"tools": [
{"tool": "search", "args": {"query": "..."}, "tag": "A"},
{"tool": "summarize", "args": {"text": "..."}}
]
}
Examples:
>>> parser = JSONCallParser()
>>> response = {
... "message": "Let me search for that.",
... "tools": [{"tool": "search", "args": {"query": "torchrl"}}]
... }
>>> result = parser(response)
>>> print(result["text"])
Let me search for that.
>>> print(result["calls"][0].tool)
search
"""
def __call__(self, response: str | dict[str, Any]) -> ParseResult:
"""Parse JSON-style function calls from response.
Args:
response (str | dict[str, Any]): The response to parse.
Returns:
ParseResult: Parsed result with message and tool calls.
"""
if isinstance(response, str):
try:
response = json.loads(response)
except json.JSONDecodeError:
# If it's not valid JSON, treat as plain text with no tools
result = ParseResult()
result["text"] = response
result["calls"] = []
result["meta"] = {"count": 0}
return result
tools_data = response.get("tools", [])
calls = [ToolCall(**c) for c in tools_data]
result = ParseResult()
result["text"] = response.get("message", "")
result["calls"] = calls
result["meta"] = {"count": len(calls)}
return result
class ExecuteToolsInOrder(ToolTransformBase):
"""A Transform that executes tools in the order they appear in LLM output.
This transform reads the LLM response, parses ordered tool blocks using a
pluggable parser, and executes tools via a ToolRegistry strictly in the
order they appear in the response (independent of transform stacking order).
The transform integrates naturally with TorchRL's LLM environments and can
read/write conversation history alongside other transforms.
Args:
registry (ToolRegistry): Registry containing available tool services.
parser (LLMToolParser): Parser for extracting tool calls from LLM output.
stop_on_error (bool, optional): Whether to stop execution on first error.
Defaults to ``False``.
pass_state_to_tools (bool, optional): Whether to pass TD state to tools.
Defaults to ``True``.
Examples:
>>> from torchrl.envs.llm import ChatEnv
>>> from torchrl.envs.transforms import TransformedEnv, Compose
>>> from torchrl.envs.llm.transforms import ExecuteToolsInOrder, ToolRegistry, XMLBlockParser
>>>
>>> # Define a simple service
>>> class WebSearch:
... name = "search"
... schema_in = {"query": str}
... schema_out = {"results": list}
... def __call__(self, query: str, **kwargs):
... return {"results": [{"title": "TorchRL docs", "url": "https://..."}]}
>>>
>>> # Create registry and parser
>>> registry = ToolRegistry([WebSearch()])
>>> parser = XMLBlockParser()
>>>
>>> # Create environment with transform
>>> env = ChatEnv(batch_size=(1,))
>>> env = TransformedEnv(
... env,
... ExecuteToolsInOrder(registry=registry, parser=parser)
... )
.. note::
This transform operates in the forward direction only; inverse is a no-op.
Tool execution order is determined by appearance in the LLM output,
not by the order of transforms in the Compose stack.
"""
use_step = True # Use _step() method
def __init__(
self,
registry: ToolRegistry,
parser: LLMToolParser,
stop_on_error: bool = False,
pass_state_to_tools: bool = True,
):
super().__init__()
self.registry = registry
self.parser = parser
self.stop_on_error = stop_on_error
self.pass_state_to_tools = pass_state_to_tools
self.tool_role = "tool"
def _process_batch_item(self, content: str, index: int) -> list[str] | None:
"""Process one batch item to extract and execute tools.
This is the main method required by ToolTransformBase.
Args:
content: The text content from the LLM response.
index: The index of this item in the batch.
Returns:
list[str] or None: List of result strings for each tool executed,
or None if no tools were found.
"""
# Parse the response for tool calls
parse: ParseResult = self.parser(content)
ordered_calls = parse["calls"]
if not ordered_calls:
return None
tool_outputs: list[dict[str, Any]] = []
# Execute tools IN ORDER OF APPEARANCE
for j, call in enumerate(ordered_calls):
try:
service = self.registry.get(call.tool)
kwargs = dict(call.args)
if self.pass_state_to_tools:
# Get tensordict from parent context if available
# For now, pass empty state - can be enhanced later
kwargs["_state"] = {}
out = service(**kwargs)
out["_tool"] = call.tool
out["_index"] = j
if call.tag:
out["_tag"] = call.tag
tool_outputs.append(out)
except Exception as e:
err = {"_tool": call.tool, "_index": j, "error": str(e)}
tool_outputs.append(err)
if self.stop_on_error:
break
# Format tool results as a single string
# Format tool results as a single string
if tool_outputs:
results_text = self._format_tool_results(tool_outputs)
return [results_text] if results_text else None
def _format_tool_results(self, tool_outputs: list[dict[str, Any]]) -> str:
"""Format tool execution results as text.
Args:
tool_outputs (list[dict[str, Any]]): List of tool execution results.
Returns:
str: Formatted text representation of results.
"""
if not tool_outputs:
return ""
lines = ["<tool_results>"]
for output in tool_outputs:
tool_name = output.pop("_tool", "unknown")
index = output.pop("_index", 0)
tag = output.pop("_tag", None)
if "error" in output:
lines.append(f"Tool {tool_name} (call {index + 1}) failed:")
lines.append(f" Error: {output['error']}")
else:
header = f"Tool {tool_name} (call {index + 1})"
if tag:
header += f" [tag: {tag}]"
header += " succeeded:"
lines.append(header)
lines.append(f" Result: {json.dumps(output, indent=2)}")
lines.append("</tool_results>")
return "\n".join(lines)
class PersistentPythonProcess:
"""A persistent Python process that can execute code blocks."""
def __init__(self, timeout: float = 10.0):
self.timeout = timeout
self._output_queue = queue.Queue()
self._error_queue = queue.Queue()
self._accumulated_errors = []
self._init_script = None
self.process = None # Initialize to None to avoid AttributeError in __del__
# Start the process
self._start_process()
def _start_process(self):
"""Start the Python process with the initialization script."""
# Create a temporary file for initialization
init_file = tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False)
self._init_script = init_file.name
# Write a script that creates a continuous execution environment
init_file.write(
"""
import sys
import traceback
def run_code(code_str):
# Create a dictionary to store the local variables
locals_dict = {}
try:
# First try to compile the code to catch syntax errors
compiled = compile(code_str, '<string>', 'exec')
# Execute the code with the locals dictionary
exec(compiled, globals(), locals_dict)
# Ensure output is flushed
sys.stdout.flush()
sys.stderr.flush()
return locals_dict
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
print("Traceback:", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
# Ensure error output is flushed immediately
sys.stdout.flush()
sys.stderr.flush()
return locals_dict
# Signal that we're ready to accept commands
print('---READY---')
sys.stdout.flush()
# Main loop to handle commands
while True:
try:
# Read a line that signals the start of a command
line = input()
if line.strip() == '---EXEC---':
# Read the code until we see the end marker
code_lines = []
while True:
line = input()
if line.strip() == '---END---':
break
code_lines.append(line)
# Execute the code
code_str = '\\n'.join(code_lines)
print('---START---') # Signal start of execution
sys.stdout.flush()
locals_dict = run_code(code_str)
# Update globals with new locals for persistence
globals().update(locals_dict)
print('---END---') # Signal end of execution
# Ensure all output is flushed
sys.stdout.flush()
sys.stderr.flush()
except (EOFError, KeyboardInterrupt):
break
except Exception as e:
print(f"Fatal error: {str(e)}", file=sys.stderr)
sys.stderr.flush()
break
"""
)
init_file.close()
# Start the process
try:
self.process = subprocess.Popen(
[sys.executable, "-u", self._init_script], # -u for unbuffered output
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
# Start output reading threads
self._stdout_thread = threading.Thread(
target=self._read_output,
args=(self.process.stdout, self._output_queue, "stdout"),
daemon=True,
)
self._stderr_thread = threading.Thread(
target=self._read_output,
args=(self.process.stderr, self._error_queue, "stderr"),
daemon=True,
)
self._stdout_thread.start()
self._stderr_thread.start()
# Wait for the process to be ready
ready = False
timeout = self.timeout
while timeout > 0 and not ready:
if self.process.poll() is not None:
raise RuntimeError(
f"Process failed to start: {self.process.returncode}"
)
try:
line = self._output_queue.get_nowait()
torchrl_logger.info(f"Output: {line}")
if "---READY---" in line:
ready = True
break
except queue.Empty:
timeout -= 0.1
time.sleep(0.1)
if not ready:
raise RuntimeError("Process failed to initialize within timeout")
except Exception:
# Clean up if process creation failed
if self._init_script:
try:
os.unlink(self._init_script)
self._init_script = None
except Exception:
pass
raise
def _read_output(self, pipe: TextIO, q: queue.Queue, pipe_name: str) -> None:
"""Read output from a pipe and put it in a queue."""
try:
for line in iter(pipe.readline, ""):
if pipe_name == "stderr":
self._accumulated_errors.append(line)
q.put(line)
except (ValueError, OSError) as e:
# Pipe has been closed
torchrl_logger.info(f"{pipe_name} pipe closed: {str(e)}")
finally:
try:
pipe.close()
except Exception:
pass
def execute(self, prompt: str) -> dict[str, Any]:
"""Execute code in the persistent process."""
if not self.process or self.process.poll() is not None:
# Get any accumulated errors
errors = "".join(self._accumulated_errors)
torchrl_logger.info(
f"Process state: poll={self.process.poll() if self.process else 'No process'}, accumulated errors: {errors}"
)
return {
"success": False,
"stdout": "",
"stderr": f"Process not initialized or terminated. Accumulated errors: {errors}",
"returncode": self.process.returncode if self.process else -1,
}
if not self.process.stdin:
return {
"success": False,
"stdout": "",
"stderr": "Process stdin not available",
"returncode": -1,
}
try:
# Clear accumulated errors before new execution
self._accumulated_errors.clear()
# Send the execution markers and code
try:
self.process.stdin.write("---EXEC---\n")
torchrl_logger.info(f"Writing to stdin: {prompt}")
self.process.stdin.write(f"{prompt}\n")
self.process.stdin.write("---END---\n")
self.process.stdin.flush()
except OSError as e:
torchrl_logger.info(f"Failed to write to stdin: {str(e)}")
return {
"success": False,
"stdout": "",
"stderr": f"Failed to write to process: {str(e)}",
"returncode": -1,
}
# Collect output until we see the end marker
output = []
error = []
start_found = False
timeout_val = self.timeout
while timeout_val > 0:
if self.process.poll() is not None:
# Process has terminated - get accumulated errors
errors = "".join(self._accumulated_errors)
torchrl_logger.info(
f"Process terminated with return code {self.process.returncode} - accumulated errors: {errors}"
)
error.append(
f"Process terminated with return code {self.process.returncode} - {errors}"
)
break
try:
# Check for errors first
try:
while True: # Drain all available error output
line = self._error_queue.get_nowait()
torchrl_logger.info(f"Error: {line}")
error.append(line)
except queue.Empty:
pass
# Then check for output
try:
line = self._output_queue.get_nowait()
torchrl_logger.info(f"Output: {line}")
if "---START---" in line:
start_found = True
continue
if "---END---" in line:
break
if start_found:
output.append(line)
except queue.Empty:
pass
if not start_found:
timeout_val -= 0.1
time.sleep(0.1)
except Exception as e:
return {
"success": False,
"stdout": "",
"stderr": f"Execution error: {str(e)}",
"returncode": -1,
}
if timeout_val <= 0:
# Kill the process and create a new one
self.cleanup()
self.__init__(self.timeout)
return {
"success": False,
"stdout": "",
"stderr": "Code execution timed out - process restarted",
"returncode": -1,
}
return {
"success": len(error) == 0,
"stdout": "".join(output),
"stderr": "".join(error),
"returncode": 0 if len(error) == 0 else 1,
}
except Exception as e:
# If we encounter any error, restart the process
self.cleanup()
self.__init__(self.timeout)
return {
"success": False,
"stdout": "",
"stderr": f"Execution error: {str(e)} - process restarted",
"returncode": -1,
}
def cleanup(self):
"""Clean up the persistent process."""
import signal
if self.process:
try:
self.process.send_signal(signal.SIGTERM)
self.process.wait(timeout=1.0)
except (subprocess.TimeoutExpired, OSError):
self.process.kill()
self.process = None
# Clean up the init script
if self._init_script:
try:
os.unlink(self._init_script)
self._init_script = None
except Exception:
pass
def __del__(self):
"""Ensure cleanup on deletion."""
self.cleanup()
class PythonExecutorService:
"""Ray actor that manages a pool of persistent Python interpreters.
This service allows multiple environments to share a pool of Python
interpreters, reducing resource usage and improving efficiency.
Args:
pool_size (int): Number of Python interpreter processes to maintain.
timeout (float): Timeout for code execution in seconds.
Examples:
>>> # Register the service
>>> from torchrl.services import get_services
>>> services = get_services(backend="ray")
>>> services.register(
... "python_executor",
... PythonExecutorService,
... pool_size=32,
... timeout=10.0,
... num_cpus=32,
... max_concurrency=32
... )
>>>
>>> # Use in transform
>>> env = env.append_transform(
... PythonInterpreter(services="ray")