11from abc import ABC , abstractmethod
2- from typing import Any , Dict , List , Union
2+ from typing import Any , Dict , List , Union , Optional , Tuple
3+
34
45class ModelAdapter (ABC ):
5- """Base adapter class for different model providers."""
6+ """Base adapter class for different model providers with common functionality."""
7+
8+ # Common parameter types and their validation
9+ COMMON_PARAMETERS = {
10+ "temperature" : (int , float ),
11+ "max_tokens" : int ,
12+ "top_p" : (int , float ),
13+ }
614
715 @abstractmethod
816 def adapt_config (self , model_config : Dict [str , Any ], version_data : Dict [str , Any ]) -> Dict [str , Any ]:
@@ -17,4 +25,148 @@ def adapt_messages(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]
1725 @abstractmethod
1826 def process_tools (self , tools_data : Union [Dict , List ]) -> List [Dict [str , Any ]]:
1927 """Process tools data into the appropriate format for the specific adapter."""
20- pass
28+ pass
29+
30+ # Common helper methods
31+
32+ def validate_and_extract_parameters (
33+ self ,
34+ version_data : Dict [str , Any ],
35+ parameter_mapping : Optional [Dict [str , str ]] = None
36+ ) -> Dict [str , Any ]:
37+ """
38+ Validate and extract common configuration parameters.
39+
40+ Args:
41+ version_data: The version data containing configuration
42+ parameter_mapping: Optional mapping from source to target parameter names
43+ If None, uses direct mapping (source = target)
44+
45+ Returns:
46+ Dict of validated parameters
47+
48+ Raises:
49+ ValueError: If parameter validation fails
50+ """
51+ parameter_mapping = parameter_mapping or {}
52+ validated_params = {}
53+ config = version_data .get ("config" , {})
54+
55+ for source_param , expected_type in self .COMMON_PARAMETERS .items ():
56+ if source_param in config and config [source_param ] is not None :
57+ value = config [source_param ]
58+
59+ # Validate parameter type
60+ if not isinstance (value , expected_type ):
61+ type_name = expected_type .__name__ if hasattr (expected_type , '__name__' ) else str (expected_type )
62+ raise ValueError (f"{ source_param } must be of type { type_name } , got { type (value ).__name__ } " )
63+
64+ # Map to target parameter name
65+ target_param = parameter_mapping .get (source_param , source_param )
66+ validated_params [target_param ] = value
67+
68+ return validated_params
69+
70+ def extract_tool_parameters (self , model_config : Dict [str , Any ]) -> Dict [str , Dict [str , Any ]]:
71+ """
72+ Extract custom tool parameters from model config.
73+
74+ Args:
75+ model_config: The model configuration dictionary
76+
77+ Returns:
78+ Dict mapping tool names to their custom parameters
79+ """
80+ tool_params = {}
81+
82+ for key in model_config :
83+ if key .startswith ("tool_params_" ):
84+ tool_name = key [len ("tool_params_" ):]
85+ tool_params [tool_name ] = model_config [key ]
86+
87+ return tool_params
88+
89+ def cleanup_tool_parameters (self , model_config : Dict [str , Any ]) -> None :
90+ """
91+ Remove temporary tool parameter entries from model config.
92+
93+ Args:
94+ model_config: The model configuration dictionary to clean
95+ """
96+ keys_to_remove = [key for key in model_config .keys () if key .startswith ("tool_params_" )]
97+ for key in keys_to_remove :
98+ del model_config [key ]
99+
100+ def apply_custom_parameters_to_schema (
101+ self ,
102+ input_schema : Dict [str , Any ],
103+ custom_params : Dict [str , Any ]
104+ ) -> Dict [str , Any ]:
105+ """
106+ Apply custom parameters to a tool's input schema.
107+
108+ Args:
109+ input_schema: The original input schema
110+ custom_params: Custom parameters to apply
111+
112+ Returns:
113+ Modified input schema with custom parameters applied
114+ """
115+ if not custom_params :
116+ return input_schema
117+
118+ # Create a copy to avoid modifying the original
119+ modified_schema = input_schema .copy ()
120+
121+ # Apply custom parameters to properties if they exist
122+ if "properties" in modified_schema and custom_params :
123+ if "properties" not in modified_schema :
124+ modified_schema ["properties" ] = {}
125+
126+ properties = modified_schema ["properties" ]
127+ for param_name , param_value in custom_params .items ():
128+ if param_name in properties :
129+ if not isinstance (properties [param_name ], dict ):
130+ properties [param_name ] = {}
131+ properties [param_name ]["default" ] = param_value
132+
133+ return modified_schema
134+
135+ def has_tools (self , model_config : Dict [str , Any ]) -> bool :
136+ """
137+ Check if model config has non-empty tools.
138+
139+ Args:
140+ model_config: The model configuration dictionary
141+
142+ Returns:
143+ True if tools exist and are non-empty
144+ """
145+ tools = model_config .get ("tools" )
146+ if not tools :
147+ return False
148+
149+ if isinstance (tools , list ):
150+ return len (tools ) > 0
151+ elif isinstance (tools , dict ):
152+ return len (tools ) > 0
153+
154+ return False
155+
156+ def get_model_from_config (self , version_data : Dict [str , Any ]) -> str :
157+ """
158+ Extract model name from version data configuration.
159+
160+ Args:
161+ version_data: The version data containing configuration
162+
163+ Returns:
164+ Model name
165+
166+ Raises:
167+ ValueError: If model is not specified
168+ """
169+ model = version_data .get ("config" , {}).get ("model" )
170+ if not model :
171+ raise ValueError ("Model must be specified in the version data config" )
172+ return model
0 commit comments