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.

merged with github

LearningCircuitb2e8b8bf6964
diff --cc data/config/.env.template
index 0000000000,0000000000..977acab960
new file mode 100644
--- /dev/null
+++ b/data/config/.env.template
@@@ -1,0 -1,0 +1,1 @@@
++# Add your environment variables here
diff --cc data/config/.secrets.toml
index 0000000000,0000000000..1dfd65e16c
new file mode 100644
--- /dev/null
+++ b/data/config/.secrets.toml
@@@ -1,0 -1,0 +1,9 @@@
++
++ # ANTHROPIC_API_KEY = "your-api-key-here"
++ # OPENAI_API_KEY = "your-openai-key-here"
++ # GOOGLE_API_KEY = "your-google-key-here"
++ # SERP_API_KEY = "your-api-key-here"
++ # GUARDIAN_API_KEY = "your-api-key-here"
++ # GOOGLE_PSE_API_KEY = "your-google-api-key-here"
++ # GOOGLE_PSE_ENGINE_ID = "your-programmable-search-engine-id-here"
++
diff --cc data/config/llm_config.py
index 0000000000,0000000000..ae4bf73415
new file mode 100644
--- /dev/null
+++ b/data/config/llm_config.py
@@@ -1,0 -1,0 +1,286 @@@
++"""
++LLM configuration for Local Deep Research.
++
++This file controls which language models are available and how they're configured.
++You can customize model selection, parameters, and fallbacks here.
++"""
++
++from langchain_anthropic import ChatAnthropic
++from langchain_openai import ChatOpenAI
++from langchain_ollama import ChatOllama
++from langchain_community.llms import VLLM
++from local_deep_research.config import settings
++import os
++import logging
++
++# Initialize environment
++logger = logging.getLogger(__name__)
++
++# Valid provider options
++VALID_PROVIDERS = ["ollama", "openai", "anthropic", "vllm", "openai_endpoint", "lmstudio", "llamacpp", "none"]
++
++# ================================
++# LLM FUNCTIONS
++# ================================
++
++def get_llm(model_name=None, temperature=None, provider=None):
++ """
++ Get LLM instance based on model name and provider.
++
++ Args:
++ model_name: Name of the model to use (if None, uses settings.llm.model)
++ temperature: Model temperature (if None, uses settings.llm.temperature)
++ provider: Provider to use (if None, uses settings.llm.provider)
++
++ Returns:
++ A LangChain LLM instance
++ """
++ # Use settings values for parameters if not provided
++ if model_name is None:
++ model_name = settings.llm.model
++
++ if temperature is None:
++ temperature = settings.llm.temperature
++
++ if provider is None:
++ provider = settings.llm.provider.lower()
++ if provider not in VALID_PROVIDERS:
++ logger.error(f"Invalid provider in settings: {provider}")
++ raise ValueError(f"Invalid provider: {provider}. Must be one of: {VALID_PROVIDERS}")
++
++ # Common parameters for all models
++ common_params = {
++ "temperature": temperature,
++ "max_tokens": settings.llm.max_tokens,
++ }
++
++ # Handle different providers
++ if provider == "anthropic":
++ api_key = settings.get('ANTHROPIC_API_KEY', '')
++ if not api_key:
++ logger.warning("ANTHROPIC_API_KEY not found. Falling back to default model.")
++ return get_fallback_model(temperature)
++
++ return ChatAnthropic(
++ model=model_name, anthropic_api_key=api_key, **common_params
++ )
++
++ elif provider == "openai":
++ api_key = settings.get('OPENAI_API_KEY', '')
++ if not api_key:
++ logger.warning("OPENAI_API_KEY not found. Falling back to default model.")
++ return get_fallback_model(temperature)
++
++ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)
++
++ elif provider == "openai_endpoint":
++ api_key = settings.get('OPENAI_ENDPOINT_API_KEY', '')
++
++ if not api_key:
++ logger.warning("OPENAI_ENDPOINT_API_KEY not found. Falling back to default model.")
++ return get_fallback_model(temperature)
++
++ # Get endpoint URL from settings
++ openai_endpoint_url = settings.llm.openai_endpoint_url
++
++ return ChatOpenAI(
++ model=model_name,
++ api_key=api_key,
++ openai_api_base=openai_endpoint_url,
++ **common_params
++ )
++
++ elif provider == "vllm":
++ try:
++ return VLLM(
++ model=model_name,
++ trust_remote_code=True,
++ max_new_tokens=128,
++ top_k=10,
++ top_p=0.95,
++ temperature=temperature,
++ )
++ except Exception as e:
++ logger.error(f"Error loading VLLM model: {e}")
++ logger.warning("Falling back.")
++ return get_fallback_model(temperature)
++
++ elif provider == "ollama":
++ try:
++ # Use the configurable Ollama base URL
++ base_url = settings.get('OLLAMA_BASE_URL', settings.llm.get('ollama_base_url', 'http://localhost:11434'))
++ return ChatOllama(model=model_name, base_url=base_url, **common_params)
++ except Exception as e:
++ logger.error(f"Error loading Ollama model: {e}")
++ return get_fallback_model(temperature)
++
++ elif provider == "lmstudio":
++
++ # LM Studio supports OpenAI API format, so we can use ChatOpenAI directly
++ lmstudio_url = settings.llm.get('lmstudio_url', "http://localhost:1234")
++
++ return ChatOpenAI(
++ model=model_name,
++ api_key="lm-studio", # LM Studio doesn't require a real API key
++ base_url=f"{lmstudio_url}/v1", # Use the configured URL with /v1 endpoint
++ temperature=temperature,
++ max_tokens=settings.llm.max_tokens
++ )
++
++
++ elif provider == "llamacpp":
++
++ # Import LlamaCpp
++ from langchain_community.llms import LlamaCpp
++
++ # Get LlamaCpp model path from settings
++ model_path = settings.llm.get('llamacpp_model_path', "")
++ if not model_path:
++ logger.error("llamacpp_model_path not set in settings")
++ raise ValueError("llamacpp_model_path not set in settings.toml")
++
++ # Get additional LlamaCpp parameters
++ n_gpu_layers = settings.llm.get('llamacpp_n_gpu_layers', 1)
++ n_batch = settings.llm.get('llamacpp_n_batch', 512)
++ f16_kv = settings.llm.get('llamacpp_f16_kv', True)
++
++ # Create LlamaCpp instance
++ return LlamaCpp(
++ model_path=model_path,
++ temperature=temperature,
++ max_tokens=settings.llm.max_tokens,
++ n_gpu_layers=n_gpu_layers,
++ n_batch=n_batch,
++ f16_kv=f16_kv,
++ verbose=True
++ )
++
++ else:
++ return get_fallback_model(temperature)
++
++def get_fallback_model(temperature=None):
++ """Create a dummy model for when no providers are available"""
++ from langchain_community.llms.fake import FakeListLLM
++ return FakeListLLM(
++ responses=["No language models are available. Please install Ollama or set up API keys."]
++ )
++
++# ================================
++# COMPATIBILITY FUNCTIONS
++# ================================
++
++def get_available_provider_types():
++ """Return available model providers"""
++ providers = {}
++
++ if is_ollama_available():
++ providers["ollama"] = "Ollama (local models)"
++
++ if is_openai_available():
++ providers["openai"] = "OpenAI API"
++
++ if is_anthropic_available():
++ providers["anthropic"] = "Anthropic API"
++
++ if is_openai_endpoint_available():
++ providers["openai_endpoint"] = "OpenAI-compatible Endpoint"
++
++ if is_lmstudio_available():
++ providers["lmstudio"] = "LM Studio (local models)"
++
++ if is_llamacpp_available():
++ providers["llamacpp"] = "LlamaCpp (local models)"
++
++ # Check for VLLM capability
++ try:
++ import torch
++ import transformers
++ providers["vllm"] = "VLLM (local models)"
++ except ImportError:
++ pass
++
++ # Default fallback
++ if not providers:
++ providers["none"] = "No model providers available"
++
++ return providers
++
++# ================================
++# HELPER FUNCTIONS
++# ================================
++
++def is_openai_available():
++ """Check if OpenAI is available"""
++ try:
++ api_key = settings.get('OPENAI_API_KEY', '')
++ return bool(api_key)
++ except:
++ return False
++
++def is_anthropic_available():
++ """Check if Anthropic is available"""
++ try:
++ api_key = settings.get('ANTHROPIC_API_KEY', '')
++ return bool(api_key)
++ except:
++ return False
++
++def is_openai_endpoint_available():
++ """Check if OpenAI endpoint is available"""
++ try:
++ api_key = settings.get('OPENAI_ENDPOINT_API_KEY', '')
++ return bool(api_key)
++ except:
++ return False
++
++def is_ollama_available():
++ """Check if Ollama is running"""
++ try:
++ import requests
++ base_url = settings.get('OLLAMA_BASE_URL', settings.llm.get('ollama_base_url', 'http://localhost:11434'))
++ response = requests.get(f"{base_url}/api/tags", timeout=1.0)
++ return response.status_code == 200
++ except:
++ return False
++
++def is_vllm_available():
++ """Check if VLLM capability is available"""
++ try:
++ import torch
++ import transformers
++ return True
++ except ImportError:
++ return False
++
++def is_lmstudio_available():
++ """Check if LM Studio is available"""
++ try:
++ import requests
++ lmstudio_url = settings.llm.get('lmstudio_url', 'http://localhost:1234')
++ # LM Studio typically uses OpenAI-compatible endpoints
++ response = requests.get(f"{lmstudio_url}/v1/models", timeout=1.0)
++ return response.status_code == 200
++ except:
++ return False
++
++def is_llamacpp_available():
++ """Check if LlamaCpp is available and configured"""
++ try:
++ from langchain_community.llms import LlamaCpp
++ model_path = settings.llm.get('llamacpp_model_path', '')
++ return bool(model_path) and os.path.exists(model_path)
++ except:
++ return False
++
++def get_available_providers():
++ """Get dictionary of available providers"""
++ return get_available_provider_types()
++
++# Log which providers are available
++AVAILABLE_PROVIDERS = get_available_providers()
++logger.info(f"Available providers: {list(AVAILABLE_PROVIDERS.keys())}")
++
++# Check if selected provider is available
++selected_provider = settings.llm.provider.lower()
++if selected_provider not in AVAILABLE_PROVIDERS and selected_provider != "none":
++ logger.warning(f"Selected provider {selected_provider} is not available.")
diff --cc data/config/local_collections.toml
index 0000000000,0000000000..f26aa97e04
new file mode 100644
--- /dev/null
+++ b/data/config/local_collections.toml
@@@ -1,0 -1,0 +1,53 @@@
++# Project Documents Collection
++[project_docs]
++name = "Project Documents"
++description = "Project documentation and specifications"
++paths = ["@format ${DOCS_DIR}/project_documents"]
++enabled = true
++embedding_model = "all-MiniLM-L6-v2"
++embedding_device = "cpu"
++embedding_model_type = "sentence_transformers"
++max_results = 20
++max_filtered_results = 5
++chunk_size = 1000
++chunk_overlap = 200
++cache_dir = "__CACHE_DIR__/local_search/project_docs"
++strengths = ["project documentation", "specifications", "internal documents"]
++weaknesses = ["no external information", "limited to organizational knowledge"]
++reliability = 0.9
++
++# Research Papers Collection
++[research_papers]
++name = "Research Papers"
++description = "Academic research papers and articles"
++paths = ["@format ${DOCS_DIR}/research_papers"]
++enabled = true
++embedding_model = "all-MiniLM-L6-v2"
++embedding_device = "cpu"
++embedding_model_type = "sentence_transformers"
++max_results = 20
++max_filtered_results = 5
++chunk_size = 800
++chunk_overlap = 150
++cache_dir = "__CACHE_DIR__/local_search/research_papers"
++strengths = ["academic research", "scientific papers", "scholarly content"]
++weaknesses = ["potentially outdated", "limited to collected papers"]
++reliability = 0.85
++
++# Personal Notes Collection
++[personal_notes]
++name = "Personal Notes"
++description = "Personal notes and documents"
++paths = ["@format ${DOCS_DIR}/personal_notes"]
++enabled = true
++embedding_model = "all-MiniLM-L6-v2"
++embedding_device = "cpu"
++embedding_model_type = "sentence_transformers"
++max_results = 30
++max_filtered_results = 10
++chunk_size = 500
++chunk_overlap = 100
++cache_dir = "__CACHE_DIR__/local_search/personal_notes"
++strengths = ["personal knowledge", "notes", "private documents"]
++weaknesses = ["subjective content", "informal information"]
++reliability = 0.75
diff --cc data/config/search_engines.toml
index 0000000000,0000000000..910413554b
new file mode 100644
--- /dev/null
+++ b/data/config/search_engines.toml
@@@ -1,0 -1,0 +1,265 @@@
++# Search Engines Configuration for Local Deep Research
++# This file defines all available search engines and their properties
++
++[wikipedia]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_wikipedia"
++class_name = "WikipediaSearchEngine"
++requires_api_key = false
++reliability = 0.95
++strengths = [
++ "factual information", "general knowledge", "definitions",
++ "historical facts", "biographies", "overview information"
++]
++weaknesses = ["recent events", "specialized academic topics", "product comparisons"]
++
++[wikipedia.default_params]
++max_results = 20
++include_content = true
++
++[arxiv]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_arxiv"
++class_name = "ArXivSearchEngine"
++requires_api_key = false
++reliability = 0.9
++strengths = [
++ "scientific papers", "academic research", "physics", "computer science",
++ "mathematics", "statistics", "machine learning", "preprints"
++]
++weaknesses = ["non-academic topics", "consumer products", "news", "general information"]
++
++[arxiv.default_params]
++max_results = 20
++sort_by = "relevance"
++sort_order = "descending"
++
++[pubmed]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_pubmed"
++class_name = "PubMedSearchEngine"
++requires_api_key = false
++api_key_env = "NCBI_API_KEY"
++reliability = 0.98
++strengths = [
++ "biomedical literature", "medical research", "clinical studies",
++ "life sciences", "health information", "scientific papers"
++]
++weaknesses = [
++ "non-medical topics", "very recent papers may be missing",
++ "limited to published research"
++]
++requires_llm = true
++
++[pubmed.default_params]
++max_results = 20
++get_abstracts = true
++get_full_text = false
++full_text_limit = 3
++days_limit = 0
++optimize_queries = true
++
++[github]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_github"
++class_name = "GitHubSearchEngine"
++requires_api_key = false
++reliability = 0.99
++strengths = [
++ "code repositories", "software documentation", "open source projects",
++ "programming issues", "developer information", "technical documentation"
++]
++weaknesses = ["non-technical content", "content outside GitHub", "rate limits without API key"]
++supports_full_search = true
++
++[github.default_params]
++max_results = 15
++search_type = "repositories"
++include_readme = true
++include_issues = false
++
++[serpapi]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_serpapi"
++class_name = "SerpAPISearchEngine"
++requires_api_key = true
++api_key_env = "SERP_API_KEY"
++reliability = 0.6
++strengths = [
++ "comprehensive web search", "product information", "reviews",
++ "recent content", "news", "broad coverage"
++]
++weaknesses = ["requires API key with usage limits", "not specialized for academic content"]
++supports_full_search = true
++full_search_module = "local_deep_research.web_search_engines.engines.full_serp_search_results_old"
++full_search_class = "FullSerpAPISearchResults"
++
++[serpapi.default_params]
++region = "us"
++time_period = "y"
++safe_search = true
++search_language = "English"
++
++[google_pse]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_google_pse"
++class_name = "GooglePSESearchEngine"
++requires_api_key = true
++api_key_env = "GOOGLE_PSE_API_KEY"
++reliability = 0.9
++strengths = [
++ "custom search scope", "high-quality results", "domain-specific search",
++ "configurable search experience", "control over search index"
++]
++weaknesses = [
++ "requires API key with usage limits",
++ "limited to 10,000 queries/day on free tier",
++ "requires search engine configuration in Google Control Panel"
++]
++supports_full_search = true
++full_search_module = "local_deep_research.web_search_engines.engines.full_search"
++full_search_class = "FullSearchResults"
++
++[google_pse.default_params]
++region = "us"
++safe_search = true
++search_language = "English"
++
++[brave]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_brave"
++class_name = "BraveSearchEngine"
++requires_api_key = true
++api_key_env = "BRAVE_API_KEY"
++reliability = 0.7
++strengths = [
++ "privacy-focused web search", "product information", "reviews",
++ "recent content", "news", "broad coverage"
++]
++weaknesses = ["requires API key with usage limits", "smaller index than Google"]
++supports_full_search = true
++full_search_module = "local_deep_research.web_search_engines.engines.full_search"
++full_search_class = "FullSearchResults"
++
++[brave.default_params]
++region = "US"
++time_period = "y"
++safe_search = true
++search_language = "English"
++
++[wayback]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_wayback"
++class_name = "WaybackSearchEngine"
++requires_api_key = false
++reliability = 0.5
++strengths = [
++ "historical web content", "archived websites", "content verification",
++ "deleted or changed web pages", "website evolution tracking"
++]
++weaknesses = [
++ "limited to previously archived content", "may miss recent changes",
++ "archiving quality varies"
++]
++supports_full_search = true
++
++[wayback.default_params]
++max_results = 15
++max_snapshots_per_url = 3
++closest_only = false
++language = "English"
++
++[auto]
++module_path = "local_deep_research.web_search_engines.engines.meta_search_engine"
++class_name = "MetaSearchEngine"
++requires_api_key = false
++reliability = 0.85
++strengths = [
++ "intelligent engine selection", "adaptable to query type",
++ "fallback capabilities"
++]
++weaknesses = ["slightly slower due to LLM analysis"]
++requires_llm = true
++
++[auto.default_params]
++use_api_key_services = true
++max_engines_to_try = 3
++
++[local_all]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_local_all"
++class_name = "LocalAllSearchEngine"
++requires_api_key = false
++reliability = 0.85
++strengths = ["searches all local collections", "personal documents", "offline access"]
++weaknesses = ["may return too many results", "requires indexing"]
++requires_llm = true
++
++[semantic_scholar]
++module_path = "local_deep_research.web_search_engines.engines.search_engine_semantic_scholar"
++class_name = "SemanticScholarSearchEngine"
++requires_api_key = false
++api_key_env = "S2_API_KEY"
++reliability = 0.87
++strengths = [
++ "comprehensive scientific literature",
++ "extensive citation network",
++ "AI-generated summaries (TLDRs)",
++ "academic paper metadata",
++ "cross-disciplinary coverage",
++ "200M+ papers across all fields",
++ "usable without API key"
++]
++weaknesses = [
++ "rate limited (1000 requests/day) without API key",
++ "limited to academic content"
++]
++supports_full_search = true
++requires_llm = false
++
++[semantic_scholar.default_params]
++max_results = 20
++get_abstracts = true
++get_tldr = true
++get_references = false
++get_citations = false
++get_embeddings = false
++citation_limit = 10
++reference_limit = 10
++optimize_queries = true
++max_retries = 5
++retry_backoff_factor = 1.0
++
++# Default search engine to use if none specified
++DEFAULT_SEARCH_ENGINE = "wikipedia"
++
++
++
++
++
++# Additional search engines can be added below
++# Uncomment and modify these templates as needed
++
++# [duckduckgo]
++# module_path = "local_deep_research.web_search_engines.engines.search_engine_ddg"
++# class_name = "DuckDuckGoSearchEngine"
++# requires_api_key = false
++# reliability = 0.4
++# strengths = [
++# "web search", "product information", "reviews", "recent information",
++# "news", "general queries", "broad coverage"
++# ]
++# weaknesses = ["inconsistent due to rate limits", "not specialized for academic content"]
++# supports_full_search = true
++# full_search_module = "local_deep_research.web_search_engines.engines.full_search"
++# full_search_class = "FullSearchResults"
++#
++# [duckduckgo.default_params]
++# region = "us"
++# safe_search = true
++
++# [guardian]
++# module_path = "local_deep_research.web_search_engines.engines.search_engine_guardian"
++# class_name = "GuardianSearchEngine"
++# requires_api_key = true
++# api_key_env = "GUARDIAN_API_KEY"
++# reliability = 0.5
++# strengths = [
++# "news articles", "current events", "opinion pieces", "journalism",
++# "UK and global news", "political analysis"
++# ]
++# weaknesses = ["primarily focused on news", "limited historical content pre-1999"]
++#
++# [guardian.default_params]
++# order_by = "relevance"
diff --cc data/config/settings.toml
index 0000000000,0000000000..76e1e7206e
new file mode 100644
--- /dev/null
+++ b/data/config/settings.toml
@@@ -1,0 -1,0 +1,80 @@@
++
++# Main configuration for Local Deep Research
++
++[web]
++port = 5000
++host = "0.0.0.0"
++debug = true
++
++[llm]
++# LLM provider (one of: ollama, openai, anthropic, vllm, openai_endpoint, lmstudio, llamacpp)
++provider = "ollama"
++# Model name
++model = "gemma3:12b"
++# Temperature
++temperature = 0.7
++# Maximum tokens
++max_tokens = 30000
++# OpenAI-compatible endpoint URL
++openai_endpoint_url = "https://openrouter.ai/api/v1"
++# LM Studio URL (default: http://localhost:1234)
++lmstudio_url = "http://localhost:1234"
++# LlamaCpp model path
++llamacpp_model_path = ""
++# LlamaCpp parameters
++llamacpp_n_gpu_layers = 1
++llamacpp_n_batch = 512
++llamacpp_f16_kv = true
++
++[general]
++# Directory for research outputs (relative to user data directory)
++output_dir = "research_outputs"
++# Knowledge accumulation approach (NONE, QUESTION, or ITERATION)
++knowledge_accumulation = "ITERATION"
++# Maximum context size for knowledge accumulation
++knowledge_accumulation_context_limit = 2000000
++# Enable fact checking (experimental, works better with large LLMs)
++enable_fact_checking = false
++
++
++[search]
++# Search tool to use (auto, wikipedia, arxiv, duckduckgo, serp, google_pse, etc.)
++# "auto" intelligently selects based on query content (recommended)
++# "local_all" searches only local document collections
++tool = "auto"
++
++# Number of research cycles
++iterations = 2
++
++# Questions generated per cycle
++questions_per_iteration = 2
++
++# Searches per report section
++searches_per_section = 2
++
++# Results per search query
++max_results = 50
++
++# Results after relevance filtering
++max_filtered_results = 5
++
++# Search region
++region = "us"
++
++# Time period (d=day, w=week, m=month, y=year)
++time_period = "y"
++
++# Enable safe search
++safe_search = true
++
++# Search language
++search_language = "English"
++
++# Return only snippets, not full content (faster but less detailed)
++snippets_only = false
++
++# Skip relevance filtering (return all results)
++skip_relevance_filter = false
++
++# Check URL quality
++quality_check_urls = true
diff --cc src/local_deep_research/web_search_engines/engines/search_engine_github.py
index 244112d67a,40978bc0e0..7228defee4
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@@ -1,14 -1,14 +1,16 @@@
-import requests
-import logging
import base64
+import logging
import os
import time
+from typing import Any, Dict, List, Optional
+
+import requests
+ import json
+ from typing import Dict, List, Any, Optional, Union
from langchain_core.language_models import BaseLLM
-from local_deep_research.web_search_engines.search_engine_base import BaseSearchEngine
-from local_deep_research import config
+from ... import config
+from ..search_engine_base import BaseSearchEngine
# Setup logging
logging.basicConfig(level=logging.INFO)
@@@ -79,15 -72,69 +81,73 @@@ class GitHubSearchEngine(BaseSearchEngi
if remaining < 5:
current_time = time.time()
wait_time = max(reset_time - current_time, 0)
- logger.warning(f"GitHub API rate limit almost reached. {remaining} requests remaining.")
-
+ logger.warning(
+ f"GitHub API rate limit almost reached. {remaining} requests remaining."
+ )
+
if wait_time > 0 and remaining == 0:
- logger.warning(f"GitHub API rate limit exceeded. Waiting {wait_time:.0f} seconds.")
+ logger.warning(
+ f"GitHub API rate limit exceeded. Waiting {wait_time:.0f} seconds."
+ )
time.sleep(min(wait_time, 60)) # Wait at most 60 seconds
+
+ def _optimize_github_query(self, query: str) -> str:
+ """
+ Optimize the GitHub search query using LLM to improve search results.
+
+ Args:
+ query: Original search query
+
+ Returns:
+ Optimized GitHub search query
+ """
+ # Get LLM from config if not already set
+ if not self.llm:
+ try:
+ self.llm = config.get_llm()
+ if not self.llm:
+ logger.warning("No LLM available for query optimization")
+ return query
+ except Exception as e:
+ logger.error(f"Error getting LLM from config: {e}")
+ return query
+
+ prompt = f"""Transform this GitHub search query into an optimized version for the GitHub search API. Follow these steps:
+ 1. Strip question words (e.g., 'what', 'are', 'is'), stop words (e.g., 'and', 'as', 'of', 'on'), and redundant terms (e.g., 'repositories', 'repos', 'github') since they're implied by the search context.
+ 2. Keep only domain-specific keywords and avoid using "-related" terms.
+ 3. Add GitHub-specific filters with dynamic thresholds based on query context:
+ - For stars: Use higher threshold (e.g., 'stars:>1000') for mainstream topics, lower (e.g., 'stars:>50') for specialized topics
+ - For language: Detect programming language from query or omit if unclear
+ - For search scope: Use 'in:name,description,readme' for general queries, 'in:file' for code-specific queries
+ 4. For date ranges, adapt based on query context:
+ - For emerging: Use 'created:>2024-01-01'
+ - For mature: Use 'pushed:>2023-01-01'
+ - For historical research: Use 'created:2020-01-01..2024-01-01'
+ 5. For excluding results, adapt based on query:
+ - Exclude irrelevant languages based on context
+ - Use 'NOT' to exclude competing terms
+ 6. Ensure the output is a concise, space-separated string with no punctuation or extra text beyond keywords and filters.
+
+
+ Original query: "{query}"
+
+ Return ONLY the optimized query, ready for GitHub's search API. Do not include explanations or additional text."""
+
+ try:
+ response = self.llm.invoke(prompt)
+ optimized_query = response.content.strip()
+
+ # Validate the optimized query
+ if optimized_query and len(optimized_query) > 0:
+ logger.info(f"LLM optimized query from '{query}' to '{optimized_query}'")
+ return optimized_query
+ else:
+ logger.warning("LLM returned empty query, using original")
+ return query
+
+ except Exception as e:
+ logger.error(f"Error optimizing query with LLM: {e}")
+ return query
def _search_github(self, query: str) -> List[Dict[str, Any]]:
"""
@@@ -100,34 -147,13 +160,13 @@@
List of GitHub search result items
"""
results = []
-
+
try:
- # Optimize GitHub query format
- github_query = query
-
- # For long queries, focus on keywords and add filters for better results
- if len(query) > 80:
- # Extract key terms if it's a recommendation request
- if "recommend" in query.lower() or "looking for" in query.lower():
- github_query = "stars:>100 " + " ".join(
- [
- word
- for word in query.split()
- if len(word) > 3
- and word.lower()
- not in [
- "recommend",
- "recommended",
- "github",
- "repositories",
- "looking",
- "developers",
- ]
- ]
- )
-
- logger.info(f"Optimized GitHub query: {github_query}")
-
+ # Optimize GitHub query using LLM
+ github_query = self._optimize_github_query(query)
+
+ logger.info(f"Final GitHub query: {github_query}")
+
# Construct search parameters
params = {
"q": github_query,
@@@ -748,3 -708,67 +787,67 @@@
logger.info(f"Set GitHub search type to: {search_type}")
else:
logger.error(f"Invalid GitHub search type: {search_type}")
+
+ def _filter_for_relevance(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:
+ """
+ Filter GitHub search results for relevance using LLM.
+
+ Args:
+ previews: List of preview dictionaries
+ query: Original search query
+
+ Returns:
+ List of relevant preview dictionaries
+ """
+ if not self.llm or not previews:
+ return previews
+
+ # Create a specialized prompt for GitHub results
+ prompt = f"""Analyze these GitHub search results and rank them by relevance to the query.
+ Consider:
+ 1. Repository stars and activity (higher is better)
+ 2. Match between query intent and repository description
+ 3. Repository language and topics
+ 4. Last update time (more recent is better)
+ 5. Whether it's a fork (original repositories are preferred)
+
+ Query: "{query}"
+
+ Results:
+ {json.dumps(previews, indent=2)}
+
+ Return ONLY a JSON array of indices in order of relevance (most relevant first).
+ Example: [0, 2, 1, 3]
+ Do not include any other text or explanation."""
+
+ try:
+ response = self.llm.invoke(prompt)
+ response_text = response.content.strip()
+
+ # Extract JSON array from response
+ start_idx = response_text.find('[')
+ end_idx = response_text.rfind(']')
+
+ if start_idx >= 0 and end_idx > start_idx:
+ array_text = response_text[start_idx:end_idx+1]
+ ranked_indices = json.loads(array_text)
+
+ # Return the results in ranked order
+ ranked_results = []
+ for idx in ranked_indices:
+ if idx < len(previews):
+ ranked_results.append(previews[idx])
+
+ # Limit to max_filtered_results if specified
+ if self.max_filtered_results and len(ranked_results) > self.max_filtered_results:
+ logger.info(f"Limiting filtered results to top {self.max_filtered_results}")
+ return ranked_results[:self.max_filtered_results]
+
+ return ranked_results
+ else:
+ logger.info("Could not find JSON array in response, returning no previews")
+ return []
+
+ except Exception as e:
+ logger.error(f"Error filtering GitHub results: {e}")
- return []
++ return []