|
| 1 | +""" |
| 2 | +Mock LM client for testing without a real model. |
| 3 | +
|
| 4 | +Use this to test LMHandler, REPL integrations, or any code that needs a BaseLM |
| 5 | +without calling an external API. |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import Any, Callable |
| 9 | + |
| 10 | +from rlm.clients.base_lm import BaseLM |
| 11 | +from rlm.core.types import ModelUsageSummary, UsageSummary |
| 12 | + |
| 13 | + |
| 14 | +class MockLM(BaseLM): |
| 15 | + """ |
| 16 | + In-memory mock LM that implements BaseLM for testing. |
| 17 | +
|
| 18 | + - completion() / acompletion(): return a simple echo-style response by default, |
| 19 | + or use the optional response list/callable if provided. |
| 20 | + - get_usage_summary() / get_last_usage(): return fixed usage for tests. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + model_name: str = "mock-model", |
| 26 | + responses: list[str] | None = None, |
| 27 | + response_fn: Callable[[str | dict[str, Any]], str] | None = None, |
| 28 | + **kwargs: Any, |
| 29 | + ): |
| 30 | + super().__init__(model_name=model_name, **kwargs) |
| 31 | + self._responses = list(responses) if responses is not None else None |
| 32 | + self._response_fn = response_fn |
| 33 | + self._call_count = 0 |
| 34 | + self._default_usage = ModelUsageSummary( |
| 35 | + total_calls=0, total_input_tokens=0, total_output_tokens=0 |
| 36 | + ) |
| 37 | + |
| 38 | + def completion(self, prompt: str | dict[str, Any]) -> str: |
| 39 | + self._call_count += 1 |
| 40 | + if self._responses is not None: |
| 41 | + if not self._responses: |
| 42 | + raise IndexError("MockLM: no more responses in list") |
| 43 | + return self._responses.pop(0) |
| 44 | + if self._response_fn is not None: |
| 45 | + return self._response_fn(prompt) |
| 46 | + prompt_str = prompt if isinstance(prompt, str) else str(prompt)[:80] |
| 47 | + return f"Mock response to: {prompt_str}" |
| 48 | + |
| 49 | + async def acompletion(self, prompt: str | dict[str, Any]) -> str: |
| 50 | + return self.completion(prompt) |
| 51 | + |
| 52 | + def get_usage_summary(self) -> UsageSummary: |
| 53 | + return UsageSummary( |
| 54 | + model_usage_summaries={ |
| 55 | + self.model_name: ModelUsageSummary( |
| 56 | + total_calls=self._call_count, |
| 57 | + total_input_tokens=self._call_count * 10, |
| 58 | + total_output_tokens=self._call_count * 10, |
| 59 | + ) |
| 60 | + } |
| 61 | + ) |
| 62 | + |
| 63 | + def get_last_usage(self) -> ModelUsageSummary: |
| 64 | + return ModelUsageSummary( |
| 65 | + total_calls=1, |
| 66 | + total_input_tokens=10, |
| 67 | + total_output_tokens=10, |
| 68 | + ) |
0 commit comments