Skip to content

Commit aa0cfb2

Browse files
committed
fix plugin loads
1 parent f0792d6 commit aa0cfb2

File tree

9 files changed

+225
-94
lines changed

9 files changed

+225
-94
lines changed

optillm/plugins/deepthink/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,9 @@
33
44
A plugin that combines SELF-DISCOVER framework with uncertainty-routed
55
chain-of-thought for enhanced reasoning capabilities.
6-
"""
6+
"""
7+
8+
from .self_discover import SelfDiscover
9+
from .uncertainty_cot import UncertaintyRoutedCoT
10+
11+
__all__ = ['SelfDiscover', 'UncertaintyRoutedCoT']

optillm/plugins/deepthink_plugin.py

Lines changed: 61 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,9 @@
55
for enhanced reasoning in large language models.
66
"""
77

8-
import os
9-
import sys
10-
import importlib.util
118
import logging
129
from typing import Tuple, Dict, Any
10+
from optillm.plugins.deepthink import SelfDiscover, UncertaintyRoutedCoT
1311

1412
# Plugin identifier for optillm
1513
SLUG = "deepthink"
@@ -41,98 +39,72 @@ def run(
4139
"""
4240
logger.info("Starting Deep Think reasoning process")
4341

44-
# Get the directory where this plugin is located
45-
plugin_dir = os.path.dirname(os.path.abspath(__file__))
46-
deepthink_dir = os.path.join(plugin_dir, 'deepthink')
42+
# Extract configuration parameters
43+
config = _parse_config(request_config or {})
4744

48-
# Add the deepthink directory to the Python path temporarily
49-
if deepthink_dir not in sys.path:
50-
sys.path.insert(0, deepthink_dir)
45+
# Initialize components
46+
self_discover = SelfDiscover(
47+
client=client,
48+
model=model,
49+
max_tokens=config["max_tokens"]
50+
)
5151

52-
try:
53-
# Load the modules dynamically
54-
self_discover_file = os.path.join(deepthink_dir, 'self_discover.py')
55-
uncertainty_cot_file = os.path.join(deepthink_dir, 'uncertainty_cot.py')
56-
57-
spec1 = importlib.util.spec_from_file_location("self_discover", self_discover_file)
58-
self_discover_module = importlib.util.module_from_spec(spec1)
59-
spec1.loader.exec_module(self_discover_module)
60-
61-
spec2 = importlib.util.spec_from_file_location("uncertainty_cot", uncertainty_cot_file)
62-
uncertainty_cot_module = importlib.util.module_from_spec(spec2)
63-
spec2.loader.exec_module(uncertainty_cot_module)
64-
65-
# Extract configuration parameters
66-
config = _parse_config(request_config or {})
67-
68-
# Initialize components
69-
self_discover = self_discover_module.SelfDiscover(
70-
client=client,
71-
model=model,
72-
max_tokens=config["max_tokens"]
73-
)
74-
75-
uncertainty_cot = uncertainty_cot_module.UncertaintyRoutedCoT(
76-
client=client,
77-
model=model,
78-
max_tokens=config["max_tokens"]
79-
)
80-
81-
total_tokens = 0
82-
83-
# Stage 1: SELF-DISCOVER reasoning structure (if enabled)
84-
reasoning_structure = None
85-
if config["enable_self_discover"]:
86-
logger.info("Discovering task-specific reasoning structure")
87-
88-
discovery_result = self_discover.discover_reasoning_structure(
89-
task_description=_extract_task_description(initial_query, system_prompt),
90-
task_examples=None # Could be enhanced to extract examples
91-
)
92-
93-
reasoning_structure = discovery_result["reasoning_structure"]
94-
total_tokens += discovery_result["completion_tokens"]
95-
96-
logger.info(f"Discovered reasoning structure with {len(reasoning_structure)} components")
97-
98-
# Prepare enhanced prompt
99-
enhanced_prompt = _create_enhanced_prompt(
100-
system_prompt=system_prompt,
101-
initial_query=initial_query,
102-
reasoning_structure=reasoning_structure,
103-
config=config
104-
)
105-
106-
# Stage 2: Uncertainty-routed generation
107-
logger.info("Generating response with uncertainty routing")
52+
uncertainty_cot = UncertaintyRoutedCoT(
53+
client=client,
54+
model=model,
55+
max_tokens=config["max_tokens"]
56+
)
57+
58+
total_tokens = 0
59+
60+
# Stage 1: SELF-DISCOVER reasoning structure (if enabled)
61+
reasoning_structure = None
62+
if config["enable_self_discover"]:
63+
logger.info("Discovering task-specific reasoning structure")
10864

109-
generation_result = uncertainty_cot.generate_with_uncertainty_routing(
110-
prompt=enhanced_prompt,
111-
num_samples=config["deepthink_samples"],
112-
confidence_threshold=config["confidence_threshold"],
113-
temperature=config["temperature"],
114-
top_p=config["top_p"]
65+
discovery_result = self_discover.discover_reasoning_structure(
66+
task_description=_extract_task_description(initial_query, system_prompt),
67+
task_examples=None # Could be enhanced to extract examples
11568
)
11669

117-
total_tokens += generation_result["completion_tokens"]
70+
reasoning_structure = discovery_result["reasoning_structure"]
71+
total_tokens += discovery_result["completion_tokens"]
11872

119-
# Log routing decision
120-
logger.info(f"Routing decision: {generation_result['routing_decision']} "
121-
f"(confidence: {generation_result['confidence_score']:.3f})")
122-
123-
final_response = generation_result["final_response"]
124-
125-
# Clean up the response if needed
126-
final_response = _clean_response(final_response)
127-
128-
logger.info(f"Deep Think completed successfully. Total tokens: {total_tokens}")
129-
130-
return final_response, total_tokens
131-
132-
finally:
133-
# Remove from path after use
134-
if deepthink_dir in sys.path:
135-
sys.path.remove(deepthink_dir)
73+
logger.info(f"Discovered reasoning structure with {len(reasoning_structure)} components")
74+
75+
# Prepare enhanced prompt
76+
enhanced_prompt = _create_enhanced_prompt(
77+
system_prompt=system_prompt,
78+
initial_query=initial_query,
79+
reasoning_structure=reasoning_structure,
80+
config=config
81+
)
82+
83+
# Stage 2: Uncertainty-routed generation
84+
logger.info("Generating response with uncertainty routing")
85+
86+
generation_result = uncertainty_cot.generate_with_uncertainty_routing(
87+
prompt=enhanced_prompt,
88+
num_samples=config["deepthink_samples"],
89+
confidence_threshold=config["confidence_threshold"],
90+
temperature=config["temperature"],
91+
top_p=config["top_p"]
92+
)
93+
94+
total_tokens += generation_result["completion_tokens"]
95+
96+
# Log routing decision
97+
logger.info(f"Routing decision: {generation_result['routing_decision']} "
98+
f"(confidence: {generation_result['confidence_score']:.3f})")
99+
100+
final_response = generation_result["final_response"]
101+
102+
# Clean up the response if needed
103+
final_response = _clean_response(final_response)
104+
105+
logger.info(f"Deep Think completed successfully. Total tokens: {total_tokens}")
106+
107+
return final_response, total_tokens
136108

137109
def _parse_config(request_config: Dict[str, Any]) -> Dict[str, Any]:
138110
"""Parse and validate configuration parameters."""
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""LongCePO Plugin Package
2+
3+
Implementation of Long-Context Cerebras Planning and Optimization method.
4+
"""
5+
6+
from .main import run_longcepo
7+
8+
__version__ = "1.0.0"
9+
__author__ = "Cerebras"
10+
__all__ = ['run_longcepo']
File renamed without changes.

optillm/plugins/spl/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
"""
22
System Prompt Learning (SPL) plugin module initialization.
33
"""
4+
5+
from .main import run_spl
6+
7+
__all__ = ['run_spl']
File renamed without changes.

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ cerebras_cloud_sdk
3030
outlines[transformers]
3131
sentencepiece
3232
adaptive-classifier
33+
datasets
3334
mcp
3435
# MLX support for Apple Silicon optimization
3536
mlx-lm>=0.24.0; platform_machine=="arm64" and sys_platform=="darwin"

tests/test_ci_quick.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,25 @@
3434
import optillm.plugins.privacy_plugin
3535
import optillm.plugins.genselect_plugin
3636
import optillm.plugins.majority_voting_plugin
37-
print("✅ Plugin modules exist and can be imported")
37+
print("✅ Basic plugin modules exist and can be imported")
3838
except Exception as e:
39-
print(f"❌ Plugin import test failed: {e}")
39+
print(f"❌ Basic plugin import test failed: {e}")
40+
41+
# Test plugin subdirectory imports (critical for issue #220)
42+
try:
43+
from optillm.plugins.deepthink import SelfDiscover, UncertaintyRoutedCoT
44+
from optillm.plugins.deep_research import DeepResearcher
45+
from optillm.plugins.longcepo import run_longcepo
46+
from optillm.plugins.spl import run_spl
47+
print("✅ Plugin submodule imports working - no relative import errors")
48+
except ImportError as e:
49+
if "attempted relative import" in str(e):
50+
print(f"❌ Critical: Relative import error detected: {e}")
51+
sys.exit(1)
52+
else:
53+
print(f"❌ Plugin submodule import error: {e}")
54+
except Exception as e:
55+
print(f"❌ Plugin submodule import error: {e}")
4056

4157
# Test approach parsing
4258
try:

tests/test_plugins.py

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ def test_plugin_module_imports():
2727
'optillm.plugins.genselect_plugin',
2828
'optillm.plugins.majority_voting_plugin',
2929
'optillm.plugins.web_search_plugin',
30-
'optillm.plugins.deep_research_plugin'
30+
'optillm.plugins.deep_research_plugin',
31+
'optillm.plugins.deepthink_plugin',
32+
'optillm.plugins.longcepo_plugin',
33+
'optillm.plugins.spl_plugin'
3134
]
3235

3336
for module_name in plugin_modules:
@@ -48,7 +51,7 @@ def test_plugin_approach_detection():
4851
load_plugins()
4952

5053
# Check if known plugins are loaded
51-
expected_plugins = ["memory", "readurls", "privacy", "web_search", "deep_research"]
54+
expected_plugins = ["memory", "readurls", "privacy", "web_search", "deep_research", "deepthink", "longcepo", "spl"]
5255
for plugin_name in expected_plugins:
5356
assert plugin_name in plugin_approaches, f"Plugin {plugin_name} not loaded"
5457

@@ -100,6 +103,96 @@ def test_deep_research_plugin():
100103
assert plugin.SLUG == "deep_research"
101104

102105

106+
def test_deepthink_plugin_imports():
107+
"""Test deepthink plugin and its submodules can be imported"""
108+
# Test main plugin
109+
import optillm.plugins.deepthink_plugin as plugin
110+
assert hasattr(plugin, 'run')
111+
assert hasattr(plugin, 'SLUG')
112+
assert plugin.SLUG == "deepthink"
113+
114+
# Test submodules can be imported
115+
from optillm.plugins.deepthink import SelfDiscover, UncertaintyRoutedCoT
116+
assert SelfDiscover is not None
117+
assert UncertaintyRoutedCoT is not None
118+
119+
120+
def test_longcepo_plugin():
121+
"""Test longcepo plugin module"""
122+
import optillm.plugins.longcepo_plugin as plugin
123+
assert hasattr(plugin, 'run')
124+
assert hasattr(plugin, 'SLUG')
125+
assert plugin.SLUG == "longcepo"
126+
127+
# Test submodule can be imported
128+
from optillm.plugins.longcepo import run_longcepo
129+
assert run_longcepo is not None
130+
131+
132+
def test_spl_plugin():
133+
"""Test spl plugin module"""
134+
import optillm.plugins.spl_plugin as plugin
135+
assert hasattr(plugin, 'run')
136+
assert hasattr(plugin, 'SLUG')
137+
assert plugin.SLUG == "spl"
138+
139+
# Test submodule can be imported
140+
from optillm.plugins.spl import run_spl
141+
assert run_spl is not None
142+
143+
144+
def test_plugin_subdirectory_imports():
145+
"""Test all plugins with subdirectories can import their submodules"""
146+
# Test deep_research
147+
from optillm.plugins.deep_research import DeepResearcher
148+
assert DeepResearcher is not None
149+
150+
# Test deepthink
151+
from optillm.plugins.deepthink import SelfDiscover, UncertaintyRoutedCoT
152+
assert SelfDiscover is not None
153+
assert UncertaintyRoutedCoT is not None
154+
155+
# Test longcepo
156+
from optillm.plugins.longcepo import run_longcepo
157+
assert run_longcepo is not None
158+
159+
# Test spl
160+
from optillm.plugins.spl import run_spl
161+
assert run_spl is not None
162+
163+
164+
def test_no_relative_import_errors():
165+
"""Test that plugins load without relative import errors"""
166+
import importlib
167+
import sys
168+
169+
plugins_with_subdirs = [
170+
'optillm.plugins.deepthink_plugin',
171+
'optillm.plugins.deep_research_plugin',
172+
'optillm.plugins.longcepo_plugin',
173+
'optillm.plugins.spl_plugin'
174+
]
175+
176+
for plugin_name in plugins_with_subdirs:
177+
# Clear any previously loaded modules to test fresh import
178+
modules_to_clear = [k for k in sys.modules.keys() if k.startswith(plugin_name)]
179+
for mod in modules_to_clear:
180+
del sys.modules[mod]
181+
182+
try:
183+
module = importlib.import_module(plugin_name)
184+
# Try to access the run function to ensure full initialization works
185+
assert hasattr(module, 'run'), f"{plugin_name} missing run function"
186+
except ImportError as e:
187+
if "attempted relative import" in str(e):
188+
if pytest:
189+
pytest.fail(f"Relative import error in {plugin_name}: {e}")
190+
else:
191+
raise AssertionError(f"Relative import error in {plugin_name}: {e}")
192+
else:
193+
raise
194+
195+
103196
if __name__ == "__main__":
104197
print("Running plugin tests...")
105198

@@ -145,4 +238,34 @@ def test_deep_research_plugin():
145238
except Exception as e:
146239
print(f"❌ Deep research plugin test failed: {e}")
147240

241+
try:
242+
test_deepthink_plugin_imports()
243+
print("✅ Deepthink plugin imports test passed")
244+
except Exception as e:
245+
print(f"❌ Deepthink plugin imports test failed: {e}")
246+
247+
try:
248+
test_longcepo_plugin()
249+
print("✅ LongCePO plugin test passed")
250+
except Exception as e:
251+
print(f"❌ LongCePO plugin test failed: {e}")
252+
253+
try:
254+
test_spl_plugin()
255+
print("✅ SPL plugin test passed")
256+
except Exception as e:
257+
print(f"❌ SPL plugin test failed: {e}")
258+
259+
try:
260+
test_plugin_subdirectory_imports()
261+
print("✅ Plugin subdirectory imports test passed")
262+
except Exception as e:
263+
print(f"❌ Plugin subdirectory imports test failed: {e}")
264+
265+
try:
266+
test_no_relative_import_errors()
267+
print("✅ No relative import errors test passed")
268+
except Exception as e:
269+
print(f"❌ Relative import errors test failed: {e}")
270+
148271
print("\nDone!")

0 commit comments

Comments
 (0)