Skip to content

Commit 3e9819c

Browse files
authored
Merge pull request #197 from codelion/fix-dynamic-plugin-loading-packages
fixes error with loading plugins in package
2 parents a25ba8e + 9997243 commit 3e9819c

File tree

10 files changed

+91
-49
lines changed

10 files changed

+91
-49
lines changed

optillm/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import os
33

44
# Version information
5-
__version__ = "0.1.14"
5+
__version__ = "0.1.15"
66

77
# Get the path to the root optillm.py
88
spec = util.spec_from_file_location(

optillm/plugins/deepthink_plugin.py

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

8+
import os
9+
import sys
10+
import importlib.util
811
import logging
912
from typing import Tuple, Dict, Any
10-
from optillm.plugins.deepthink.self_discover import SelfDiscover
11-
from optillm.plugins.deepthink.uncertainty_cot import UncertaintyRoutedCoT
1213

1314
# Plugin identifier for optillm
1415
SLUG = "deepthink"
@@ -40,18 +41,38 @@ def run(
4041
"""
4142
logger.info("Starting Deep Think reasoning process")
4243

43-
# Extract configuration parameters
44-
config = _parse_config(request_config or {})
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')
47+
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)
4551

4652
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+
4768
# Initialize components
48-
self_discover = SelfDiscover(
69+
self_discover = self_discover_module.SelfDiscover(
4970
client=client,
5071
model=model,
5172
max_tokens=config["max_tokens"]
5273
)
5374

54-
uncertainty_cot = UncertaintyRoutedCoT(
75+
uncertainty_cot = uncertainty_cot_module.UncertaintyRoutedCoT(
5576
client=client,
5677
model=model,
5778
max_tokens=config["max_tokens"]
@@ -108,31 +129,10 @@ def run(
108129

109130
return final_response, total_tokens
110131

111-
except Exception as e:
112-
logger.error(f"Error in Deep Think plugin: {str(e)}")
113-
logger.debug(f"Exception traceback:", exc_info=True)
114-
115-
# Fallback to simple generation
116-
try:
117-
logger.info("Attempting fallback to simple generation")
118-
response = client.chat.completions.create(
119-
model=model,
120-
messages=[
121-
{"role": "system", "content": system_prompt},
122-
{"role": "user", "content": initial_query}
123-
],
124-
max_tokens=config["max_tokens"],
125-
temperature=config["temperature"],
126-
top_p=config["top_p"]
127-
)
128-
129-
logger.info("Fallback generation successful")
130-
return response.choices[0].message.content.strip(), response.usage.completion_tokens
131-
132-
except Exception as fallback_error:
133-
logger.error(f"Fallback generation also failed: {str(fallback_error)}")
134-
logger.debug(f"Fallback exception traceback:", exc_info=True)
135-
return f"Error in Deep Think plugin: {str(e)}", 0
132+
finally:
133+
# Remove from path after use
134+
if deepthink_dir in sys.path:
135+
sys.path.remove(deepthink_dir)
136136

137137
def _parse_config(request_config: Dict[str, Any]) -> Dict[str, Any]:
138138
"""Parse and validate configuration parameters."""

optillm/plugins/longcepo.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,31 @@
55
If you have any questions or want to contribute, please reach out to us on [cerebras.ai/discord](https://cerebras.ai/discord).
66
"""
77

8+
import os
9+
import sys
10+
import importlib.util
811
from typing import Tuple
9-
from optillm.plugins.longcepo.main import run_longcepo
10-
1112

1213
SLUG = "longcepo"
1314

1415
def run(system_prompt: str, initial_query: str, client, model: str) -> Tuple[str, int]:
15-
return run_longcepo(system_prompt, initial_query, client, model)
16+
# Get the directory where this plugin is located
17+
plugin_dir = os.path.dirname(os.path.abspath(__file__))
18+
longcepo_dir = os.path.join(plugin_dir, 'longcepo')
19+
main_file = os.path.join(longcepo_dir, 'main.py')
20+
21+
# Load the main module dynamically
22+
spec = importlib.util.spec_from_file_location("longcepo_main", main_file)
23+
longcepo_main = importlib.util.module_from_spec(spec)
24+
25+
# Add the longcepo directory to the Python path temporarily
26+
if longcepo_dir not in sys.path:
27+
sys.path.insert(0, longcepo_dir)
28+
29+
try:
30+
spec.loader.exec_module(longcepo_main)
31+
return longcepo_main.run_longcepo(system_prompt, initial_query, client, model)
32+
finally:
33+
# Remove from path after use
34+
if longcepo_dir in sys.path:
35+
sys.path.remove(longcepo_dir)

optillm/plugins/longcepo/chunking.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import re
44
from typing import List
55

6-
from optillm.plugins.longcepo.utils import logger
6+
from .utils import logger
77

88

99
def get_prompt_length(prompt: str, tokenizer, no_special_tokens=False, **kwargs) -> int:

optillm/plugins/longcepo/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
from typing import Tuple
33
from functools import partial
44

5-
from optillm.plugins.longcepo.mapreduce import mapreduce
6-
from optillm.plugins.longcepo.utils import (
5+
# Use relative imports that work within the dynamically loaded module
6+
from .mapreduce import mapreduce
7+
from .utils import (
78
get_prompt_response,
89
logger,
910
longcepo_init,

optillm/plugins/longcepo/mapreduce.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
from functools import partial
22
from typing import Tuple, List
33

4-
from optillm.plugins.longcepo.utils import (
4+
from .utils import (
55
CBLog,
66
LongCepoConfig,
77
get_prompt_response,
88
concurrent_map,
99
logger,
1010
loop_until_match,
1111
)
12-
from optillm.plugins.longcepo.chunking import (
12+
from .chunking import (
1313
chunk_context,
1414
get_prompt_length,
1515
)

optillm/plugins/longcepo/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from concurrent.futures import ThreadPoolExecutor, as_completed
44

55
from transformers import AutoTokenizer, PreTrainedTokenizerBase
6-
from optillm.plugins.longcepo.config import LongCepoConfig
6+
from .config import LongCepoConfig
77

88
logger = logging.getLogger(__name__)
99

optillm/plugins/spl.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
LLM incrementally better at solving problems by learning from its experiences.
1414
"""
1515

16+
import os
17+
import sys
18+
import importlib.util
1619
from typing import Tuple
17-
from optillm.plugins.spl.main import run_spl
1820

1921
# Plugin identifier
2022
SLUG = "spl"
@@ -34,4 +36,23 @@ def run(system_prompt: str, initial_query: str, client, model: str, request_conf
3436
Returns:
3537
Tuple[str, int]: The LLM response and token count
3638
"""
37-
return run_spl(system_prompt, initial_query, client, model, request_config)
39+
# Get the directory where this plugin is located
40+
plugin_dir = os.path.dirname(os.path.abspath(__file__))
41+
spl_dir = os.path.join(plugin_dir, 'spl')
42+
main_file = os.path.join(spl_dir, 'main.py')
43+
44+
# Load the main module dynamically
45+
spec = importlib.util.spec_from_file_location("spl_main", main_file)
46+
spl_main = importlib.util.module_from_spec(spec)
47+
48+
# Add the spl directory to the Python path temporarily
49+
if spl_dir not in sys.path:
50+
sys.path.insert(0, spl_dir)
51+
52+
try:
53+
spec.loader.exec_module(spl_main)
54+
return spl_main.run_spl(system_prompt, initial_query, client, model, request_config)
55+
finally:
56+
# Remove from path after use
57+
if spl_dir in sys.path:
58+
sys.path.remove(spl_dir)

optillm/plugins/spl/main.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,22 @@
66
import logging
77
from typing import Tuple, Dict, List, Optional, Any
88

9-
from optillm.plugins.spl.strategy import Strategy, StrategyDatabase
10-
from optillm.plugins.spl.generation import (
9+
from .strategy import Strategy, StrategyDatabase
10+
from .generation import (
1111
classify_problem,
1212
generate_strategy,
1313
should_create_new_strategy
1414
)
15-
from optillm.plugins.spl.evaluation import (
15+
from .evaluation import (
1616
select_relevant_strategies,
1717
evaluate_strategy_effectiveness,
1818
refine_strategy
1919
)
20-
from optillm.plugins.spl.utils import (
20+
from .utils import (
2121
extract_thinking,
2222
augment_system_prompt
2323
)
24-
from optillm.plugins.spl.config import (
24+
from .config import (
2525
DEFAULT_MAX_TOKENS,
2626
MAINTENANCE_INTERVAL,
2727
STRATEGY_MERGING_THRESHOLD,

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
setup(
55
name="optillm",
6-
version="0.1.14",
6+
version="0.1.15",
77
packages=find_packages(include=['optillm', 'optillm.*']), # This ensures all subpackages are included
88
py_modules=['optillm'],
99
package_data={

0 commit comments

Comments
 (0)