Skip to content

Commit 3cd8c9c

Browse files
committed
Improve OpenAI client instantiation and test mocks
Pass http_client explicitly to OpenAI client in server.py for consistent configuration. Update test_conversation_logging_approaches to use set_global_logger instead of directly assigning the logger. Enhance MockOpenAIClient in test_mars_parallel to generate context-aware mock responses based on problem type, and improve EnhancedMockClient to match problem keywords for more realistic test outputs.
1 parent b670e61 commit 3cd8c9c

3 files changed

Lines changed: 39 additions & 22 deletions

File tree

optillm/server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,10 @@ def get_config():
9494
API_KEY = os.environ.get("OPENAI_API_KEY")
9595
base_url = server_config['base_url']
9696
if base_url != "":
97-
default_client = OpenAI(api_key=API_KEY, base_url=base_url)
97+
default_client = OpenAI(api_key=API_KEY, base_url=base_url, http_client=http_client)
9898
logger.info(f"Created OpenAI client with base_url: {base_url}")
9999
else:
100-
default_client = OpenAI(api_key=API_KEY)
100+
default_client = OpenAI(api_key=API_KEY, http_client=http_client)
101101
logger.info("Created OpenAI client without base_url")
102102
elif os.environ.get("AZURE_OPENAI_API_KEY"):
103103
API_KEY = os.environ.get("AZURE_OPENAI_API_KEY")

tests/test_conversation_logging_approaches.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,24 +91,25 @@ def setUp(self):
9191
self.temp_dir = tempfile.mkdtemp()
9292
self.log_dir = Path(self.temp_dir) / "conversations"
9393
self.logger = ConversationLogger(self.log_dir, enabled=True)
94-
95-
# Mock optillm.conversation_logger
96-
optillm.conversation_logger = self.logger
97-
94+
95+
# Set the global logger instance for approach modules to use
96+
set_global_logger(self.logger)
97+
9898
# Common test parameters
9999
self.system_prompt = "You are a helpful assistant."
100100
self.initial_query = "What is 2 + 2?"
101101
self.model = "test-model"
102102
self.request_id = "test-request-123"
103-
103+
104104
# Create mock client
105105
self.client = MockOpenAIClient()
106-
106+
107107
def tearDown(self):
108108
"""Clean up test environment"""
109109
import shutil
110110
shutil.rmtree(self.temp_dir, ignore_errors=True)
111-
optillm.conversation_logger = None
111+
# Clear the global logger
112+
set_global_logger(None)
112113

113114
def test_multi_call_approaches_logging(self):
114115
"""Test BON, MCTS, and RTO approaches log API calls correctly"""

tests/test_mars_parallel.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@ def chat_completions_create(self, **kwargs):
4242

4343
call_count = self.call_count # Capture for closure
4444

45+
# Check the problem content to provide appropriate mock response
46+
messages = kwargs.get('messages', [])
47+
problem_text = ' '.join(m.get('content', '') for m in messages if isinstance(m, dict)).lower()
48+
49+
# Generate response with expected features based on problem type
50+
if 'polynomial' in problem_text or 'algebra' in problem_text:
51+
content = f'Using systematic analysis and case-by-case examination, solution {call_count}. The answer is 42.'
52+
elif 'distribute' in problem_text or 'combinatorics' in problem_text:
53+
content = f'Using stars and bars method with constraint analysis, solution {call_count}. The answer is 42.'
54+
elif 'triangle' in problem_text or 'geometry' in problem_text:
55+
content = f'Applying geometric inequality and area analysis, solution {call_count}. The answer is 42.'
56+
else:
57+
content = f'Mock mathematical solution {call_count}. The answer is 42.'
58+
4559
class MockUsage:
4660
def __init__(self, reasoning_tokens):
4761
self.completion_tokens_details = type('obj', (), {
@@ -50,17 +64,17 @@ def __init__(self, reasoning_tokens):
5064
self.total_tokens = reasoning_tokens + 100
5165

5266
class MockChoice:
53-
def __init__(self):
67+
def __init__(self, response_content):
5468
self.message = type('obj', (), {
55-
'content': f'Mock mathematical solution {call_count}. The answer is 42.'
69+
'content': response_content
5670
})()
5771

5872
class MockResponse:
59-
def __init__(self, reasoning_tokens):
60-
self.choices = [MockChoice()]
73+
def __init__(self, reasoning_tokens, response_content):
74+
self.choices = [MockChoice(response_content)]
6175
self.usage = MockUsage(reasoning_tokens)
6276

63-
return MockResponse(self.reasoning_tokens)
77+
return MockResponse(self.reasoning_tokens, content)
6478

6579
@property
6680
def chat(self):
@@ -292,22 +306,24 @@ def test_mars_hard_problems(self):
292306
class EnhancedMockClient(MockOpenAIClient):
293307
def __init__(self):
294308
super().__init__(response_delay=0.1, reasoning_tokens=3000)
309+
# Map problem keywords to responses that contain expected features
295310
self.problem_responses = {
296-
"Advanced Algebra": "This requires systematic case analysis. Let me examine small values systematically. After checking cases x,y,z < 100, the equation x³ + y³ = z³ - 1 has solutions like (x,y,z) = (1,1,1) since 1³ + 1³ = 2 = 2³ - 6... Actually, let me recalculate: 1³ + 1³ = 2, and z³ - 1 = 2 means z³ = 3, so z ≈ 1.44. Let me check (2,2,2): 8 + 8 = 16 = 8 - 1 = 7? No. This is a difficult Diophantine equation requiring advanced techniques.",
297-
"Number Theory": "I'll prove this by contradiction using Euclid's method. Assume there are only finitely many primes of the form 4k+3: p₁, p₂, ..., pₙ. Consider N = 4(p₁p₂...pₙ) + 3. Since N ≡ 3 (mod 4), at least one prime factor of N must be ≡ 3 (mod 4). But N is not divisible by any of p₁, p₂, ..., pₙ, so there must be another prime of the form 4k+3, contradicting our assumption. Therefore, there are infinitely many such primes.",
298-
"Combinatorics": "This is a stars and bars problem with constraints. We need to distribute 20 balls into 5 boxes with each box having at least 2 balls. First, place 2 balls in each box (using 10 balls). Now we need to distribute the remaining 10 balls into 5 boxes with no constraints. Using stars and bars: C(10+5-1, 5-1) = C(14,4) = 1001 ways.",
299-
"Geometry": "This is a form of Weitzenböck's inequality. We can prove this using the relationship between area and sides. For a triangle with area S and sides a,b,c, we have S = √[s(s-a)(s-b)(s-c)] where s = (a+b+c)/2. We want to show a² + b² + c² ≥ 4√3 · S. This can be proven using the isoperimetric inequality and Jensen's inequality applied to the convex function f(x) = x²."
311+
# Keywords from problem text -> response with expected features
312+
"integer solutions": "This requires systematic case analysis. Let me examine small values systematically. After checking cases x,y,z < 100, the equation x³ + y³ = z³ - 1 has solutions like (x,y,z) = (1,1,1) since 1³ + 1³ = 2 = 2³ - 6... Actually, let me recalculate: 1³ + 1³ = 2, and z³ - 1 = 2 means z³ = 3, so z ≈ 1.44. Let me check (2,2,2): 8 + 8 = 16 = 8 - 1 = 7? No. This is a difficult Diophantine equation requiring advanced techniques.",
313+
"primes": "I'll prove this by contradiction using Euclid's method. Assume there are only finitely many primes of the form 4k+3: p₁, p₂, ..., pₙ. Consider N = 4(p₁p₂...pₙ) + 3. Since N ≡ 3 (mod 4), at least one prime factor of N must be ≡ 3 (mod 4). But N is not divisible by any of p₁, p₂, ..., pₙ, so there must be another prime of the form 4k+3, contradicting our assumption. Therefore, there are infinitely many such primes.",
314+
"distribute": "This is a stars and bars problem with constraints. We need to distribute 20 balls into 5 boxes with each box having at least 2 balls. First, place 2 balls in each box (using 10 balls). Now we need to distribute the remaining 10 balls into 5 boxes with no constraints. Using stars and bars: C(10+5-1, 5-1) = C(14,4) = 1001 ways.",
315+
"triangle": "This is a form of Weitzenböck's inequality. We can prove this using the relationship between area and sides. For a triangle with area S and sides a,b,c, we have S = √[s(s-a)(s-b)(s-c)] where s = (a+b+c)/2. We want to show a² + b² + c² ≥ 4√3 · S. This can be proven using the isoperimetric inequality and Jensen's inequality applied to the convex function f(x) = x²."
300316
}
301317

302318
def chat_completions_create(self, **kwargs):
303319
result = super().chat_completions_create(**kwargs)
304320

305-
# Look for problem type in the messages
321+
# Look for problem keywords in the messages
306322
messages = kwargs.get('messages', [])
307323
for message in messages:
308-
content = message.get('content', '')
309-
for prob_type, response in self.problem_responses.items():
310-
if any(keyword in content for keyword in prob_type.lower().split()):
324+
content = message.get('content', '').lower()
325+
for keyword, response in self.problem_responses.items():
326+
if keyword.lower() in content:
311327
result.choices[0].message.content = response
312328
return result
313329

0 commit comments

Comments
 (0)