-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_chain_runner.py
More file actions
executable file
·53 lines (42 loc) · 1.38 KB
/
Copy pathpython_chain_runner.py
File metadata and controls
executable file
·53 lines (42 loc) · 1.38 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
#!/usr/bin/env python3
from __future__ import annotations
import importlib
import json
import os
import sys
from typing import Any, Callable
def main() -> int:
target = os.environ.get("REDLINE_PYTHON_RUNNER", "").strip()
if not target or ":" not in target:
print(
"Set REDLINE_PYTHON_RUNNER to 'module:function' before running this replay command.",
file=sys.stderr,
)
return 2
prompt = sys.stdin.read()
try:
runner = _load_runner(target)
result = runner(prompt)
except Exception as exc:
print(f"Python chain runner failed: {exc}", file=sys.stderr)
return 1
print(_stringify_result(result))
return 0
def _load_runner(target: str) -> Callable[[str], Any]:
module_name, function_name = target.split(":", 1)
module = importlib.import_module(module_name)
runner = getattr(module, function_name)
if not callable(runner):
raise TypeError(f"{target} is not callable")
return runner
def _stringify_result(result: Any) -> str:
content = getattr(result, "content", None)
if isinstance(content, str):
return content
if isinstance(result, str):
return result
if isinstance(result, (dict, list)):
return json.dumps(result, ensure_ascii=False, sort_keys=True)
return str(result)
if __name__ == "__main__":
raise SystemExit(main())