karenina.adapters.factory¶
factory
¶
Adapter factory for routing to the appropriate LLM backend.
This module provides factory functions that create adapter instances based on the interface type specified in ModelConfig. The factory handles:
- Adapter Selection: Map
interfacevalue to correct adapter implementation - Availability Checking: Detect if required infrastructure is available
- Graceful Fallback: Fall back to LangChain when preferred adapter unavailable
- Configuration Conversion: Convert ModelConfig to adapter-specific options
Supported Interfaces
- langchain: Uses LangChainLLMAdapter/LangChainAgentAdapter
- openrouter: Routes through LangChain adapter
- openai_endpoint: Routes through LangChain adapter
- claude_agent_sdk: Uses Claude Agent SDK adapter (when available)
- claude_tool: Uses Claude Tool adapter with native structured output
- manual: Returns ManualAdapter (raises error if invoked)
Example
from karenina.adapters import get_agent, get_llm, get_parser from karenina.schemas.config import ModelConfig
config = ModelConfig( ... id="claude-sonnet", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic" ... )
Get adapters (always returns a port, never None)¶
agent = get_agent(config) llm = get_llm(config) parser = get_parser(config)
Use them (check interface before using for manual)¶
if config.interface != "manual": ... result = await agent.arun(messages=[Message.user("Hello!")])
Classes¶
Functions¶
build_llm_kwargs
¶
build_llm_kwargs(
model_config: ModelConfig,
*,
question_hash: str | None = None,
) -> dict[str, Any]
Build kwargs dict for init_chat_model_unified from a ModelConfig.
This centralizes the interface-specific parameter handling that was previously duplicated across call sites (generate_answer.py, template_evaluator.py, etc.).
Handles: - Base parameters (model, provider, temperature, interface) - OpenAI endpoint configuration (base_url, api_key) - Manual interface (question_hash) - MCP server configuration (urls, tool filter, description overrides) - Agent middleware configuration - Max context tokens - Extra kwargs from model config
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
ModelConfig
|
Model configuration with all settings. |
required |
|
str | None
|
MD5 hash of the question (required for manual interface). |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict of kwargs ready to pass to init_chat_model_unified(). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required parameters are missing for the interface. |
Example
config = ModelConfig( ... model_name="gpt-4", ... model_provider="openai", ... interface="langchain" ... ) kwargs = build_llm_kwargs(config) llm = init_chat_model_unified(**kwargs)
Source code in src/karenina/adapters/factory.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
check_adapter_available
¶
check_adapter_available(
interface: str,
) -> AdapterAvailability
Check if an adapter is available for the given interface.
This function verifies that the required infrastructure for an adapter is properly installed and configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The interface type to check (e.g., "langchain", "claude_agent_sdk"). |
required |
Returns:
| Type | Description |
|---|---|
AdapterAvailability
|
AdapterAvailability with status and details. |
Example
result = check_adapter_available("claude_agent_sdk") if result.available: ... print("Claude SDK is ready to use") ... else: ... print(f"Not available: {result.reason}")
Source code in src/karenina/adapters/factory.py
get_agent
¶
get_agent(
model_config: ModelConfig, *, auto_fallback: bool = True
) -> AgentPort
Create an Agent adapter for the given model configuration.
This factory function returns the appropriate AgentPort implementation based on the interface specified in the model configuration. Agent adapters support tool use and MCP server integration.
IMPORTANT: This function always returns an AgentPort, never None.
For manual interface, returns ManualAgentAdapter which raises
ManualInterfaceError if invoked. Call sites should check
model_config.interface != "manual" before using the adapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
|
bool
|
If True, automatically fall back to an alternative adapter when the preferred one is unavailable. If False, raise an error. |
True
|
Returns:
| Type | Description |
|---|---|
AgentPort
|
An AgentPort implementation. |
Raises:
| Type | Description |
|---|---|
AdapterUnavailableError
|
If the adapter is unavailable and auto_fallback=False. |
Example
config = ModelConfig( ... id="claude-sonnet", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic" ... ) agent = get_agent(config) if config.interface != "manual": ... result = await agent.arun( ... messages=[Message.user("What files are in /tmp?")], ... mcp_servers={"filesystem": {"type": "http", "url": "http://localhost:8080"}} ... )
Source code in src/karenina/adapters/factory.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
get_llm
¶
get_llm(
model_config: ModelConfig, *, auto_fallback: bool = True
) -> LLMPort
Create an LLM adapter for the given model configuration.
This factory function returns the appropriate LLMPort implementation based on the interface specified in the model configuration.
IMPORTANT: This function always returns an LLMPort, never None.
For manual interface, returns ManualLLMAdapter which raises
ManualInterfaceError if invoked. Call sites should check
model_config.interface != "manual" before using the adapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
|
bool
|
If True, automatically fall back to an alternative adapter when the preferred one is unavailable. If False, raise an error. |
True
|
Returns:
| Type | Description |
|---|---|
LLMPort
|
An LLMPort implementation. |
Raises:
| Type | Description |
|---|---|
AdapterUnavailableError
|
If the adapter is unavailable and auto_fallback=False. |
Example
config = ModelConfig( ... id="claude-sonnet", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic" ... ) llm = get_llm(config) if config.interface != "manual": ... response = await llm.ainvoke([Message.user("Hello!")])
Source code in src/karenina/adapters/factory.py
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 | |
get_parser
¶
get_parser(
model_config: ModelConfig, *, auto_fallback: bool = True
) -> ParserPort
Create a Parser adapter for the given model configuration.
This factory function returns the appropriate ParserPort implementation based on the interface specified in the model configuration. Parser adapters use LLMs to extract structured data from natural language responses.
IMPORTANT: This function always returns a ParserPort, never None.
For manual interface, returns ManualParserAdapter which raises
ManualInterfaceError if invoked. Call sites should check
model_config.interface != "manual" before using the adapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
|
bool
|
If True, automatically fall back to an alternative adapter when the preferred one is unavailable. If False, raise an error. |
True
|
Returns:
| Type | Description |
|---|---|
ParserPort
|
A ParserPort implementation. |
Raises:
| Type | Description |
|---|---|
AdapterUnavailableError
|
If the adapter is unavailable and auto_fallback=False. |
Example
from pydantic import BaseModel, Field
class Answer(BaseModel): ... gene: str = Field(description="Gene name mentioned")
config = ModelConfig( ... id="claude-sonnet", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic" ... ) parser = get_parser(config) if config.interface != "manual": ... answer = await parser.aparse_to_pydantic(trace_text, Answer)
Source code in src/karenina/adapters/factory.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | |
validate_model_config
¶
validate_model_config(
model_config: ModelConfig | None,
) -> None
Validate that a model configuration has all required fields.
This centralizes validation that was previously duplicated across evaluators. Called by factory functions before creating adapters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
ModelConfig | None
|
The model configuration to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If model_config is None, model_name is empty, or model_provider is missing for interfaces that require it. |
Example
config = ModelConfig(model_name="gpt-4", model_provider="openai") validate_model_config(config) # OK
validate_model_config(None) # Raises ValueError