Repository navigation
Expand file tree
/
Copy pathtest_lm.py
More file actions
211 lines (168 loc) · 7.39 KB
/
Copy pathtest_lm.py
File metadata and controls
211 lines (168 loc) · 7.39 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
# Copyright (c) 2025 Lakshya A Agrawal and the GEPA contributors
# https://github.com/gepa-ai/gepa
import uuid
from unittest.mock import MagicMock, patch
import httpx
import litellm
import openai
import pytest
from gepa.lm import LM, LMOutput
class TestLMInit:
"""Test LM constructor parameter handling."""
def test_defaults(self):
lm = LM("openai/gpt-4.1")
assert "temperature" not in lm.completion_kwargs
assert "max_tokens" not in lm.completion_kwargs
def test_custom_params(self):
lm = LM("openai/gpt-4.1", temperature=0.5, max_tokens=4096)
assert lm.completion_kwargs["temperature"] == 0.5
assert lm.completion_kwargs["max_tokens"] == 4096
def test_extra_kwargs_forwarded(self):
lm = LM("openai/gpt-4.1", top_p=0.9, stop=["\n"])
assert lm.completion_kwargs["top_p"] == 0.9
assert lm.completion_kwargs["stop"] == ["\n"]
def test_reasoning_model_no_special_treatment(self):
"""Reasoning models should NOT get special parameter handling."""
lm = LM("openai/gpt-5-mini", temperature=0.7, max_tokens=4096)
assert lm.completion_kwargs["temperature"] == 0.7
assert lm.completion_kwargs["max_tokens"] == 4096
assert "max_completion_tokens" not in lm.completion_kwargs
class TestLMCall:
"""Test LM __call__ method."""
@patch("litellm.completion")
def test_string_prompt(self, mock_completion):
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = "response text"
mock_response.choices[0].finish_reason = "stop"
mock_completion.return_value = mock_response
lm = LM("openai/gpt-4.1", temperature=0.5)
result = lm("hello")
assert result == "response text"
mock_completion.assert_called_once_with(
model="openai/gpt-4.1",
messages=[{"role": "user", "content": "hello"}],
num_retries=3,
drop_params=True,
temperature=0.5,
)
@patch("litellm.completion")
def test_messages_prompt(self, mock_completion):
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = "chat response"
mock_response.choices[0].finish_reason = "stop"
mock_completion.return_value = mock_response
lm = LM("openai/gpt-4.1")
messages = [{"role": "system", "content": "sys"}, {"role": "user", "content": "hi"}]
result = lm(messages)
assert result == "chat response"
mock_completion.assert_called_once_with(
model="openai/gpt-4.1",
messages=messages,
num_retries=3,
drop_params=True,
)
@patch("litellm.completion")
def test_truncation_warning(self, mock_completion, caplog):
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = "truncated"
mock_response.choices[0].finish_reason = "length"
mock_completion.return_value = mock_response
lm = LM("openai/gpt-4.1", max_tokens=100)
result = lm("hello")
assert result == "truncated"
assert isinstance(result, LMOutput)
assert result.finish_reason == "length"
assert result.strip().finish_reason == "length"
assert "truncated" in caplog.text.lower()
class TestLMBatchComplete:
"""Test LM batch_complete method."""
@patch("litellm.batch_completion")
def test_batch_complete(self, mock_batch):
resp1 = MagicMock()
resp1.choices = [MagicMock()]
resp1.choices[0].message.content = " answer1 "
resp1.choices[0].finish_reason = "stop"
resp2 = MagicMock()
resp2.choices = [MagicMock()]
resp2.choices[0].message.content = " answer2 "
resp2.choices[0].finish_reason = "stop"
mock_batch.return_value = [resp1, resp2]
lm = LM("openai/gpt-4.1")
msgs = [
[{"role": "user", "content": "q1"}],
[{"role": "user", "content": "q2"}],
]
results = lm.batch_complete(msgs, max_workers=5)
assert results == ["answer1", "answer2"]
assert [result.finish_reason for result in results] == ["stop", "stop"]
mock_batch.assert_called_once_with(
model="openai/gpt-4.1",
messages=msgs,
max_workers=5,
num_retries=3,
drop_params=True,
)
@patch("litellm.batch_completion")
def test_batch_complete_forwards_extra_kwargs(self, mock_batch):
"""Extra kwargs passed to batch_complete should be forwarded to litellm."""
resp = MagicMock()
resp.choices = [MagicMock()]
resp.choices[0].message.content = "ans"
resp.choices[0].finish_reason = "stop"
mock_batch.return_value = [resp]
lm = LM("openai/gpt-4.1", temperature=0.5)
lm.batch_complete(
[[{"role": "user", "content": "q"}]],
max_workers=3,
timeout=30,
api_base="https://custom.api",
)
call_kwargs = mock_batch.call_args[1]
assert call_kwargs["temperature"] == 0.5
assert call_kwargs["timeout"] == 30
assert call_kwargs["api_base"] == "https://custom.api"
@patch("litellm.batch_completion")
def test_batch_complete_kwargs_override_init(self, mock_batch):
"""Kwargs passed at call time should override init kwargs."""
resp = MagicMock()
resp.choices = [MagicMock()]
resp.choices[0].message.content = "ans"
resp.choices[0].finish_reason = "stop"
mock_batch.return_value = [resp]
lm = LM("openai/gpt-4.1", temperature=0.5)
lm.batch_complete(
[[{"role": "user", "content": "q"}]],
temperature=0.9, # override init value
)
call_kwargs = mock_batch.call_args[1]
assert call_kwargs["temperature"] == 0.9
class TestLMRepr:
def test_repr(self):
lm = LM("openai/gpt-4.1", temperature=0.5)
assert "gpt-4.1" in repr(lm)
assert "temperature=0.5" in repr(lm)
class TestLMConformsToProtocol:
"""Verify LM satisfies the LanguageModel protocol."""
def test_callable(self):
lm = LM("openai/gpt-4.1")
assert callable(lm)
assert hasattr(lm, "__call__")
class TestLMRetries:
"""Exercise the retries that ``num_retries`` asks of LiteLLM, without mocking LiteLLM."""
def test_failed_call_is_retried_and_raises_the_provider_error(self, monkeypatch):
requests = []
def not_found(request):
requests.append(request)
return httpx.Response(404, json={"error": {"message": "model not found", "type": "invalid_request_error"}})
monkeypatch.setattr(litellm, "client_session", httpx.Client(transport=httpx.MockTransport(not_found)))
# A fresh api_base keeps LiteLLM from reusing a client cached by another test.
lm = LM("openai/gpt-4.1", api_key="sk-test", api_base=f"http://{uuid.uuid4().hex}.invalid/v1")
# LiteLLM maps the provider's error to one of its own, which subclass OpenAI's.
with pytest.raises(openai.APIStatusError, match="model not found"):
lm("hello")
# The OpenAI SDK does not resend a 404, so the first attempt sends one request.
# LiteLLM then retries the call itself, which needs tenacity, with three more.
assert len(requests) == 4