|
| 1 | +"""IPython REPL environment example. |
| 2 | +
|
| 3 | +Runs user code inside a real IPython session. Two kernel modes: |
| 4 | +
|
| 5 | +- ``in_process``: IPython InteractiveShell in the same Python process as RLM. |
| 6 | + Fast, zero-overhead subcalls, full Python object interop. |
| 7 | +- ``subprocess``: ipykernel subprocess managed via jupyter_client. Gives you |
| 8 | + real per-cell timeouts via kernel interrupt, and full isolation from the |
| 9 | + host namespace. |
| 10 | +
|
| 11 | +Setup: |
| 12 | + pip install 'rlms[ipython]' |
| 13 | + python -m examples.ipython_repl_example |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +from rlm.clients.base_lm import BaseLM |
| 19 | +from rlm.core.lm_handler import LMHandler |
| 20 | +from rlm.core.types import ModelUsageSummary, UsageSummary |
| 21 | +from rlm.environments.ipython_repl import IPythonREPL |
| 22 | + |
| 23 | + |
| 24 | +class MockLM(BaseLM): |
| 25 | + def __init__(self): |
| 26 | + super().__init__(model_name="mock") |
| 27 | + |
| 28 | + def completion(self, prompt): |
| 29 | + return f"Mock: {str(prompt)[:50]}" |
| 30 | + |
| 31 | + async def acompletion(self, prompt): |
| 32 | + return self.completion(prompt) |
| 33 | + |
| 34 | + def get_usage_summary(self): |
| 35 | + return UsageSummary({"mock": ModelUsageSummary(1, 10, 10)}) |
| 36 | + |
| 37 | + def get_last_usage(self): |
| 38 | + return self.get_usage_summary() |
| 39 | + |
| 40 | + |
| 41 | +def section(title: str) -> None: |
| 42 | + print("\n" + "=" * 60) |
| 43 | + print(title) |
| 44 | + print("=" * 60) |
| 45 | + |
| 46 | + |
| 47 | +def demo_in_process() -> None: |
| 48 | + section("[1] In-process IPython kernel") |
| 49 | + with IPythonREPL(kernel_mode="in_process") as repl: |
| 50 | + r = repl.execute_code("x = 40\ny = 2\nprint(x + y)") |
| 51 | + print(f" stdout: {r.stdout.strip()}") |
| 52 | + print(f" locals: x={repl.locals['x']}, y={repl.locals['y']}") |
| 53 | + |
| 54 | + # FINAL_VAR captures the final answer out-of-band. |
| 55 | + repl.execute_code('answer = "forty-two"') |
| 56 | + r = repl.execute_code('FINAL_VAR("answer")') |
| 57 | + print(f" FINAL_VAR → {r.final_answer}") |
| 58 | + |
| 59 | + |
| 60 | +def demo_subprocess() -> None: |
| 61 | + section("[2] Subprocess ipykernel — real timeouts") |
| 62 | + with IPythonREPL(kernel_mode="subprocess", cell_timeout=1.0) as repl: |
| 63 | + r = repl.execute_code("import sys; print(sys.executable)") |
| 64 | + print(f" kernel python: {r.stdout.strip()}") |
| 65 | + |
| 66 | + r = repl.execute_code("xs = [i*i for i in range(5)]; print(xs)") |
| 67 | + print(f" stdout: {r.stdout.strip()}") |
| 68 | + |
| 69 | + print(" -- running a 5s sleep with cell_timeout=1.0s --") |
| 70 | + r = repl.execute_code("import time; time.sleep(5); print('never')") |
| 71 | + print(f" elapsed: {r.execution_time:.2f}s") |
| 72 | + print(f" stderr: {r.stderr.strip()}") |
| 73 | + |
| 74 | + # Kernel survives the interrupt and still responds. |
| 75 | + r = repl.execute_code("print('kernel still alive')") |
| 76 | + print(f" follow-up: {r.stdout.strip()}") |
| 77 | + |
| 78 | + |
| 79 | +def demo_llm_query() -> None: |
| 80 | + section("[3] llm_query plumbing via LMHandler") |
| 81 | + with LMHandler(client=MockLM()) as handler: |
| 82 | + for mode in ("in_process", "subprocess"): |
| 83 | + print(f"\n -- kernel_mode={mode} --") |
| 84 | + with IPythonREPL( |
| 85 | + kernel_mode=mode, |
| 86 | + lm_handler_address=handler.address, |
| 87 | + ) as repl: |
| 88 | + r = repl.execute_code('r = llm_query("ping"); print(r)') |
| 89 | + print(f" response: {r.stdout.strip()}") |
| 90 | + |
| 91 | + r = repl.execute_code('print(llm_query_batched(["a", "b"]))') |
| 92 | + print(f" batched: {r.stdout.strip()}") |
| 93 | + |
| 94 | + |
| 95 | +def demo_recursion() -> None: |
| 96 | + section("[4] rlm_query — recursive RLM subcalls") |
| 97 | + # Stand-in for RLM._subcall: returns a canned reply for the demo. |
| 98 | + from rlm.core.types import RLMChatCompletion |
| 99 | + |
| 100 | + class _FakeSubcall: |
| 101 | + def __call__(self, prompt: str, model=None) -> RLMChatCompletion: |
| 102 | + return RLMChatCompletion( |
| 103 | + root_model="fake", |
| 104 | + prompt=prompt, |
| 105 | + response=f"child-answer[{prompt}]", |
| 106 | + usage_summary=UsageSummary({"fake": ModelUsageSummary(1, 0, 0)}), |
| 107 | + execution_time=0.0, |
| 108 | + ) |
| 109 | + |
| 110 | + subcall = _FakeSubcall() |
| 111 | + for mode in ("in_process", "subprocess"): |
| 112 | + print(f"\n -- kernel_mode={mode} --") |
| 113 | + with IPythonREPL(kernel_mode=mode, subcall_fn=subcall) as repl: |
| 114 | + r = repl.execute_code('print(rlm_query("deep-think-topic-A"))') |
| 115 | + print(f" single: {r.stdout.strip()}") |
| 116 | + r = repl.execute_code('print(rlm_query_batched(["t1","t2","t3"]))') |
| 117 | + print(f" batched: {r.stdout.strip()}") |
| 118 | + |
| 119 | + |
| 120 | +def main() -> None: |
| 121 | + demo_in_process() |
| 122 | + demo_subprocess() |
| 123 | + demo_llm_query() |
| 124 | + demo_recursion() |
| 125 | + print("\nDone.") |
| 126 | + |
| 127 | + |
| 128 | +if __name__ == "__main__": |
| 129 | + main() |
0 commit comments