Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: Add custom LLM integration support (#507)

LearningCircuit3d102da08db3
diff --git a/.github/workflows/llm-tests.yml b/.github/workflows/llm-tests.yml
new file mode 100644
index 0000000000..cc58dfd95e
--- /dev/null
+++ b/.github/workflows/llm-tests.yml
@@ -0,0 +1,106 @@
+name: LLM Integration Tests
+
+on:
+ push:
+ branches: [ main, dev ]
+ paths:
+ - 'src/local_deep_research/llm/**'
+ - 'src/local_deep_research/config/llm_config.py'
+ - 'src/local_deep_research/api/research_functions.py'
+ - 'tests/test_llm/**'
+ - '.github/workflows/llm-tests.yml'
+ pull_request:
+ branches: [ main, dev ]
+ paths:
+ - 'src/local_deep_research/llm/**'
+ - 'src/local_deep_research/config/llm_config.py'
+ - 'src/local_deep_research/api/research_functions.py'
+ - 'tests/test_llm/**'
+ - '.github/workflows/llm-tests.yml'
+ workflow_dispatch:
+
+jobs:
+ llm-unit-tests:
+ runs-on: ubuntu-latest
+ name: LLM Unit Tests
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Set up PDM
+ uses: pdm-project/setup-pdm@v4
+
+ - name: Install dependencies
+ run: |
+ pdm install
+ pdm install -d
+
+ - name: Run LLM registry tests
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ pdm run pytest tests/test_llm/test_llm_registry.py -v
+
+ - name: Run LLM integration tests
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ export LDR_USE_FALLBACK_LLM=true
+ pdm run pytest tests/test_llm/test_llm_integration.py -v
+
+ - name: Run API LLM integration tests
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ export LDR_USE_FALLBACK_LLM=true
+ pdm run pytest tests/test_llm/test_api_llm_integration.py -v
+
+ - name: Run LLM edge case tests
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ pdm run pytest tests/test_llm/test_llm_edge_cases.py -v
+
+ - name: Run LLM benchmark tests
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ pdm run pytest tests/test_llm/test_llm_benchmarks.py -v
+
+ llm-example-tests:
+ runs-on: ubuntu-latest
+ name: LLM Example Tests
+ needs: llm-unit-tests
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Set up PDM
+ uses: pdm-project/setup-pdm@v4
+
+ - name: Install dependencies
+ run: |
+ pdm install
+
+ - name: Test basic custom LLM example
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ export LDR_USE_FALLBACK_LLM=true
+ timeout 60s pdm run python examples/llm_integration/basic_custom_llm.py || true
+
+ - name: Test mock LLM example
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ export LDR_USE_FALLBACK_LLM=true
+ timeout 60s pdm run python examples/llm_integration/mock_llm_example.py || true
+
+ - name: Test advanced custom LLM example
+ run: |
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
+ export LDR_USE_FALLBACK_LLM=true
+ timeout 60s pdm run python examples/llm_integration/advanced_custom_llm.py || true
diff --git a/docs/CUSTOM_LLM_INTEGRATION.md b/docs/CUSTOM_LLM_INTEGRATION.md
new file mode 100644
index 0000000000..8e73359a8b
--- /dev/null
+++ b/docs/CUSTOM_LLM_INTEGRATION.md
@@ -0,0 +1,275 @@
+# Custom LLM Integration Guide
+
+Local Deep Research now supports seamless integration with custom LangChain LLMs, allowing you to use your own language models, specialized wrappers, or third-party LLM providers alongside the built-in options.
+
+## Overview
+
+Similar to the custom retriever support, LDR allows you to register any LangChain-compatible LLM and use it throughout the system. This enables:
+
+- Using proprietary or fine-tuned models
+- Implementing custom retry logic or preprocessing
+- Integrating with LLM providers not built into LDR
+- Testing with mock LLMs
+- Creating specialized model configurations
+
+## Quick Start
+
+```python
+from local_deep_research.api import quick_summary
+
+# Option 1: Pass an LLM instance
+result = quick_summary(
+ query="Your research question",
+ llms={"my_model": your_llm_instance},
+ provider="my_model" # Use your custom LLM
+)
+
+# Option 2: Pass a factory function
+def create_llm(model_name=None, temperature=0.7, **kwargs):
+ return YourCustomLLM(model=model_name, temp=temperature)
+
+result = quick_summary(
+ query="Your research question",
+ llms={"custom": create_llm},
+ provider="custom",
+ model_name="gpt-turbo", # Passed to factory
+ temperature=0.5
+)
+```
+
+## Requirements
+
+Your custom LLM must:
+1. Inherit from `langchain_core.language_models.BaseChatModel`
+2. Implement the required methods (`_generate`, `_llm_type`)
+3. Handle the standard LangChain message formats
+
+## Example Implementation
+
+```python
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from typing import List, Optional, Any
+
+class CustomLLM(BaseChatModel):
+ """Example custom LLM implementation."""
+
+ def __init__(self, api_key: str, model_name: str = "custom-v1", **kwargs):
+ super().__init__(**kwargs)
+ self.api_key = api_key
+ self.model_name = model_name
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[Any] = None,
+ **kwargs: Any
+ ) -> ChatResult:
+ """Generate a response from your model."""
+ # Call your API/model here
+ response = your_api_call(messages, self.model_name, self.api_key)
+
+ # Convert to LangChain format
+ message = AIMessage(content=response.text)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ """Return identifier for this LLM."""
+ return "custom"
+```
+
+## Using with Different Research Modes
+
+### Quick Summary
+```python
+from local_deep_research.api import quick_summary
+
+result = quick_summary(
+ query="Explain quantum computing",
+ llms={"quantum_expert": quantum_llm},
+ provider="quantum_expert",
+ search_tool="arxiv" # Search scientific papers
+)
+```
+
+### Detailed Research
+```python
+from local_deep_research.api import detailed_research
+
+result = detailed_research(
+ query="Climate change impacts",
+ llms={"climate_model": climate_specialized_llm},
+ provider="climate_model",
+ iterations=3
+)
+```
+
+### Report Generation
+```python
+from local_deep_research.api import generate_report
+
+report = generate_report(
+ query="AI in healthcare",
+ llms={"medical_ai": medical_llm},
+ provider="medical_ai",
+ output_file="healthcare_ai_report.md"
+)
+```
+
+## Advanced Usage
+
+### Multiple Custom LLMs
+
+Register multiple LLMs for different purposes:
+
+```python
+llms = {
+ "technical": TechnicalWriterLLM(temperature=0.2),
+ "creative": CreativeWriterLLM(temperature=0.9),
+ "fact_checker": FactCheckingLLM(temperature=0.0)
+}
+
+# Use technical LLM for precise analysis
+result = quick_summary(
+ query="How do transformers work?",
+ llms=llms,
+ provider="technical"
+)
+```
+
+### Factory Functions with Configuration
+
+```python
+def create_configured_llm(model_name=None, temperature=0.7, max_retries=3, **kwargs):
+ """Factory that creates LLM with retry logic."""
+ base_llm = YourLLM(model=model_name, temperature=temperature)
+ return RetryWrapper(base_llm, max_retries=max_retries)
+
+result = quick_summary(
+ query="Your question",
+ llms={"retry_llm": create_configured_llm},
+ provider="retry_llm",
+ model_name="your-model-v2",
+ max_retries=5 # Custom parameter
+)
+```
+
+### Combining Custom LLMs and Retrievers
+
+```python
+result = quick_summary(
+ query="Internal policy on remote work",
+ llms={"company_llm": company_fine_tuned_llm},
+ retrievers={"company_docs": company_retriever},
+ provider="company_llm",
+ search_tool="company_docs"
+)
+```
+
+## Implementation Details
+
+### How It Works
+
+1. **Registration**: When you pass LLMs via the `llms` parameter, they are registered in a global registry
+2. **Provider Check**: When creating an LLM, the system first checks if the provider name matches a registered custom LLM
+3. **Factory Support**: If the registered LLM is callable, it's treated as a factory and called with the provided parameters
+4. **Wrapping**: All LLMs (custom and built-in) are wrapped with think-tag removal and token counting
+
+### Thread Safety
+
+The LLM registry is thread-safe, allowing concurrent usage in multi-threaded applications.
+
+### Scope
+
+Registered LLMs are available globally within the Python process. They persist until explicitly unregistered or the process ends.
+
+## Best Practices
+
+1. **Consistent Naming**: Use clear, descriptive names for your custom LLMs
+2. **Error Handling**: Implement proper error handling in your LLM's `_generate` method
+3. **Token Counting**: If your LLM supports token counting, implement the appropriate methods
+4. **Temperature Handling**: Respect the temperature parameter for consistency
+5. **Async Support**: Implement async methods if your LLM supports asynchronous operation
+
+## Common Use Cases
+
+### Fine-tuned Models
+```python
+# Use your fine-tuned model for domain-specific research
+fine_tuned_llm = CustomLLM(
+ model_path="/path/to/fine-tuned-model",
+ domain="medical"
+)
+
+result = quick_summary(
+ query="Latest treatments for condition X",
+ llms={"medical_expert": fine_tuned_llm},
+ provider="medical_expert"
+)
+```
+
+### Mock LLMs for Testing
+```python
+class MockLLM(BaseChatModel):
+ """Returns predefined responses for testing."""
+
+ def _generate(self, messages, **kwargs):
+ # Return test data
+ return ChatResult(generations=[
+ ChatGeneration(message=AIMessage(content="Test response"))
+ ])
+
+# Use in tests
+result = quick_summary(
+ query="Test query",
+ llms={"mock": MockLLM()},
+ provider="mock",
+ search_tool="none" # Disable search for pure testing
+)
+```
+
+### Rate-Limited Wrapper
+```python
+class RateLimitedLLM(BaseChatModel):
+ """Adds rate limiting to any LLM."""
+
+ def __init__(self, base_llm, requests_per_minute=10):
+ super().__init__()
+ self.base_llm = base_llm
+ self.rate_limiter = RateLimiter(requests_per_minute)
+
+ def _generate(self, messages, **kwargs):
+ self.rate_limiter.wait_if_needed()
+ return self.base_llm._generate(messages, **kwargs)
+```
+
+## Troubleshooting
+
+### LLM Not Found
+If you get "Invalid provider" errors:
+- Ensure you're passing the `llms` parameter to the API function
+- Check that the provider name matches exactly (case-insensitive)
+- Verify your LLM instance is properly initialized
+
+### Parameter Passing
+When using factory functions:
+- Standard parameters (model_name, temperature) are passed automatically
+- Custom parameters can be passed via kwargs
+- The factory receives all parameters from the API call
+
+### Compatibility Issues
+Ensure your LLM:
+- Inherits from `BaseChatModel`
+- Returns proper `ChatResult` objects
+- Handles the LangChain message format
+
+## Related Documentation
+
+- [API Documentation](api-quickstart.md)
+- [Configuration Guide](env_configuration.md)
+- [LangChain Retriever Integration](LANGCHAIN_RETRIEVER_INTEGRATION.md)
diff --git a/examples/llm_integration/README.md b/examples/llm_integration/README.md
new file mode 100644
index 0000000000..370762ac09
--- /dev/null
+++ b/examples/llm_integration/README.md
@@ -0,0 +1,51 @@
+# LLM Integration Examples
+
+This directory contains examples of integrating custom LangChain LLMs with Local Deep Research.
+
+## Examples
+
+### 1. Basic Custom LLM (`basic_custom_llm.py`)
+Shows the simplest way to create and use a custom LLM with LDR.
+
+### 2. Advanced Custom LLM (`advanced_custom_llm.py`)
+Demonstrates advanced features like:
+- Factory functions with configuration
+- Multiple LLM registration
+- Combining with custom retrievers
+- Error handling and retry logic
+
+### 3. Fine-tuned Model Integration (`finetuned_model_example.py`)
+Example of using a fine-tuned model for domain-specific research.
+
+### 4. Mock LLM for Testing (`mock_llm_example.py`)
+Shows how to create mock LLMs for testing your research pipelines without API costs.
+
+### 5. Rate-Limited Wrapper (`rate_limited_llm.py`)
+Demonstrates wrapping any LLM with rate limiting to avoid API limits.
+
+## Running the Examples
+
+1. Install Local Deep Research:
+```bash
+pip install local-deep-research
+```
+
+2. Run an example:
+```bash
+python examples/llm_integration/basic_custom_llm.py
+```
+
+## Key Concepts
+
+- **BaseChatModel**: All custom LLMs must inherit from `langchain_core.language_models.BaseChatModel`
+- **Factory Functions**: Can be used to create LLMs with dynamic configuration
+- **Registration**: LLMs are registered via the `llms` parameter in API functions
+- **Provider Selection**: Use the registered name as the `provider` parameter
+
+## Common Use Cases
+
+1. **Fine-tuned Models**: Use models trained on your specific domain
+2. **Custom Wrappers**: Add logging, retry logic, or preprocessing
+3. **Mock Testing**: Test research flows without real LLM calls
+4. **Rate Limiting**: Manage API quotas effectively
+5. **Multi-Model Pipelines**: Use different models for different research phases
diff --git a/examples/llm_integration/advanced_custom_llm.py b/examples/llm_integration/advanced_custom_llm.py
new file mode 100644
index 0000000000..eda76f5834
--- /dev/null
+++ b/examples/llm_integration/advanced_custom_llm.py
@@ -0,0 +1,349 @@
+"""
+Advanced example of custom LLM integration with Local Deep Research.
+
+This example demonstrates:
+- Factory functions with configuration
+- Error handling and retry logic
+- Combining multiple LLMs
+- Integration with custom retrievers
+"""
+
+import time
+from typing import List, Optional, Any, Dict
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import BaseMessage, AIMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from loguru import logger
+
+from local_deep_research.api import quick_summary, detailed_research
+
+
+class RetryLLM(BaseChatModel):
+ """LLM wrapper that adds retry logic to any base LLM."""
+
+ def __init__(
+ self,
+ base_llm: BaseChatModel,
+ max_retries: int = 3,
+ retry_delay: float = 1.0,
+ ):
+ super().__init__()
+ self.base_llm = base_llm
+ self.max_retries = max_retries
+ self.retry_delay = retry_delay
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate with retry logic."""
+ last_error = None
+
+ for attempt in range(self.max_retries):
+ try:
+ return self.base_llm._generate(
+ messages, stop, run_manager, **kwargs
+ )
+ except Exception as e:
+ last_error = e
+ if attempt < self.max_retries - 1:
+ logger.warning(
+ f"Attempt {attempt + 1} failed, retrying in {self.retry_delay}s..."
+ )
+ time.sleep(self.retry_delay)
+ self.retry_delay *= 2 # Exponential backoff
+
+ raise last_error
+
+ @property
+ def _llm_type(self) -> str:
+ return f"retry_{self.base_llm._llm_type}"
+
+
+class ConfigurableLLM(BaseChatModel):
+ """LLM that can be configured with custom parameters."""
+
+ def __init__(
+ self,
+ model_name: str = "configurable-v1",
+ response_style: str = "technical",
+ max_length: int = 500,
+ include_confidence: bool = False,
+ **kwargs,
+ ):
+ """
+ Initialize ConfigurableLLM.
+
+ Args:
+ model_name: Name of the model to use
+ response_style: Style of response ('technical', 'simple', or other)
+ max_length: Maximum length of response in characters
+ include_confidence: Whether to include confidence scores in responses
+ **kwargs: Additional keyword arguments
+ """
+ super().__init__(**kwargs)
+ self.model_name = model_name
+ self.response_style = response_style
+ self.max_length = max_length
+ self.include_confidence = include_confidence
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate response based on configuration."""
+ # Extract the query
+ query = messages[-1].content if messages else "No query"
+
+ # Build response based on style
+ if self.response_style == "technical":
+ response = (
+ f"Technical Analysis ({self.model_name}): {query[:100]}..."
+ )
+ elif self.response_style == "simple":
+ response = (
+ f"Simple Answer: Based on the query about {query[:50]}..."
+ )
+ else:
+ response = f"Response: Processing '{query[:50]}...'"
+
+ # Limit length
+ response = response[: self.max_length]
+
+ # Add confidence if requested
+ if self.include_confidence:
+ response += "\n\nConfidence: High" # Use descriptive confidence instead of hardcoded percentage
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "configurable"
+
+
+class DomainExpertLLM(BaseChatModel):
+ """LLM that specializes in specific domains."""
+
+ def __init__(self, domain: str = "general", expertise_level: float = 0.8):
+ super().__init__()
+ self.domain = domain
+ self.expertise_level = expertise_level
+ self.domain_knowledge = {
+ "medical": ["diagnosis", "treatment", "symptoms", "medications"],
+ "legal": ["contracts", "liability", "regulations", "compliance"],
+ "technical": [
+ "algorithms",
+ "architecture",
+ "performance",
+ "scalability",
+ ],
+ "finance": ["investments", "risk", "portfolio", "markets"],
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate domain-specific response."""
+ query = messages[-1].content if messages else ""
+
+ # Check if query matches domain
+ domain_terms = self.domain_knowledge.get(self.domain, [])
+ relevance = sum(
+ 1 for term in domain_terms if term.lower() in query.lower()
+ )
+
+ if relevance > 0:
+ response = f"[{self.domain.upper()} EXPERT - High Relevance]: "
+ else:
+ response = f"[{self.domain.upper()} EXPERT - General]: "
+
+ response += f"Based on my {self.domain} expertise (level: {self.expertise_level}), "
+ response += f"regarding '{query[:100]}...': This requires specialized knowledge."
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return f"expert_{self.domain}"
+
+
+def create_configured_llm(config: Dict[str, Any]) -> BaseChatModel:
+ """Factory function that creates LLMs based on configuration."""
+ llm_type = config.get("type", "basic")
+
+ if llm_type == "retry":
+ # Create base LLM first
+ base_config = config.get("base_config", {})
+ base_llm = create_configured_llm(base_config)
+
+ # Wrap with retry
+ return RetryLLM(
+ base_llm=base_llm,
+ max_retries=config.get("max_retries", 3),
+ retry_delay=config.get("retry_delay", 1.0),
+ )
+
+ elif llm_type == "configurable":
+ return ConfigurableLLM(
+ model_name=config.get("model_name", "config-v1"),
+ response_style=config.get("style", "technical"),
+ max_length=config.get("max_length", 500),
+ include_confidence=config.get("include_confidence", False),
+ )
+
+ elif llm_type == "expert":
+ return DomainExpertLLM(
+ domain=config.get("domain", "general"),
+ expertise_level=config.get("expertise_level", 0.8),
+ )
+
+ else:
+ # Default fallback
+ return ConfigurableLLM()
+
+
+def main():
+ logger.info("Advanced Custom LLM Integration Examples")
+ logger.info("=" * 60)
+
+ # Example 1: Using a retry wrapper
+ logger.info("\n1. Retry Wrapper Example:")
+ base_llm = ConfigurableLLM(response_style="technical")
+ retry_llm = RetryLLM(base_llm, max_retries=3)
+
+ result = quick_summary(
+ query="Explain quantum computing applications",
+ llms={"retry_tech": retry_llm},
+ provider="retry_tech",
+ search_tool="wikipedia",
+ )
+ logger.info(f"Summary: {result['summary'][:200]}...")
+
+ # Example 2: Multiple domain experts
+ logger.info("\n\n2. Multiple Domain Experts:")
+ experts = {
+ "medical_expert": DomainExpertLLM(
+ domain="medical", expertise_level=0.95
+ ),
+ "tech_expert": DomainExpertLLM(domain="technical", expertise_level=0.9),
+ "finance_expert": DomainExpertLLM(
+ domain="finance", expertise_level=0.85
+ ),
+ }
+
+ # Medical query
+ _ = quick_summary(
+ query="What are the latest treatments for diabetes?",
+ llms=experts,
+ provider="medical_expert",
+ search_tool="pubmed",
+ )
+ logger.info(
+ "Medical summary retrieved successfully. Content not logged for privacy."
+ )
+
+ # Example 3: Factory with configuration
+ logger.info("\n\n3. Factory Configuration Example:")
+
+ # Configuration for a technical writer
+ tech_writer_config = {
+ "type": "configurable",
+ "model_name": "tech-writer-v2",
+ "style": "technical",
+ "max_length": 1000,
+ "include_confidence": True,
+ }
+
+ # Configuration for a retry wrapper around the technical writer
+ robust_config = {
+ "type": "retry",
+ "max_retries": 5,
+ "retry_delay": 0.5,
+ "base_config": tech_writer_config,
+ }
+
+ result = quick_summary(
+ query="How do neural networks learn?",
+ llms={
+ "robust_writer": lambda **kwargs: create_configured_llm(
+ robust_config
+ )
+ },
+ provider="robust_writer",
+ search_tool="arxiv",
+ )
+ logger.info(f"Robust Writer: {result['summary'][:150]}...")
+
+ # Example 4: Research pipeline with different LLMs
+ logger.info("\n\n4. Multi-Stage Research Pipeline:")
+
+ # Stage 1: Quick exploration with simple LLM
+ simple_llm = ConfigurableLLM(response_style="simple", max_length=200)
+
+ initial = quick_summary(
+ query="Climate change impacts on agriculture",
+ llms={"simple": simple_llm},
+ provider="simple",
+ iterations=1,
+ )
+
+ logger.info(f"Initial exploration: {initial['summary'][:100]}...")
+
+ # Stage 2: Detailed research with expert
+ expert_llm = DomainExpertLLM(domain="technical", expertise_level=0.95)
+
+ detailed = detailed_research(
+ query="Climate change impacts on agriculture: focus on technology solutions",
+ llms={"expert": expert_llm},
+ provider="expert",
+ iterations=2,
+ )
+
+ logger.info(f"Expert analysis: {detailed['summary'][:150]}...")
+
+ # Example 5: Combining custom LLMs with custom retrievers
+ logger.info("\n\n5. Custom LLM + Retriever Combination:")
+
+ # Mock retriever for demonstration
+ class MockRetriever:
+ def get_relevant_documents(self, query):
+ return [
+ {"page_content": f"Mock document about {query}", "metadata": {}}
+ ]
+
+ custom_llm = ConfigurableLLM(
+ model_name="integrated-v1",
+ response_style="technical",
+ include_confidence=True,
+ )
+
+ result = quick_summary(
+ query="Internal company policies on remote work",
+ llms={"integrated": custom_llm},
+ retrievers={"company_docs": MockRetriever()},
+ provider="integrated",
+ search_tool="company_docs",
+ )
+
+ logger.info(f"Integrated result: {result['summary'][:150]}...")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/llm_integration/basic_custom_llm.py b/examples/llm_integration/basic_custom_llm.py
new file mode 100644
index 0000000000..940509edff
--- /dev/null
+++ b/examples/llm_integration/basic_custom_llm.py
@@ -0,0 +1,115 @@
+"""
+Example of using custom LangChain LLMs with Local Deep Research.
+
+This example shows how to integrate your own LLM implementations or wrappers
+with LDR's research functions.
+"""
+
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import BaseMessage, AIMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from typing import List, Optional, Any
+from local_deep_research.api import quick_summary, detailed_research
+
+
+class CustomLLM(BaseChatModel):
+ """Example custom LLM implementation."""
+
+ def __init__(
+ self, model_name: str = "custom-model", temperature: float = 0.7
+ ):
+ super().__init__()
+ self.model_name = model_name
+ self.temperature = temperature
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[Any] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate a response. This is where you'd call your custom model."""
+ # This is a mock implementation - replace with your actual model call
+ response_text = f"This is a response from {self.model_name} to: {messages[-1].content}"
+
+ # Create the response
+ message = AIMessage(content=response_text)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ """Return identifier for this LLM."""
+ return "custom"
+
+
+def custom_llm_factory(
+ model_name: str = "factory-model", temperature: float = 0.5, **kwargs
+):
+ """Factory function that creates a custom LLM instance."""
+ return CustomLLM(model_name=model_name, temperature=temperature)
+
+
+def main():
+ # Example 1: Using a custom LLM instance
+ custom_llm = CustomLLM(model_name="my-custom-model", temperature=0.8)
+
+ result = quick_summary(
+ query="What are the latest advances in quantum computing?",
+ llms={"my_custom": custom_llm},
+ provider="my_custom", # Use our registered LLM
+ search_tool="wikipedia", # Use Wikipedia as search engine
+ )
+
+ print("Summary with custom LLM instance:")
+ print(result["summary"])
+ print("-" * 80)
+
+ # Example 2: Using a factory function
+ result = quick_summary(
+ query="Explain the benefits of renewable energy",
+ llms={"factory_llm": custom_llm_factory},
+ provider="factory_llm", # Use our factory-created LLM
+ model_name="renewable-expert", # This gets passed to the factory
+ temperature=0.3,
+ search_tool="auto",
+ )
+
+ print("\nSummary with factory-created LLM:")
+ print(result["summary"])
+ print("-" * 80)
+
+ # Example 3: Multiple custom LLMs
+ llms = {
+ "technical": CustomLLM(model_name="technical-writer", temperature=0.2),
+ "creative": CustomLLM(model_name="creative-writer", temperature=0.9),
+ }
+
+ # Technical analysis
+ technical_result = detailed_research(
+ query="How do neural networks work?",
+ llms=llms,
+ provider="technical",
+ search_tool="arxiv",
+ )
+
+ print("\nTechnical analysis:")
+ print(technical_result["summary"])
+ print("-" * 80)
+
+ # Creative exploration
+ creative_result = quick_summary(
+ query="What are the philosophical implications of AI?",
+ llms=llms,
+ provider="creative",
+ search_tool="wikipedia",
+ )
+
+ print("\nCreative exploration:")
+ print(creative_result["summary"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/llm_integration/mock_llm_example.py b/examples/llm_integration/mock_llm_example.py
new file mode 100644
index 0000000000..81a42018b2
--- /dev/null
+++ b/examples/llm_integration/mock_llm_example.py
@@ -0,0 +1,317 @@
+"""
+Mock LLM example for testing Local Deep Research without API costs.
+
+This example shows how to create mock LLMs that return predefined responses,
+useful for:
+- Testing research pipelines
+- Development without API keys
+- Debugging specific scenarios
+- CI/CD pipelines
+"""
+
+from typing import List, Optional, Any, Dict
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import BaseMessage, AIMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+import json
+
+from local_deep_research.api import quick_summary, generate_report
+
+
+class MockLLM(BaseChatModel):
+ """Mock LLM that returns predefined responses based on queries."""
+
+ def __init__(self, response_map: Optional[Dict[str, str]] = None):
+ super().__init__()
+ self.response_map = response_map or self._get_default_responses()
+ self.call_history = []
+
+ def _get_default_responses(self) -> Dict[str, str]:
+ """Get default mock responses."""
+ return {
+ "default": "This is a mock response for testing purposes.",
+ "quantum": "Quantum computing uses quantum mechanics principles like superposition and entanglement to process information in fundamentally new ways.",
+ "climate": "Climate change refers to long-term shifts in global temperatures and weather patterns, primarily driven by human activities.",
+ "ai": "Artificial Intelligence encompasses machine learning, neural networks, and systems that can perform tasks requiring human intelligence.",
+ "summary": "Based on the search results, here is a comprehensive summary of the findings.",
+ "report": "# Research Report\n\n## Executive Summary\n\nThis report provides detailed analysis.\n\n## Findings\n\n1. Key finding one\n2. Key finding two",
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[Any] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate mock response based on query content."""
+ # Extract query
+ query = messages[-1].content.lower() if messages else ""
+
+ # Log the call
+ self.call_history.append(
+ {
+ "messages": [
+ {"role": m.__class__.__name__, "content": m.content}
+ for m in messages
+ ],
+ "kwargs": kwargs,
+ }
+ )
+
+ # Find matching response
+ response = self.response_map.get("default", "Mock response")
+
+ for key, value in self.response_map.items():
+ if key in query:
+ response = value
+ break
+
+ # Create response
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "mock"
+
+ def get_call_history(self) -> List[Dict]:
+ """Get history of all calls made to this LLM."""
+ return self.call_history
+
+ def clear_history(self):
+ """Clear call history."""
+ self.call_history = []
+
+
+class ScenarioMockLLM(BaseChatModel):
+ """Mock LLM that simulates specific scenarios for testing."""
+
+ def __init__(self, scenario: str = "success"):
+ super().__init__()
+ self.scenario = scenario
+ self.call_count = 0
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[Any] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate response based on scenario."""
+ self.call_count += 1
+
+ if self.scenario == "success":
+ response = self._success_response(messages)
+ elif self.scenario == "partial_failure":
+ response = self._partial_failure_response()
+ elif self.scenario == "empty":
+ response = ""
+ elif self.scenario == "verbose":
+ response = self._verbose_response(messages)
+ elif self.scenario == "json":
+ response = self._json_response(messages)
+ else:
+ response = f"Unknown scenario: {self.scenario}"
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+
+ return ChatResult(generations=[generation])
+
+ def _success_response(self, messages):
+ """Generate successful response."""
+ query = messages[-1].content if messages else "query"
+ return f"Successfully analyzed: {query}. Found 5 relevant sources with high confidence."
+
+ def _partial_failure_response(self):
+ """Generate partial failure response."""
+ if self.call_count % 3 == 0:
+ return "Unable to process query due to insufficient data."
+ return "Partial results found. Limited information available."
+
+ def _verbose_response(self, messages):
+ """Generate verbose response for testing truncation."""
+ query = messages[-1].content if messages else "query"
+ return f"""
+ Detailed Analysis of: {query}
+
+ Section 1: Introduction
+ {"-" * 50}
+ This is a comprehensive analysis with multiple sections.
+
+ Section 2: Methodology
+ {"-" * 50}
+ We used advanced techniques to analyze this query.
+
+ Section 3: Findings
+ {"-" * 50}
+ Finding 1: Important discovery about the topic.
+ Finding 2: Another significant insight.
+ Finding 3: Additional relevant information.
+
+ Section 4: Conclusion
+ {"-" * 50}
+ In conclusion, this analysis provides valuable insights.
+ """ + "\n".join([f"Additional point {i}" for i in range(20)])
+
+ def _json_response(self, messages):
+ """Generate JSON response for testing parsing."""
+ query = messages[-1].content if messages else "query"
+ data = {
+ "query": query,
+ "findings": [
+ {"id": 1, "content": "First finding", "confidence": 0.9},
+ {"id": 2, "content": "Second finding", "confidence": 0.85},
+ ],
+ "summary": "JSON-formatted response for testing",
+ "metadata": {"timestamp": "2024-01-01T00:00:00Z", "version": "1.0"},
+ }
+ return json.dumps(data, indent=2)
+
+ @property
+ def _llm_type(self) -> str:
+ return f"scenario_{self.scenario}"
+
+
+def test_basic_mock():
+ """Test basic mock functionality."""
+ print("Testing Basic Mock LLM")
+ print("-" * 40)
+
+ mock_llm = MockLLM()
+
+ result = quick_summary(
+ query="Tell me about quantum computing",
+ llms={"mock": mock_llm},
+ provider="mock",
+ search_tool="none", # Disable search for pure mock testing
+ iterations=1,
+ )
+
+ print(f"Result: {result['summary']}")
+ print(f"Call history: {len(mock_llm.get_call_history())} calls")
+ print()
+
+
+def test_scenario_mocks():
+ """Test different scenario mocks."""
+ print("Testing Scenario Mocks")
+ print("-" * 40)
+
+ scenarios = ["success", "partial_failure", "empty", "verbose", "json"]
+
+ for scenario in scenarios:
+ print(f"\nScenario: {scenario}")
+ mock_llm = ScenarioMockLLM(scenario=scenario)
+
+ try:
+ result = quick_summary(
+ query="Test query for scenario",
+ llms={f"mock_{scenario}": mock_llm},
+ provider=f"mock_{scenario}",
+ search_tool="none",
+ iterations=1,
+ )
+
+ print(f"Summary preview: {result['summary'][:100]}...")
+ print(f"Calls made: {mock_llm.call_count}")
+
+ except Exception as e:
+ print(f"Error in scenario {scenario}: {e}")
+
+
+def test_mock_in_pipeline():
+ """Test mock LLM in a full research pipeline."""
+ print("\nTesting Mock in Research Pipeline")
+ print("-" * 40)
+
+ # Create specialized mocks for different stages
+ response_map = {
+ "questions": "Generated questions: 1) What is X? 2) How does Y work? 3) What are the benefits?",
+ "analysis": "Analysis complete. Key findings: A, B, and C.",
+ "synthesis": "Synthesis: Combining all findings into coherent summary.",
+ "report": "# Final Report\n\n## Summary\n\nAll findings have been compiled.",
+ }
+
+ mock_llm = MockLLM(response_map=response_map)
+
+ # Test with report generation
+ report = generate_report(
+ query="Create a comprehensive report",
+ llms={"pipeline_mock": mock_llm},
+ provider="pipeline_mock",
+ search_tool="none",
+ searches_per_section=1,
+ )
+
+ print(f"Report generated: {len(report.get('content', ''))} characters")
+ print(f"Total LLM calls: {len(mock_llm.get_call_history())}")
+
+ # Analyze call patterns
+ print("\nCall Analysis:")
+ for i, call in enumerate(mock_llm.get_call_history()[:5]): # First 5 calls
+ last_message = (
+ call["messages"][-1]["content"]
+ if call["messages"]
+ else "No message"
+ )
+ print(f" Call {i + 1}: {last_message[:50]}...")
+
+
+def test_mock_with_custom_retriever():
+ """Test mock LLM with custom retriever."""
+ print("\nTesting Mock LLM with Custom Retriever")
+ print("-" * 40)
+
+ class MockRetriever:
+ def get_relevant_documents(self, query):
+ return [
+ {
+ "page_content": f"Document 1 about {query}",
+ "metadata": {"source": "test1"},
+ },
+ {
+ "page_content": f"Document 2 about {query}",
+ "metadata": {"source": "test2"},
+ },
+ ]
+
+ mock_llm = MockLLM(
+ {
+ "default": "Analyzed documents and found relevant information.",
+ "summary": "Summary: Based on internal documents, the answer is clear.",
+ }
+ )
+
+ result = quick_summary(
+ query="Internal policy question",
+ llms={"mock": mock_llm},
+ retrievers={"mock_retriever": MockRetriever()},
+ provider="mock",
+ search_tool="mock_retriever",
+ )
+
+ print(f"Result: {result['summary']}")
+ print(f"Sources: {result.get('sources', [])}")
+
+
+def main():
+ """Run all mock examples."""
+ test_basic_mock()
+ test_scenario_mocks()
+ test_mock_in_pipeline()
+ test_mock_with_custom_retriever()
+
+ print("\n" + "=" * 60)
+ print("Mock LLM Testing Complete!")
+ print(
+ "Use these patterns to test your research pipelines without API costs."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 9c271c7669..bc8b597553 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -25,6 +25,8 @@ def _init_search_system(
search_strategy: str = "source_based",
iterations: int = 1,
questions_per_iteration: int = 1,
+ retrievers: Optional[Dict[str, Any]] = None,
+ llms: Optional[Dict[str, Any]] = None,
) -> AdvancedSearchSystem:
"""
Initializes the advanced search system with specified parameters. This function sets up
@@ -44,11 +46,22 @@ def _init_search_system(
iterations: Number of research cycles to perform
questions_per_iteration: Number of questions to generate per cycle
search_strategy: The name of the search strategy to use.
+ retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
+ llms: Optional dictionary of {name: llm} pairs to use as language models
Returns:
AdvancedSearchSystem: An instance of the configured AdvancedSearchSystem.
"""
+ # Register retrievers if provided
+ if retrievers:
+ from ..web_search_engines.retriever_registry import retriever_registry
+
+ retriever_registry.register_multiple(retrievers)
+ logger.info(
+ f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}"
+ )
+
# Get language model with custom temperature
llm = get_llm(
temperature=temperature,
@@ -87,6 +100,7 @@ def quick_summary(
query: str,
research_id: Optional[Union[int, str]] = None,
retrievers: Optional[Dict[str, Any]] = None,
+ llms: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""
@@ -96,6 +110,7 @@ def quick_summary(
query: The research query to analyze
research_id: Optional research ID (int or UUID string) for tracking metrics
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
+ llms: Optional dictionary of {name: llm} pairs to use as language models
**kwargs: Configuration for the search system. Will be forwarded to
`_init_search_system()`.
@@ -108,15 +123,6 @@ def quick_summary(
"""
logger.info("Generating quick summary for query: %s", query)
- # Register retrievers if provided
- if retrievers:
- from ..web_search_engines.retriever_registry import retriever_registry
-
- retriever_registry.register_multiple(retrievers)
- logger.info(
- f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}"
- )
-
# Generate a research_id if none provided
if research_id is None:
import uuid
@@ -167,6 +173,7 @@ def generate_report(
progress_callback: Optional[Callable] = None,
searches_per_section: int = 2,
retrievers: Optional[Dict[str, Any]] = None,
+ llms: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""
@@ -179,6 +186,7 @@ def generate_report(
searches_per_section: The number of searches to perform for each
section in the report.
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
+ llms: Optional dictionary of {name: llm} pairs to use as language models
Returns:
Dictionary containing the research report with keys:
@@ -187,16 +195,7 @@ def generate_report(
"""
logger.info("Generating comprehensive research report for query: %s", query)
- # Register retrievers if provided
- if retrievers:
- from ..web_search_engines.retriever_registry import retriever_registry
-
- retriever_registry.register_multiple(retrievers)
- logger.info(
- f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}"
- )
-
- system = _init_search_system(**kwargs)
+ system = _init_search_system(retrievers=retrievers, llms=llms, **kwargs)
# Set progress callback if provided
if progress_callback:
@@ -226,6 +225,7 @@ def detailed_research(
query: str,
research_id: Optional[Union[int, str]] = None,
retrievers: Optional[Dict[str, Any]] = None,
+ llms: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""
@@ -237,6 +237,7 @@ def detailed_research(
query: The research query to analyze
research_id: Optional research ID (int or UUID string) for tracking metrics
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
+ llms: Optional dictionary of {name: llm} pairs to use as language models
**kwargs: Configuration for the search system
Returns:
@@ -244,15 +245,6 @@ def detailed_research(
"""
logger.info("Performing detailed research for query: %s", query)
- # Register retrievers if provided
- if retrievers:
- from ..web_search_engines.retriever_registry import retriever_registry
-
- retriever_registry.register_multiple(retrievers)
- logger.info(
- f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}"
- )
-
# Generate a research_id if none provided
if research_id is None:
import uuid
@@ -274,7 +266,7 @@ def detailed_research(
set_search_context(search_context)
# Initialize system
- system = _init_search_system(**kwargs)
+ system = _init_search_system(retrievers=retrievers, llms=llms, **kwargs)
# Perform detailed research
results = system.analyze_topic(query)
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 1a1a3baacb..f9eac9cbfd 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -3,7 +3,7 @@ from functools import cache
from langchain_anthropic import ChatAnthropic
from langchain_community.llms import VLLM
-from langchain_core.language_models import FakeListChatModel
+from langchain_core.language_models import FakeListChatModel, BaseChatModel
from langchain_ollama import ChatOllama
from langchain_openai import ChatOpenAI
from loguru import logger
@@ -11,6 +11,7 @@ from loguru import logger
from ..utilities.db_utils import get_db_setting
from ..utilities.search_utilities import remove_think_tags
from ..utilities.url_utils import normalize_url
+from ..llm import get_llm_from_registry, is_llm_registered
# Valid provider options
VALID_PROVIDERS = [
@@ -227,6 +228,37 @@ def get_llm(
# Normalize provider: convert to lowercase
provider = provider.lower() if provider else None
+ # Check if this is a registered custom LLM first
+ if provider and is_llm_registered(provider):
+ logger.info(f"Using registered custom LLM: {provider}")
+ custom_llm = get_llm_from_registry(provider)
+
+ # Check if it's already a BaseChatModel instance
+ if isinstance(custom_llm, BaseChatModel):
+ # It's already an LLM instance, use it directly
+ llm_instance = custom_llm
+ elif callable(custom_llm):
+ # It's a factory function, call it with parameters
+ try:
+ llm_instance = custom_llm(
+ model_name=model_name,
+ temperature=temperature,
+ )
+ except Exception as e:
+ logger.exception(f"Error creating custom LLM instance: {e}")
+ raise
+ else:
+ raise ValueError(
+ f"Registered LLM {provider} is neither a BaseChatModel nor a callable factory"
+ )
+
+ return wrap_llm_without_think_tags(
+ llm_instance,
+ research_id=research_id,
+ provider=provider,
+ research_context=research_context,
+ )
+
# Validate provider
if provider not in VALID_PROVIDERS:
logger.error(f"Invalid provider in settings: {provider}")
diff --git a/src/local_deep_research/llm/__init__.py b/src/local_deep_research/llm/__init__.py
new file mode 100644
index 0000000000..622a4c5b29
--- /dev/null
+++ b/src/local_deep_research/llm/__init__.py
@@ -0,0 +1,19 @@
+"""LLM module for Local Deep Research."""
+
+from .llm_registry import (
+ register_llm,
+ unregister_llm,
+ get_llm_from_registry,
+ is_llm_registered,
+ list_registered_llms,
+ clear_llm_registry,
+)
+
+__all__ = [
+ "register_llm",
+ "unregister_llm",
+ "get_llm_from_registry",
+ "is_llm_registered",
+ "list_registered_llms",
+ "clear_llm_registry",
+]
diff --git a/src/local_deep_research/llm/llm_registry.py b/src/local_deep_research/llm/llm_registry.py
new file mode 100644
index 0000000000..41361ed58f
--- /dev/null
+++ b/src/local_deep_research/llm/llm_registry.py
@@ -0,0 +1,155 @@
+"""Registry for custom LangChain LLMs.
+
+This module provides a global registry for registering and managing custom LangChain
+LLMs that can be used with Local Deep Research.
+"""
+
+from typing import Dict, Optional, Union, Callable
+from langchain.chat_models.base import BaseChatModel
+import threading
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class LLMRegistry:
+ """Thread-safe registry for custom LangChain LLMs."""
+
+ def __init__(self):
+ self._llms: Dict[
+ str, Union[BaseChatModel, Callable[..., BaseChatModel]]
+ ] = {}
+ self._lock = threading.Lock()
+
+ def register(
+ self, name: str, llm: Union[BaseChatModel, Callable[..., BaseChatModel]]
+ ) -> None:
+ """Register a custom LLM.
+
+ Args:
+ name: Unique name for the LLM
+ llm: Either a BaseChatModel instance or a factory function that returns one
+ """
+ with self._lock:
+ if name in self._llms:
+ logger.warning(f"Overwriting existing LLM: {name}")
+ self._llms[name] = llm
+ logger.info(f"Registered custom LLM: {name}")
+
+ def unregister(self, name: str) -> None:
+ """Unregister a custom LLM.
+
+ Args:
+ name: Name of the LLM to unregister
+ """
+ with self._lock:
+ if name in self._llms:
+ del self._llms[name]
+ logger.info(f"Unregistered custom LLM: {name}")
+
+ def get(
+ self, name: str
+ ) -> Optional[Union[BaseChatModel, Callable[..., BaseChatModel]]]:
+ """Get a registered LLM.
+
+ Args:
+ name: Name of the LLM to retrieve
+
+ Returns:
+ The LLM instance/factory or None if not found
+ """
+ with self._lock:
+ return self._llms.get(name)
+
+ def is_registered(self, name: str) -> bool:
+ """Check if an LLM is registered.
+
+ Args:
+ name: Name to check
+
+ Returns:
+ True if registered, False otherwise
+ """
+ with self._lock:
+ return name in self._llms
+
+ def list_registered(self) -> list[str]:
+ """Get list of all registered LLM names.
+
+ Returns:
+ List of registered LLM names
+ """
+ with self._lock:
+ return list(self._llms.keys())
+
+ def clear(self) -> None:
+ """Clear all registered LLMs."""
+ with self._lock:
+ self._llms.clear()
+ logger.info("Cleared all registered custom LLMs")
+
+
+# Global registry instance
+_llm_registry = LLMRegistry()
+
+
+# Public API functions
+def register_llm(
+ name: str, llm: Union[BaseChatModel, Callable[..., BaseChatModel]]
+) -> None:
+ """Register a custom LLM in the global registry.
+
+ Args:
+ name: Unique name for the LLM
+ llm: Either a BaseChatModel instance or a factory function
+ """
+ _llm_registry.register(name, llm)
+
+
+def unregister_llm(name: str) -> None:
+ """Unregister a custom LLM from the global registry.
+
+ Args:
+ name: Name of the LLM to unregister
+ """
+ _llm_registry.unregister(name)
+
+
+def get_llm_from_registry(
+ name: str,
+) -> Optional[Union[BaseChatModel, Callable[..., BaseChatModel]]]:
+ """Get a registered LLM from the global registry.
+
+ Args:
+ name: Name of the LLM to retrieve
+
+ Returns:
+ The LLM instance/factory or None if not found
+ """
+ return _llm_registry.get(name)
+
+
+def is_llm_registered(name: str) -> bool:
+ """Check if an LLM is registered in the global registry.
+
+ Args:
+ name: Name to check
+
+ Returns:
+ True if registered, False otherwise
+ """
+ return _llm_registry.is_registered(name)
+
+
+def list_registered_llms() -> list[str]:
+ """Get list of all registered LLM names.
+
+ Returns:
+ List of registered LLM names
+ """
+ return _llm_registry.list_registered()
+
+
+def clear_llm_registry() -> None:
+ """Clear all registered LLMs from the global registry."""
+ _llm_registry.clear()
diff --git a/tests/test_llm/__init__.py b/tests/test_llm/__init__.py
new file mode 100644
index 0000000000..ed34f35683
--- /dev/null
+++ b/tests/test_llm/__init__.py
@@ -0,0 +1 @@
+"""Tests for custom LLM integration."""
diff --git a/tests/test_llm/run_llm_tests.sh b/tests/test_llm/run_llm_tests.sh
new file mode 100755
index 0000000000..22bc9b4fa3
--- /dev/null
+++ b/tests/test_llm/run_llm_tests.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+# Run all LLM integration tests
+
+echo "Running LLM Integration Tests"
+echo "============================="
+
+# Set up environment
+export PYTHONPATH=$PYTHONPATH:$(pwd)
+export LDR_USE_FALLBACK_LLM=true
+
+# Run registry tests
+echo -e "\n1. Running LLM Registry Tests..."
+python -m pytest tests/test_llm/test_llm_registry.py -v
+
+# Run integration tests
+echo -e "\n2. Running LLM Integration Tests..."
+python -m pytest tests/test_llm/test_llm_integration.py -v
+
+# Run API integration tests
+echo -e "\n3. Running API LLM Integration Tests..."
+python -m pytest tests/test_llm/test_api_llm_integration.py -v
+
+echo -e "\nAll LLM tests completed!"
diff --git a/tests/test_llm/test_api_llm_integration.py b/tests/test_llm/test_api_llm_integration.py
new file mode 100644
index 0000000000..404d681243
--- /dev/null
+++ b/tests/test_llm/test_api_llm_integration.py
@@ -0,0 +1,310 @@
+"""Tests for custom LLM integration with API functions."""
+
+import pytest
+from typing import List
+from unittest.mock import patch, MagicMock
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage, BaseMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from pydantic import Field
+
+from src.local_deep_research.api import (
+ quick_summary,
+ detailed_research,
+ generate_report,
+)
+from src.local_deep_research.llm import clear_llm_registry, is_llm_registered
+
+
+class CustomTestLLM(BaseChatModel):
+ """Custom LLM for API testing."""
+
+ identifier: str = Field(default="custom")
+ messages_received: List[List[BaseMessage]] = Field(default_factory=list)
+
+ def _generate(self, messages, **kwargs):
+ """Generate response and track messages."""
+ self.messages_received.append(messages)
+
+ response = f"Response from {self.identifier}: {len(messages)} messages"
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self):
+ return f"custom_{self.identifier}"
+
+
[email protected](autouse=True)
+def clear_registry():
+ """Clear the registry before and after each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+
+def mock_search_system():
+ """Create a mock search system."""
+ system = MagicMock()
+ system.analyze_topic.return_value = {
+ "current_knowledge": "Mock research summary",
+ "findings": ["Finding 1", "Finding 2"],
+ "iterations": 2,
+ "questions": {"iteration_1": ["Q1", "Q2"]},
+ "formatted_findings": "Formatted findings",
+ "all_links_of_system": ["http://example.com"],
+ }
+ system.model = MagicMock()
+ return system
+
+
+def test_quick_summary_with_custom_llm(mock_search_system):
+ """Test quick_summary with a custom LLM."""
+ llm = CustomTestLLM(identifier="quick")
+
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ mock_init.return_value = mock_search_system
+
+ result = quick_summary(
+ query="Test query",
+ llms={"my_llm": llm},
+ provider="my_llm",
+ temperature=0.5,
+ )
+
+ # Verify LLM was registered
+ assert is_llm_registered("my_llm")
+
+ # Verify result structure
+ assert "summary" in result
+ assert result["summary"] == "Mock research summary"
+ assert len(result["findings"]) == 2
+
+ # Verify init was called with correct provider
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "my_llm"
+ assert init_kwargs["temperature"] == 0.5
+
+
+def test_multiple_llms_registration(mock_search_system):
+ """Test registering multiple LLMs at once."""
+ llm1 = CustomTestLLM(identifier="llm1")
+ llm2 = CustomTestLLM(identifier="llm2")
+ llm3 = CustomTestLLM(identifier="llm3")
+
+ llms = {"model1": llm1, "model2": llm2, "model3": llm3}
+
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ mock_init.return_value = mock_search_system
+
+ quick_summary(
+ query="Test multiple LLMs",
+ llms=llms,
+ provider="model2", # Use the second one
+ )
+
+ # Verify all were registered
+ assert is_llm_registered("model1")
+ assert is_llm_registered("model2")
+ assert is_llm_registered("model3")
+
+ # Verify correct provider was used
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "model2"
+
+
+def test_detailed_research_with_custom_llm(mock_search_system):
+ """Test detailed_research with custom LLM."""
+ llm = CustomTestLLM(identifier="detailed")
+
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ mock_init.return_value = mock_search_system
+
+ result = detailed_research(
+ query="Detailed test query",
+ llms={"detail_llm": llm},
+ provider="detail_llm",
+ iterations=3,
+ research_id="test-123",
+ )
+
+ # Verify result
+ assert result["summary"] == "Mock research summary"
+ assert "findings" in result
+
+ # Verify research context was set
+ with patch(
+ "src.local_deep_research.metrics.search_tracker.set_search_context"
+ ) as mock_context:
+ detailed_research(
+ query="Context test",
+ llms={"ctx_llm": llm},
+ provider="ctx_llm",
+ research_id="ctx-123",
+ )
+
+ # Check context was set with correct research_id
+ context_call = mock_context.call_args[0][0]
+ assert context_call["research_id"] == "ctx-123"
+ assert context_call["research_mode"] == "detailed"
+
+
+def test_generate_report_with_custom_llm():
+ """Test generate_report with custom LLM."""
+ llm = CustomTestLLM(identifier="report")
+
+ # Patch the entire flow to avoid real execution
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ # Set up the mock system with a properly mocked model
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "current_knowledge": "Initial findings",
+ "findings": ["Finding 1", "Finding 2"],
+ }
+
+ # Mock the model's invoke method properly
+ mock_model = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "Report structure"
+ mock_model.invoke.return_value = mock_response
+ mock_system.model = mock_model
+
+ mock_init.return_value = mock_system
+
+ # Call the function
+ result = generate_report(
+ query="Report test query",
+ llms={"report_llm": llm},
+ provider="report_llm",
+ searches_per_section=3,
+ )
+
+ # Verify custom LLM was registered
+ assert is_llm_registered("report_llm")
+
+ # Verify the init system was called with our provider
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "report_llm"
+
+ # Verify we got a report back
+ assert "content" in result
+ assert isinstance(result["content"], str)
+
+
+def test_llm_factory_in_api():
+ """Test using a factory function with API."""
+ factory_calls = []
+
+ def create_custom_llm(model_name=None, temperature=0.7, **kwargs):
+ factory_calls.append(
+ {
+ "model_name": model_name,
+ "temperature": temperature,
+ "extra": kwargs,
+ }
+ )
+ return CustomTestLLM(identifier=f"factory-{model_name}")
+
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "current_knowledge": "Factory test",
+ "findings": [],
+ "iterations": 1,
+ "questions": {},
+ "formatted_findings": "",
+ "all_links_of_system": [],
+ }
+ mock_init.return_value = mock_system
+
+ # Call quick_summary with factory
+ quick_summary(
+ query="Factory test",
+ llms={"factory_llm": create_custom_llm},
+ provider="factory_llm",
+ model_name="test-v1",
+ temperature=0.2,
+ )
+
+ # Verify the factory was registered
+ assert is_llm_registered("factory_llm")
+
+ # Verify init was called with correct provider
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "factory_llm"
+ assert init_kwargs["model_name"] == "test-v1"
+ assert init_kwargs["temperature"] == 0.2
+
+
+def test_combining_custom_llms_and_retrievers():
+ """Test using both custom LLMs and retrievers."""
+ llm = CustomTestLLM(identifier="combined")
+ mock_retriever = MagicMock()
+
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ with patch(
+ "src.local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ ) as mock_reg:
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "current_knowledge": "Combined test"
+ }
+ mock_init.return_value = mock_system
+
+ quick_summary(
+ query="Combined test",
+ llms={"custom_llm": llm},
+ retrievers={"custom_retriever": mock_retriever},
+ provider="custom_llm",
+ search_tool="custom_retriever",
+ )
+
+ # Verify both were registered
+ assert is_llm_registered("custom_llm")
+ mock_reg.register_multiple.assert_called_once()
+
+ # Verify correct parameters passed
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "custom_llm"
+ assert init_kwargs["search_tool"] == "custom_retriever"
+
+
+def test_api_without_custom_llms():
+ """Test that API still works without custom LLMs."""
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "current_knowledge": "No custom LLM"
+ }
+ mock_init.return_value = mock_system
+
+ # Call without llms parameter
+ result = quick_summary(
+ query="No custom LLM test",
+ provider="ollama", # Use built-in provider
+ model_name="llama2",
+ )
+
+ # Should work normally
+ assert "summary" in result
+
+ # Verify no custom LLMs were registered
+ init_kwargs = mock_init.call_args[1]
+ assert init_kwargs["provider"] == "ollama"
+ assert init_kwargs["model_name"] == "llama2"
diff --git a/tests/test_llm/test_llm_benchmarks.py b/tests/test_llm/test_llm_benchmarks.py
new file mode 100644
index 0000000000..00429e7e70
--- /dev/null
+++ b/tests/test_llm/test_llm_benchmarks.py
@@ -0,0 +1,258 @@
+"""Tests for custom LLM integration with benchmarking system."""
+
+import pytest
+from unittest.mock import patch
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage, BaseMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from pydantic import Field
+from typing import List
+
+from src.local_deep_research.llm import register_llm, clear_llm_registry
+
+
+class BenchmarkLLM(BaseChatModel):
+ """LLM designed for benchmark testing."""
+
+ correct_answers: dict = Field(default_factory=dict)
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Generate responses based on predefined correct answers."""
+ query = messages[-1].content if messages else ""
+
+ # Check if we have a predefined answer
+ for key, answer in self.correct_answers.items():
+ if key.lower() in query.lower():
+ message = AIMessage(content=answer)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ # Default response
+ message = AIMessage(content="I don't know")
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "benchmark"
+
+
[email protected](autouse=True)
+def clear_registry():
+ """Clear the registry before and after each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+
+def test_custom_llm_with_benchmarks():
+ """Test that custom LLMs work with the benchmark system."""
+ # Create a benchmark LLM with some correct answers
+ benchmark_llm = BenchmarkLLM(
+ correct_answers={
+ "capital of France": "Paris",
+ "2+2": "4",
+ "meaning of life": "42",
+ }
+ )
+
+ register_llm("benchmark_llm", benchmark_llm)
+
+ # Mock the benchmark flow
+ with patch(
+ "src.local_deep_research.config.llm_config.get_llm"
+ ) as mock_get_llm:
+ # Return our benchmark LLM when requested
+ mock_get_llm.return_value = benchmark_llm
+
+ # Simulate benchmark questions
+ questions = [
+ ("What is the capital of France?", "Paris"),
+ ("What is 2+2?", "4"),
+ ("What is the meaning of life?", "42"),
+ ("Unknown question", "I don't know"),
+ ]
+
+ for question, expected in questions:
+ from langchain_core.messages import HumanMessage
+
+ result = benchmark_llm._generate([HumanMessage(content=question)])
+ assert result.generations[0].message.content == expected
+
+
+def test_benchmark_llm_metrics():
+ """Test that custom LLMs properly track metrics for benchmarks."""
+
+ class MetricsLLM(BaseChatModel):
+ """LLM that tracks metrics."""
+
+ total_tokens: int = Field(default=0)
+ call_count: int = Field(default=0)
+
+ def _generate(
+ self, messages: List[BaseMessage], **kwargs
+ ) -> ChatResult:
+ self.call_count += 1
+ response = f"Response {self.call_count}"
+ self.total_tokens += len(response.split())
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(
+ message=message,
+ generation_info={"token_count": len(response.split())},
+ )
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "metrics"
+
+ metrics_llm = MetricsLLM()
+ register_llm("metrics_llm", metrics_llm)
+
+ # Simulate multiple benchmark runs
+ from langchain_core.messages import HumanMessage
+
+ for i in range(5):
+ metrics_llm._generate([HumanMessage(content=f"Query {i}")])
+
+ assert metrics_llm.call_count == 5
+ assert metrics_llm.total_tokens == 10 # "Response X" = 2 tokens each
+
+
+def test_custom_llm_accuracy_scoring():
+ """Test custom LLMs with accuracy scoring."""
+
+ class ScoringLLM(BaseChatModel):
+ """LLM that returns scores with answers."""
+
+ def _generate(
+ self, messages: List[BaseMessage], **kwargs
+ ) -> ChatResult:
+ query = messages[-1].content if messages else ""
+
+ # Return answer with confidence score
+ if "easy" in query.lower():
+ response = "Easy answer"
+ confidence = 1.0
+ elif "hard" in query.lower():
+ response = "Hard answer"
+ confidence = 0.5
+ else:
+ response = "Unknown"
+ confidence = 0.1
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(
+ message=message, generation_info={"confidence": confidence}
+ )
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "scoring"
+
+ scoring_llm = ScoringLLM()
+ register_llm("scoring_llm", scoring_llm)
+
+ # Test different query types
+ from langchain_core.messages import HumanMessage
+
+ easy_result = scoring_llm._generate([HumanMessage(content="Easy question")])
+ assert easy_result.generations[0].generation_info["confidence"] == 1.0
+
+ hard_result = scoring_llm._generate([HumanMessage(content="Hard question")])
+ assert hard_result.generations[0].generation_info["confidence"] == 0.5
+
+ unknown_result = scoring_llm._generate(
+ [HumanMessage(content="Random question")]
+ )
+ assert unknown_result.generations[0].generation_info["confidence"] == 0.1
+
+
+def test_benchmark_with_custom_llm_factory():
+ """Test benchmarking with LLM factories."""
+ factory_calls = []
+
+ def create_benchmark_llm(model_name=None, temperature=0.7, **kwargs):
+ """Factory that creates benchmark-optimized LLMs."""
+ factory_calls.append(
+ {"model_name": model_name, "temperature": temperature}
+ )
+
+ # Return different LLMs based on model name
+ if model_name == "accurate":
+ return BenchmarkLLM(correct_answers={"test": "correct"})
+ else:
+ return BenchmarkLLM(correct_answers={})
+
+ register_llm("benchmark_factory", create_benchmark_llm)
+
+ # Simulate benchmark configuration testing
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ # Test with accurate model
+ with patch(
+ "src.local_deep_research.config.llm_config.is_llm_registered",
+ return_value=True,
+ ):
+ with patch(
+ "src.local_deep_research.config.llm_config.get_llm_from_registry",
+ return_value=create_benchmark_llm,
+ ):
+ from src.local_deep_research.config.llm_config import get_llm
+
+ accurate_llm = get_llm(
+ provider="benchmark_factory",
+ model_name="accurate",
+ temperature=0.1,
+ )
+
+ # Should create the accurate version
+ from langchain_core.messages import HumanMessage
+
+ result = accurate_llm._generate(
+ [HumanMessage(content="test question")]
+ )
+ assert result.generations[0].message.content == "correct"
+
+
+def test_benchmark_comparison_with_custom_llms():
+ """Test comparing multiple custom LLMs in benchmarks."""
+ # Create multiple LLMs with different characteristics
+ fast_llm = BenchmarkLLM(correct_answers={"quick": "fast response"})
+ accurate_llm = BenchmarkLLM(
+ correct_answers={
+ "quick": "fast response",
+ "complex": "detailed accurate response",
+ }
+ )
+
+ register_llm("fast_llm", fast_llm)
+ register_llm("accurate_llm", accurate_llm)
+
+ # Simulate benchmark comparison
+ test_queries = ["quick question", "complex problem"]
+
+ results = {}
+ for llm_name, llm in [
+ ("fast_llm", fast_llm),
+ ("accurate_llm", accurate_llm),
+ ]:
+ results[llm_name] = []
+ for query in test_queries:
+ from langchain_core.messages import HumanMessage
+
+ response = llm._generate([HumanMessage(content=query)])
+ results[llm_name].append(response.generations[0].message.content)
+
+ # Fast LLM should only answer one correctly
+ assert results["fast_llm"][0] == "fast response"
+ assert results["fast_llm"][1] == "I don't know"
+
+ # Accurate LLM should answer both
+ assert results["accurate_llm"][0] == "fast response"
+ assert results["accurate_llm"][1] == "detailed accurate response"
diff --git a/tests/test_llm/test_llm_edge_cases.py b/tests/test_llm/test_llm_edge_cases.py
new file mode 100644
index 0000000000..6099355529
--- /dev/null
+++ b/tests/test_llm/test_llm_edge_cases.py
@@ -0,0 +1,385 @@
+"""Tests for edge cases and advanced scenarios in custom LLM integration."""
+
+import pytest
+import asyncio
+from typing import List, Optional, Any, Iterator
+from unittest.mock import patch
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage, BaseMessage, AIMessageChunk
+from langchain_core.outputs import (
+ ChatResult,
+ ChatGeneration,
+ ChatGenerationChunk,
+)
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+ AsyncCallbackManagerForLLMRun,
+)
+from pydantic import Field
+
+from src.local_deep_research.llm import (
+ register_llm,
+ clear_llm_registry,
+ get_llm_from_registry,
+)
+from src.local_deep_research.config.llm_config import get_llm
+
+
+class StreamingLLM(BaseChatModel):
+ """LLM that supports streaming."""
+
+ chunks: List[str] = Field(
+ default_factory=lambda: [
+ "Hello",
+ " world",
+ " from",
+ " streaming",
+ " LLM",
+ ]
+ )
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Generate non-streaming response."""
+ full_response = "".join(self.chunks)
+ message = AIMessage(content=full_response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream response chunks."""
+ for chunk in self.chunks:
+ yield ChatGenerationChunk(message=AIMessageChunk(content=chunk))
+
+ @property
+ def _llm_type(self) -> str:
+ return "streaming"
+
+
+class AsyncLLM(BaseChatModel):
+ """LLM that supports async operations."""
+
+ response: str = Field(default="Async response")
+ delay: float = Field(default=0.1)
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Sync generation (fallback)."""
+ message = AIMessage(content=self.response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Async generation."""
+ await asyncio.sleep(self.delay) # Simulate async work
+ message = AIMessage(content=f"Async: {self.response}")
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "async"
+
+
+class BrokenLLM(BaseChatModel):
+ """LLM that raises errors."""
+
+ error_message: str = Field(default="LLM is broken")
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Always raises an error."""
+ raise RuntimeError(self.error_message)
+
+ @property
+ def _llm_type(self) -> str:
+ return "broken"
+
+
+class SlowLLM(BaseChatModel):
+ """LLM that responds slowly."""
+
+ response: str = Field(default="Slow response")
+ delay: float = Field(default=2.0)
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Generate response with delay."""
+ import time
+
+ time.sleep(self.delay)
+ message = AIMessage(content=self.response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "slow"
+
+
+class MalformedResponseLLM(BaseChatModel):
+ """LLM that returns malformed responses."""
+
+ def _generate(self, messages: List[BaseMessage], **kwargs) -> ChatResult:
+ """Return invalid response structure."""
+ # Return a ChatResult with no generations
+ return ChatResult(generations=[])
+
+ @property
+ def _llm_type(self) -> str:
+ return "malformed"
+
+
[email protected](autouse=True)
+def clear_registry():
+ """Clear the registry before and after each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+
+def test_streaming_llm_registration():
+ """Test registering an LLM with streaming support."""
+ streaming_llm = StreamingLLM()
+ register_llm("streaming", streaming_llm)
+
+ # Get the LLM through the system
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ llm = get_llm(provider="streaming")
+ assert isinstance(llm, StreamingLLM)
+
+ # Test that streaming works
+ chunks = list(llm._stream([]))
+ assert len(chunks) == 5
+ assert all(hasattr(chunk, "message") for chunk in chunks)
+
+
+async def test_async_llm_operations():
+ """Test async LLM operations."""
+ async_llm = AsyncLLM(delay=0.05)
+ register_llm("async", async_llm)
+
+ # Test async generation
+ result = await async_llm._agenerate([])
+ assert result.generations[0].message.content == "Async: Async response"
+
+
+def test_broken_llm_error_handling():
+ """Test handling of LLMs that raise errors."""
+ broken_llm = BrokenLLM(error_message="Test error")
+ register_llm("broken", broken_llm)
+
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ llm = get_llm(provider="broken")
+
+ # Should raise the error when trying to generate
+ with pytest.raises(RuntimeError, match="Test error"):
+ llm._generate([])
+
+
+def test_malformed_response_handling():
+ """Test handling of LLMs that return malformed responses."""
+ malformed_llm = MalformedResponseLLM()
+ register_llm("malformed", malformed_llm)
+
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ llm = get_llm(provider="malformed")
+ result = llm._generate([])
+
+ # Should return empty generations
+ assert len(result.generations) == 0
+
+
+def test_concurrent_llm_registration():
+ """Test concurrent registration and usage of LLMs."""
+ import threading
+
+ errors = []
+
+ def register_and_use(name: str, response: str):
+ try:
+ llm = SlowLLM(response=response, delay=0.01)
+ register_llm(name, llm)
+
+ # Try to use it
+ retrieved = get_llm_from_registry(name)
+ assert retrieved is not None
+ except Exception as e:
+ errors.append(e)
+
+ # Start multiple threads
+ threads = []
+ for i in range(10):
+ t = threading.Thread(
+ target=register_and_use, args=(f"llm_{i}", f"Response {i}")
+ )
+ threads.append(t)
+ t.start()
+
+ # Wait for all to complete
+ for t in threads:
+ t.join()
+
+ assert len(errors) == 0
+
+ # Verify all were registered
+ for i in range(10):
+ assert get_llm_from_registry(f"llm_{i}") is not None
+
+
+def test_provider_name_normalization():
+ """Test that provider names are normalized correctly."""
+ llm = SlowLLM()
+
+ # Register with mixed case - the registry stores as-is
+ register_llm("MixedCase", llm)
+
+ # The registry is case-sensitive, so we need to register with lowercase too
+ register_llm("mixedcase", llm)
+
+ # Should be retrievable with lowercase
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ # The provider name should be normalized to lowercase
+ result = get_llm(provider="mixedcase")
+ assert isinstance(result, SlowLLM)
+
+
+def test_factory_with_invalid_signature():
+ """Test factory functions with invalid signatures."""
+
+ def bad_factory():
+ # Missing required parameters
+ return SlowLLM()
+
+ register_llm("bad_factory", bad_factory)
+
+ # Should raise error when trying to use with parameters
+ with pytest.raises(TypeError):
+ get_llm(provider="bad_factory", model_name="test", temperature=0.5)
+
+
+def test_llm_memory_cleanup():
+ """Test that LLMs are properly cleaned up."""
+ import gc
+ import weakref
+
+ # Create an LLM and register it
+ llm = SlowLLM()
+ weak_ref = weakref.ref(llm)
+ register_llm("memory_test", llm)
+
+ # Delete the original reference
+ del llm
+
+ # Force garbage collection
+ gc.collect()
+
+ # The LLM should still exist because registry holds a reference
+ assert weak_ref() is not None
+
+ # Clear the registry
+ clear_llm_registry()
+ gc.collect()
+
+ # Now it should be garbage collected
+ assert weak_ref() is None
+
+
+def test_llm_with_custom_attributes():
+ """Test LLMs with custom attributes and methods."""
+
+ class CustomLLM(BaseChatModel):
+ custom_attr: str = Field(default="custom")
+
+ def custom_method(self):
+ return "custom_result"
+
+ def _generate(
+ self, messages: List[BaseMessage], **kwargs
+ ) -> ChatResult:
+ message = AIMessage(content=f"Custom: {self.custom_attr}")
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "custom_attrs"
+
+ custom_llm = CustomLLM(custom_attr="test_value")
+ register_llm("custom_attrs", custom_llm)
+
+ retrieved = get_llm_from_registry("custom_attrs")
+ assert retrieved.custom_attr == "test_value"
+ assert retrieved.custom_method() == "custom_result"
+
+
+def test_llm_state_persistence():
+ """Test that LLM state persists across calls."""
+
+ class StatefulLLM(BaseChatModel):
+ call_count: int = Field(default=0)
+ history: List[str] = Field(default_factory=list)
+
+ def _generate(
+ self, messages: List[BaseMessage], **kwargs
+ ) -> ChatResult:
+ self.call_count += 1
+ query = messages[-1].content if messages else "empty"
+ self.history.append(query)
+
+ message = AIMessage(content=f"Call {self.call_count}: {query}")
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "stateful"
+
+ stateful_llm = StatefulLLM()
+ register_llm("stateful", stateful_llm)
+
+ # Use it multiple times
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ llm1 = get_llm(provider="stateful")
+ llm2 = get_llm(provider="stateful")
+
+ # Should be the same instance
+ assert llm1 is llm2
+
+ # State should persist
+ from langchain_core.messages import HumanMessage
+
+ llm1._generate([HumanMessage(content="First")])
+ llm2._generate([HumanMessage(content="Second")])
+
+ assert stateful_llm.call_count == 2
+ assert stateful_llm.history == ["First", "Second"]
diff --git a/tests/test_llm/test_llm_integration.py b/tests/test_llm/test_llm_integration.py
new file mode 100644
index 0000000000..7d27b42665
--- /dev/null
+++ b/tests/test_llm/test_llm_integration.py
@@ -0,0 +1,226 @@
+"""Tests for LLM integration with the broader system."""
+
+import pytest
+from typing import List, Optional
+from unittest.mock import patch, MagicMock
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage, BaseMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+from pydantic import Field
+
+from src.local_deep_research.llm import register_llm, clear_llm_registry
+from src.local_deep_research.config.llm_config import get_llm
+
+
+class TestLLM(BaseChatModel):
+ """Test LLM implementation."""
+
+ response_text: str = Field(default="Test response")
+ call_count: int = Field(default=0)
+ last_messages: Optional[List[BaseMessage]] = Field(default=None)
+
+ def _generate(self, messages, **kwargs):
+ """Generate test response."""
+ self.call_count += 1
+ self.last_messages = messages
+
+ message = AIMessage(content=self.response_text)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self):
+ return "test"
+
+
[email protected](autouse=True)
+def clear_registry():
+ """Clear the registry before and after each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+
+def test_get_llm_with_custom_provider():
+ """Test that get_llm returns custom LLMs when registered."""
+ # Register a custom LLM
+ custom_llm = TestLLM(response_text="Custom response")
+ register_llm("custom_provider", custom_llm)
+
+ # Get LLM with custom provider
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ # Configure mock to return the LLM passed to it
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ get_llm(provider="custom_provider", temperature=0.5)
+
+ # Verify wrap was called with our custom LLM
+ assert mock_wrap.called
+ assert mock_wrap.call_args[0][0] is custom_llm
+
+
+def test_get_llm_with_factory_function():
+ """Test that get_llm works with factory functions."""
+ # Create a factory that tracks calls
+ factory_calls = []
+
+ def llm_factory(model_name=None, temperature=0.7, **kwargs):
+ factory_calls.append(
+ {
+ "model_name": model_name,
+ "temperature": temperature,
+ "kwargs": kwargs,
+ }
+ )
+ return TestLLM(response_text=f"Factory LLM: {model_name}")
+
+ # Register the factory
+ register_llm("factory_provider", llm_factory)
+
+ # Get LLM with factory provider
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ get_llm(
+ provider="factory_provider",
+ model_name="test-model",
+ temperature=0.3,
+ )
+
+ # Verify factory was called with correct parameters
+ assert len(factory_calls) == 1
+ assert factory_calls[0]["model_name"] == "test-model"
+ assert factory_calls[0]["temperature"] == 0.3
+
+
+def test_get_llm_falls_back_to_builtin():
+ """Test that get_llm falls back to built-in providers when custom not found."""
+ # Don't register any custom LLM
+
+ # Mock the built-in provider check
+ with patch(
+ "src.local_deep_research.config.llm_config.is_ollama_available",
+ return_value=False,
+ ):
+ with patch(
+ "src.local_deep_research.config.llm_config.get_fallback_model"
+ ) as mock_fallback:
+ mock_fallback.return_value = TestLLM(response_text="Fallback")
+
+ # Try to get Ollama (which is not available)
+ get_llm(provider="ollama", model_name="llama2")
+
+ # Should fall back
+ assert mock_fallback.called
+
+
+def test_api_integration_with_custom_llm():
+ """Test that API functions work with custom LLMs."""
+ from src.local_deep_research.api import quick_summary
+
+ # Create a custom LLM
+ custom_llm = TestLLM(response_text="API test response")
+
+ # Mock the necessary components
+ with patch(
+ "src.local_deep_research.api.research_functions._init_search_system"
+ ) as mock_init:
+ # Create a mock search system
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "current_knowledge": "Test summary",
+ "findings": [],
+ "iterations": 1,
+ "questions": {},
+ "formatted_findings": "Test findings",
+ "all_links_of_system": [],
+ }
+ mock_init.return_value = mock_system
+
+ # Call quick_summary with custom LLM
+ result = quick_summary(
+ query="Test query",
+ llms={"test_llm": custom_llm},
+ provider="test_llm",
+ )
+
+ # Verify the LLM was registered and used
+ assert result["summary"] == "Test summary"
+ assert mock_init.called
+
+ # Check that provider was passed correctly
+ call_kwargs = mock_init.call_args[1]
+ assert call_kwargs.get("provider") == "test_llm"
+
+
+def test_multiple_custom_llms():
+ """Test registering and using multiple custom LLMs."""
+ llm1 = TestLLM(response_text="Response 1")
+ llm2 = TestLLM(response_text="Response 2")
+
+ register_llm("provider1", llm1)
+ register_llm("provider2", llm2)
+
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ # Get first LLM
+ get_llm(provider="provider1")
+ assert mock_wrap.call_args[0][0] is llm1
+
+ # Get second LLM
+ get_llm(provider="provider2")
+ assert mock_wrap.call_args[0][0] is llm2
+
+
+def test_custom_llm_with_research_context():
+ """Test that custom LLMs receive research context properly."""
+ custom_llm = TestLLM()
+ register_llm("context_test", custom_llm)
+
+ research_id = "test-research-123"
+ research_context = {"query": "test", "mode": "quick"}
+
+ with patch(
+ "src.local_deep_research.config.llm_config.wrap_llm_without_think_tags"
+ ) as mock_wrap:
+ mock_wrap.side_effect = lambda llm, **kwargs: llm
+
+ get_llm(
+ provider="context_test",
+ research_id=research_id,
+ research_context=research_context,
+ )
+
+ # Verify context was passed to wrapper
+ wrap_kwargs = mock_wrap.call_args[1]
+ assert wrap_kwargs["research_id"] == research_id
+ assert wrap_kwargs["research_context"] == research_context
+ assert wrap_kwargs["provider"] == "context_test"
+
+
+def test_factory_error_handling():
+ """Test error handling when factory fails."""
+
+ def failing_factory(**kwargs):
+ raise ValueError("Factory error")
+
+ register_llm("failing_factory", failing_factory)
+
+ # Should raise the factory error
+ with pytest.raises(ValueError, match="Factory error"):
+ get_llm(provider="failing_factory")
+
+
+def test_invalid_provider_after_checking_registry():
+ """Test that invalid provider error is raised for non-existent providers."""
+ # Don't register anything
+
+ with pytest.raises(ValueError, match="Invalid provider: fake_provider"):
+ get_llm(provider="fake_provider")
diff --git a/tests/test_llm/test_llm_registry.py b/tests/test_llm/test_llm_registry.py
new file mode 100644
index 0000000000..55d53a9b48
--- /dev/null
+++ b/tests/test_llm/test_llm_registry.py
@@ -0,0 +1,203 @@
+"""Tests for the LLM registry module."""
+
+import pytest
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage
+from langchain_core.outputs import ChatResult, ChatGeneration
+
+from src.local_deep_research.llm import (
+ register_llm,
+ unregister_llm,
+ get_llm_from_registry,
+ is_llm_registered,
+ list_registered_llms,
+ clear_llm_registry,
+)
+
+
+class MockLLM(BaseChatModel):
+ """Mock LLM for testing."""
+
+ name: str = "mock"
+
+ def _generate(self, messages, **kwargs):
+ """Generate mock response."""
+ message = AIMessage(content=f"Mock response from {self.name}")
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self):
+ return "mock"
+
+
[email protected](autouse=True)
+def clear_registry():
+ """Clear the registry before and after each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+
+def test_register_llm_instance():
+ """Test registering an LLM instance."""
+ llm = MockLLM(name="test-llm")
+
+ # Register the LLM
+ register_llm("test_model", llm)
+
+ # Check it's registered
+ assert is_llm_registered("test_model")
+ assert "test_model" in list_registered_llms()
+
+ # Retrieve it
+ retrieved = get_llm_from_registry("test_model")
+ assert retrieved is llm
+
+
+def test_register_llm_factory():
+ """Test registering an LLM factory function."""
+
+ def create_llm(**kwargs):
+ return MockLLM(name="factory-llm", **kwargs)
+
+ # Register the factory
+ register_llm("factory_model", create_llm)
+
+ # Check it's registered
+ assert is_llm_registered("factory_model")
+
+ # Retrieve the factory
+ factory = get_llm_from_registry("factory_model")
+ assert callable(factory)
+
+ # Create an LLM from the factory
+ llm = factory()
+ assert isinstance(llm, MockLLM)
+ assert llm.name == "factory-llm"
+
+
+def test_unregister_llm():
+ """Test unregistering an LLM."""
+ llm = MockLLM()
+ register_llm("temp_model", llm)
+
+ # Verify it's registered
+ assert is_llm_registered("temp_model")
+
+ # Unregister it
+ unregister_llm("temp_model")
+
+ # Verify it's gone
+ assert not is_llm_registered("temp_model")
+ assert "temp_model" not in list_registered_llms()
+ assert get_llm_from_registry("temp_model") is None
+
+
+def test_multiple_llms():
+ """Test registering multiple LLMs."""
+ llm1 = MockLLM(name="llm1")
+ llm2 = MockLLM(name="llm2")
+
+ register_llm("model1", llm1)
+ register_llm("model2", llm2)
+
+ # Check both are registered
+ registered = list_registered_llms()
+ assert len(registered) == 2
+ assert "model1" in registered
+ assert "model2" in registered
+
+ # Retrieve them
+ assert get_llm_from_registry("model1") is llm1
+ assert get_llm_from_registry("model2") is llm2
+
+
+def test_overwrite_existing():
+ """Test overwriting an existing LLM."""
+ llm1 = MockLLM(name="original")
+ llm2 = MockLLM(name="replacement")
+
+ # Register first LLM
+ register_llm("model", llm1)
+ assert get_llm_from_registry("model") is llm1
+
+ # Overwrite with second LLM
+ register_llm("model", llm2)
+ assert get_llm_from_registry("model") is llm2
+
+
+def test_clear_registry():
+ """Test clearing all registered LLMs."""
+ # Register multiple LLMs
+ register_llm("model1", MockLLM())
+ register_llm("model2", MockLLM())
+ register_llm("model3", MockLLM())
+
+ assert len(list_registered_llms()) == 3
+
+ # Clear the registry
+ clear_llm_registry()
+
+ # Verify all are gone
+ assert len(list_registered_llms()) == 0
+ assert not is_llm_registered("model1")
+ assert not is_llm_registered("model2")
+ assert not is_llm_registered("model3")
+
+
+def test_thread_safety():
+ """Test that registry operations are thread-safe."""
+ import threading
+ import time
+
+ results = []
+ errors = []
+
+ def register_many():
+ """Register many LLMs in a thread."""
+ try:
+ for i in range(100):
+ register_llm(f"thread_model_{i}", MockLLM(name=f"thread-{i}"))
+ results.append("register_complete")
+ except Exception as e:
+ errors.append(e)
+
+ def read_many():
+ """Read from registry in a thread."""
+ try:
+ for _ in range(100):
+ _ = list_registered_llms()
+ time.sleep(0.001) # Small delay to increase contention
+ results.append("read_complete")
+ except Exception as e:
+ errors.append(e)
+
+ # Start multiple threads
+ threads = []
+ for _ in range(3):
+ threads.append(threading.Thread(target=register_many))
+ threads.append(threading.Thread(target=read_many))
+
+ for t in threads:
+ t.start()
+
+ for t in threads:
+ t.join()
+
+ # Check no errors occurred
+ assert len(errors) == 0
+ assert len(results) == 6 # 3 register + 3 read threads
+
+
+def test_get_nonexistent():
+ """Test getting a non-existent LLM."""
+ assert get_llm_from_registry("does_not_exist") is None
+ assert not is_llm_registered("does_not_exist")
+
+
+def test_empty_registry():
+ """Test operations on empty registry."""
+ assert list_registered_llms() == []
+ assert not is_llm_registered("any_model")
+ assert get_llm_from_registry("any_model") is None