instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Help me write clear docstrings
import uuid # Removed direct logging import - using unified config from datetime import datetime from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) class DocumentService: def __init__(self, supabase_client=Non...
--- +++ @@ -1,3 +1,9 @@+""" +Document Service Module for Archon + +This module provides core business logic for document operations within projects +that can be shared between MCP tools and FastAPI endpoints. +""" import uuid @@ -13,8 +19,10 @@ class DocumentService: + """Service class for document operatio...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/document_service.py
Add docstrings including usage examples
# Removed direct logging import - using unified config from datetime import datetime from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) # Task updates are handled via polling - no broadcasting needed class TaskServ...
--- +++ @@ -1,3 +1,9 @@+""" +Task Service Module for Archon + +This module provides core business logic for task operations that can be +shared between MCP tools and FastAPI endpoints. +""" # Removed direct logging import - using unified config from datetime import datetime @@ -13,13 +19,16 @@ class TaskService...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/task_service.py
Add minimal docstrings for each function
# Removed direct logging import - using unified config from datetime import datetime from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) class VersioningService: def __init__(self, supabase_client=None): ...
--- +++ @@ -1,3 +1,9 @@+""" +Versioning Service Module for Archon + +This module provides core business logic for document versioning operations +that can be shared between MCP tools and FastAPI endpoints. +""" # Removed direct logging import - using unified config from datetime import datetime @@ -11,8 +17,10 @@ ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/versioning_service.py
Add docstrings to existing functions
from typing import Any from supabase import Client from ...config.logfire_config import get_logger, safe_span logger = get_logger(__name__) # Fixed similarity threshold for vector results SIMILARITY_THRESHOLD = 0.05 class BaseSearchStrategy: def __init__(self, supabase_client: Client): self.supabase...
--- +++ @@ -1,3 +1,9 @@+""" +Base Search Strategy + +Implements the foundational vector similarity search that all other strategies build upon. +This is the core semantic search functionality. +""" from typing import Any @@ -12,8 +18,10 @@ class BaseSearchStrategy: + """Base strategy implementing fundamenta...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/base_search_strategy.py
Help me add docstrings to my project
# Removed direct logging import - using unified config from datetime import UTC, datetime from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) class ProjectCreationService: def __init__(self, supabase_client=None...
--- +++ @@ -1,3 +1,9 @@+""" +Project Creation Service Module for Archon + +This module handles the complex project creation workflow including +AI-assisted documentation generation and progress tracking. +""" # Removed direct logging import - using unified config from datetime import UTC, datetime @@ -11,8 +17,10 @...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/project_creation_service.py
Add return value explanations in docstrings
from typing import Any from supabase import Client from ..config.logfire_config import get_logger, search_logger from .client_manager import get_supabase_client from .llm_provider_service import extract_message_text, get_llm_client logger = get_logger(__name__) async def extract_source_summary( source_id: str...
--- +++ @@ -1,544 +1,658 @@- -from typing import Any - -from supabase import Client - -from ..config.logfire_config import get_logger, search_logger -from .client_manager import get_supabase_client -from .llm_provider_service import extract_message_text, get_llm_client - -logger = get_logger(__name__) - - -async def ex...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/source_management_service.py
Provide docstrings following PEP 257
import asyncio from collections.abc import Callable from xml.etree import ElementTree import requests from ....config.logfire_config import get_logger logger = get_logger(__name__) class SitemapCrawlStrategy: def parse_sitemap(self, sitemap_url: str, cancellation_check: Callable[[], None] | None = None) -> li...
--- +++ @@ -1,3 +1,8 @@+""" +Sitemap Crawling Strategy + +Handles crawling of URLs from XML sitemaps. +""" import asyncio from collections.abc import Callable from xml.etree import ElementTree @@ -10,8 +15,19 @@ class SitemapCrawlStrategy: + """Strategy for parsing and crawling sitemaps.""" def parse_s...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/strategies/sitemap.py
Generate NumPy-style docstrings
import os import openai from ...config.logfire_config import search_logger from ..credential_service import credential_service from ..llm_provider_service import ( extract_message_text, get_llm_client, prepare_chat_completion_params, requires_max_completion_tokens, ) from ..threading_service import g...
--- +++ @@ -1,3 +1,9 @@+""" +Contextual Embedding Service + +Handles generation of contextual embeddings for improved RAG retrieval. +Includes proper rate limiting for OpenAI API calls. +""" import os @@ -17,6 +23,19 @@ async def generate_contextual_embedding( full_document: str, chunk: str, provider: str = N...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/embeddings/contextual_embedding_service.py
Add clean documentation to messy code
import asyncio from collections.abc import Awaitable, Callable from typing import Any from urllib.parse import urldefrag from crawl4ai import CacheMode, CrawlerRunConfig, MemoryAdaptiveDispatcher from ....config.logfire_config import get_logger from ...credential_service import credential_service from ..helpers.url_...
--- +++ @@ -1,3 +1,8 @@+""" +Recursive Crawling Strategy + +Handles recursive crawling of websites by following internal links. +""" import asyncio from collections.abc import Awaitable, Callable @@ -14,8 +19,16 @@ class RecursiveCrawlStrategy: + """Strategy for recursive crawling of websites.""" def ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/strategies/recursive.py
Add docstrings to meet PEP guidelines
from typing import Any from supabase import Client from ...config.logfire_config import get_logger, safe_span from ..embeddings.embedding_service import create_embedding logger = get_logger(__name__) class HybridSearchStrategy: def __init__(self, supabase_client: Client, base_strategy): self.supabase...
--- +++ @@ -1,3 +1,15 @@+""" +Hybrid Search Strategy + +Implements hybrid search combining vector similarity search with full-text search +using PostgreSQL's ts_vector for improved recall and precision in document and +code example retrieval. + +Strategy combines: +1. Vector/semantic search for conceptual matches +2. ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/hybrid_search_strategy.py
Add minimal docstrings for each function
# Removed direct logging import - using unified config from datetime import datetime from ..config.logfire_config import get_logger from ..utils import get_supabase_client logger = get_logger(__name__) class PromptService: _instance = None _prompts: dict[str, str] = {} _last_loaded: datetime | None = ...
--- +++ @@ -1,3 +1,10 @@+""" +Prompt Service Module for Archon + +This module provides a singleton service for managing AI agent prompts. +Prompts are loaded from the database at startup and cached in memory for +fast access during agent operations. +""" # Removed direct logging import - using unified config from d...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/prompt_service.py
Write docstrings for backend logic
import os from typing import Any from ...config.logfire_config import get_logger, safe_span from ...utils import get_supabase_client from ..embeddings.embedding_service import create_embedding from .agentic_rag_strategy import AgenticRAGStrategy # Import all strategies from .base_search_strategy import BaseSearchStr...
--- +++ @@ -1,3 +1,16 @@+""" +RAG Service - Thin Coordinator + +This service acts as a coordinator that delegates to specific strategy implementations. +It combines multiple RAG strategies in a pipeline fashion: + +1. Base vector search +2. + Hybrid search (if enabled) - combines vector + keyword +3. + Reranking (if en...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/rag_service.py
Add docstrings to meet PEP guidelines
import re # Common stop words to filter out STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "been", "by", "for", "from", "has", "have", "he", "in", "is", "it", "its", "of", "on", "that", "the", "to", "was", "...
--- +++ @@ -1,3 +1,9 @@+""" +Keyword Extraction Utility + +Simple and effective keyword extraction for improved search capabilities. +Uses lightweight Python string operations without heavy NLP dependencies. +""" import re @@ -234,6 +240,7 @@ class KeywordExtractor: + """Simple keyword extraction for search...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/keyword_extractor.py
Add missing documentation to my Python functions
import base64 import os import re import time from dataclasses import dataclass # Removed direct logging import - using unified config from typing import Any from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from ...
--- +++ @@ -1,3 +1,9 @@+""" +Credential management service for Archon backend + +Handles loading, storing, and accessing credentials with encryption for sensitive values. +Credentials include API keys, service credentials, and application configuration. +""" import base64 import os @@ -20,6 +26,7 @@ @dataclass c...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/credential_service.py
Add docstrings for production code
import asyncio from collections.abc import Awaitable, Callable from typing import Any from crawl4ai import CacheMode, CrawlerRunConfig, MemoryAdaptiveDispatcher from ....config.logfire_config import get_logger from ...credential_service import credential_service logger = get_logger(__name__) class BatchCrawlStrat...
--- +++ @@ -1,3 +1,8 @@+""" +Batch Crawling Strategy + +Handles batch crawling of multiple URLs in parallel. +""" import asyncio from collections.abc import Awaitable, Callable @@ -12,8 +17,16 @@ class BatchCrawlStrategy: + """Strategy for crawling multiple URLs in batch.""" def __init__(self, crawler...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/strategies/batch.py
Expand my code with proper documentation strings
import os from typing import Any try: from sentence_transformers import CrossEncoder CROSSENCODER_AVAILABLE = True except ImportError: CrossEncoder = None CROSSENCODER_AVAILABLE = False from ...config.logfire_config import get_logger, safe_span logger = get_logger(__name__) # Default reranking mod...
--- +++ @@ -1,3 +1,12 @@+""" +Reranking Strategy + +Implements result reranking using CrossEncoder models to improve search result ordering. +The reranking process re-scores search results based on query-document relevance using +a trained neural model, typically improving precision over initial retrieval scores. + +Us...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/reranking_strategy.py
Auto-generate documentation strings for this file
import time from dataclasses import dataclass from typing import Any from urllib.parse import urlparse import aiohttp import openai from ..config.logfire_config import get_logger from .credential_service import credential_service logger = get_logger(__name__) # Provider capabilities and model specifications cache ...
--- +++ @@ -1,3 +1,9 @@+""" +Provider Discovery Service + +Discovers available models, checks provider health, and provides model specifications +for OpenAI, Google Gemini, Ollama, Anthropic, and Grok providers. +""" import time from dataclasses import dataclass @@ -43,6 +49,7 @@ @dataclass class ModelSpec: + ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/provider_discovery_service.py
Add docstrings to meet PEP guidelines
import asyncio import time from dataclasses import dataclass from typing import Any, cast import httpx from ...config.logfire_config import get_logger from ..llm_provider_service import get_llm_client logger = get_logger(__name__) @dataclass class OllamaModel: name: str tag: str size: int digest:...
--- +++ @@ -1,3 +1,9 @@+""" +Ollama Model Discovery Service + +Provides comprehensive model discovery, validation, and capability detection for Ollama instances. +Supports multi-instance configurations with automatic dimension detection and health monitoring. +""" import asyncio import time @@ -14,6 +20,7 @@ @dat...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/ollama/model_discovery_service.py
Create docstrings for API functions
from typing import Any from supabase import Client from ...config.logfire_config import get_logger, safe_span from ..embeddings.embedding_service import create_embedding logger = get_logger(__name__) class AgenticRAGStrategy: def __init__(self, supabase_client: Client, base_strategy): self.supabase_c...
--- +++ @@ -1,3 +1,16 @@+""" +Agentic RAG Strategy + +Implements agentic RAG functionality for intelligent code example extraction and search. +This strategy focuses on code-specific search and retrieval, providing enhanced +search capabilities for code examples, documentation, and programming-related content. + +Key f...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/search/agentic_rag_strategy.py
Help me comply with documentation standards
import asyncio import inspect import os from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Any import httpx import numpy as np import openai from ...config.logfire_config import safe_span, search_logger from ..credential_service import credential_service from ..llm_provid...
--- +++ @@ -1,3 +1,8 @@+""" +Embedding Service + +Handles all OpenAI embedding operations with proper rate limiting and error handling. +""" import asyncio import inspect @@ -24,6 +29,7 @@ @dataclass class EmbeddingBatchResult: + """Result of batch embedding creation with success/failure tracking.""" e...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/embeddings/embedding_service.py
Generate documentation strings for clarity
import hashlib import json from typing import Any def generate_etag(data: Any) -> str: # Convert data to stable JSON string json_str = json.dumps(data, sort_keys=True, default=str) # Generate MD5 hash hash_obj = hashlib.md5(json_str.encode('utf-8')) # Return ETag in standard format (quoted) ...
--- +++ @@ -1,3 +1,4 @@+"""ETag utilities for HTTP caching and efficient polling.""" import hashlib import json @@ -5,6 +6,14 @@ def generate_etag(data: Any) -> str: + """Generate an ETag hash from data. + + Args: + data: Any JSON-serializable data to hash + + Returns: + ETag ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/utils/etag_utils.py
Add concise docstrings to each method
from typing import Any class EmbeddingError(Exception): def __init__( self, message: str, text_preview: str | None = None, batch_index: int | None = None, **kwargs, ): self.text_preview = text_preview[:200] if text_preview else None self.batch_index = ...
--- +++ @@ -1,8 +1,15 @@+""" +Custom exceptions for embedding service failures. + +These exceptions follow the principle: "fail fast and loud" for data integrity issues, +while allowing batch processes to continue by skipping failed items. +""" from typing import Any class EmbeddingError(Exception): + """Bas...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/embeddings/embedding_exceptions.py
Help me document legacy Python code
import asyncio import traceback from collections.abc import Awaitable, Callable from typing import Any from crawl4ai import CacheMode, CrawlerRunConfig from ....config.logfire_config import get_logger logger = get_logger(__name__) class SinglePageCrawlStrategy: def __init__(self, crawler, markdown_generator):...
--- +++ @@ -1,3 +1,8 @@+""" +Single Page Crawling Strategy + +Handles crawling of individual web pages. +""" import asyncio import traceback from collections.abc import Awaitable, Callable @@ -11,12 +16,21 @@ class SinglePageCrawlStrategy: + """Strategy for crawling a single web page.""" def __init__(s...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/strategies/single_page.py
Add docstrings to existing functions
from typing import Any from ...config.logfire_config import safe_logfire_error, safe_logfire_info class KnowledgeItemService: def __init__(self, supabase_client): self.supabase = supabase_client async def list_items( self, page: int = 1, per_page: int = 20, knowledg...
--- +++ @@ -1,412 +1,479 @@- -from typing import Any - -from ...config.logfire_config import safe_logfire_error, safe_logfire_info - - -class KnowledgeItemService: - - def __init__(self, supabase_client): - self.supabase = supabase_client - - async def list_items( - self, - page: int = 1, - ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/knowledge/knowledge_item_service.py
Write docstrings for data processing functions
import re def parse_version(version_string: str) -> tuple[int, int, int, str | None]: # Remove 'v' prefix if present version = version_string.strip() if version.lower().startswith('v'): version = version[1:] # Parse version with optional prerelease pattern = r'^(\d+)\.(\d+)\.(\d+)(?:-(.+...
--- +++ @@ -1,8 +1,26 @@+""" +Semantic version parsing and comparison utilities. +""" import re def parse_version(version_string: str) -> tuple[int, int, int, str | None]: + """ + Parse a semantic version string into major, minor, patch, and optional prerelease. + + Supports formats like: + - "1.0.0...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/utils/semantic_version.py
Add structured docstrings to improve clarity
import asyncio from datetime import datetime from typing import Any from ...config.logfire_config import safe_logfire_error, safe_logfire_info class ProgressTracker: # Class-level storage for all progress states _progress_states: dict[str, dict[str, Any]] = {} def __init__(self, progress_id: str, oper...
--- +++ @@ -1,3 +1,8 @@+""" +Progress Tracker Utility + +Tracks operation progress in memory for HTTP polling access. +""" import asyncio from datetime import datetime @@ -7,11 +12,22 @@ class ProgressTracker: + """ + Utility class for tracking progress updates in memory. + State can be accessed via HT...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/utils/progress/progress_tracker.py
Generate NumPy-style docstrings
import asyncio import gc import threading import time from collections import deque from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from dataclasses import dataclass, field # Removed direct logging import - using unified config from enu...
--- +++ @@ -1,3 +1,11 @@+""" +Threading Service for Archon + +This service provides comprehensive threading patterns for high-performance AI operations +with adaptive resource management and rate limiting. + +Based on proven patterns from crawl4ai_mcp.py architecture. +""" import asyncio import gc @@ -22,6 +30,7 @@...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/threading_service.py
Write docstrings including parameters and return values
from datetime import datetime, timedelta from typing import Any import httpx import logfire from ..config.version import ARCHON_VERSION, GITHUB_REPO_NAME, GITHUB_REPO_OWNER from ..utils.semantic_version import is_newer_version class VersionService: def __init__(self): self._cache: dict[str, Any] | Non...
--- +++ @@ -1,3 +1,6 @@+""" +Version checking service with GitHub API integration. +""" from datetime import datetime, timedelta from typing import Any @@ -10,6 +13,7 @@ class VersionService: + """Service for checking Archon version against GitHub releases.""" def __init__(self): self._cache:...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/version_service.py
Document this code for team use
import io # Removed direct logging import - using unified config # Import document processing libraries with availability checks try: import PyPDF2 PYPDF2_AVAILABLE = True except ImportError: PYPDF2_AVAILABLE = False try: import pdfplumber PDFPLUMBER_AVAILABLE = True except ImportError: PD...
--- +++ @@ -1,3 +1,9 @@+""" +Document Processing Utilities + +This module provides utilities for extracting text from various document formats +including PDF, Word documents, and plain text files. +""" import io @@ -31,6 +37,19 @@ def _preserve_code_blocks_across_pages(text: str) -> str: + """ + Fix code...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/utils/document_processing.py
Write Python docstrings for this snippet
import asyncio import json import os import re import time from collections import defaultdict, deque from collections.abc import Callable from difflib import SequenceMatcher from typing import Any from urllib.parse import urlparse from supabase import Client from ...config.logfire_config import search_logger from ....
--- +++ @@ -1,3 +1,8 @@+""" +Code Storage Service + +Handles extraction and storage of code examples from documents. +""" import asyncio import json @@ -26,6 +31,7 @@ def _extract_json_payload(raw_response: str, context_code: str = "", language: str = "") -> str: + """Return the best-effort JSON object from ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/storage/code_storage_service.py
Add inline docstrings for readability
from typing import Any from ...config.logfire_config import get_logger logger = get_logger(__name__) # Supported embedding dimensions based on tested database schema # Note: Model lists are dynamically determined by providers, not hardcoded SUPPORTED_DIMENSIONS = { 768: [], # Common dimensions for various pro...
--- +++ @@ -1,3 +1,11 @@+""" +Multi-Dimensional Embedding Service + +Manages embeddings with different dimensions (768, 1024, 1536, 3072) to support +various embedding models from OpenAI, Google, Ollama, and other providers. + +This service works with the tested database schema that has been validated. +""" from typ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/embeddings/multi_dimensional_embedding_service.py
Add docstrings for production code
import asyncio import os from typing import Any from ...config.logfire_config import safe_span, search_logger from ..embeddings.contextual_embedding_service import generate_contextual_embeddings_batch from ..embeddings.embedding_service import create_embeddings_batch async def add_documents_to_supabase( client,...
--- +++ @@ -1,3 +1,8 @@+""" +Document Storage Service + +Handles storage of documents in Supabase with parallel processing support. +""" import asyncio import os @@ -22,6 +27,22 @@ cancellation_check: Any | None = None, url_to_page_id: dict[str, str] | None = None, ) -> dict[str, int]: + """ + Add d...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/storage/document_storage_service.py
Write docstrings including parameters and return values
from typing import Any, Optional from ...config.logfire_config import safe_logfire_info, safe_logfire_error class KnowledgeSummaryService: def __init__(self, supabase_client): self.supabase = supabase_client async def get_summaries( self, page: int = 1, per_page: int = 20, ...
--- +++ @@ -1,3 +1,9 @@+""" +Knowledge Summary Service + +Provides lightweight summary data for knowledge items to minimize data transfer. +Optimized for frequent polling and card displays. +""" from typing import Any, Optional @@ -5,8 +11,18 @@ class KnowledgeSummaryService: + """ + Service for providin...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/knowledge/knowledge_summary_service.py
Add structured docstrings to improve clarity
import re from abc import ABC, abstractmethod from collections.abc import Callable from typing import Any from urllib.parse import urlparse from ...config.logfire_config import get_logger, safe_span logger = get_logger(__name__) class BaseStorageService(ABC): def __init__(self, supabase_client=None): ...
--- +++ @@ -1,3 +1,12 @@+""" +Base Storage Service + +Provides common functionality for all document storage operations including: +- Text chunking +- Metadata extraction +- Batch processing +- Progress reporting +""" import re from abc import ABC, abstractmethod @@ -11,8 +20,10 @@ class BaseStorageService(ABC)...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/storage/base_storage_service.py
Add docstrings including usage examples
import inspect import time from contextlib import asynccontextmanager from typing import Any import openai from ..config.logfire_config import get_logger from .credential_service import credential_service logger = get_logger(__name__) # Basic validation functions to avoid circular imports def _is_valid_provider(p...
--- +++ @@ -1,3 +1,9 @@+""" +LLM Provider Service + +Provides a unified interface for creating OpenAI-compatible clients for different LLM providers. +Supports OpenAI, Ollama, and Google Gemini. +""" import inspect import time @@ -14,12 +20,14 @@ # Basic validation functions to avoid circular imports def _is_val...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/llm_provider_service.py
Create docstrings for each class method
# Removed direct logging import - using unified config from datetime import datetime from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) class ProjectService: def __init__(self, supabase_client=None): se...
--- +++ @@ -1,3 +1,10 @@+""" +Project Service Module for Archon + +This module provides core business logic for project operations that can be +shared between MCP tools and FastAPI endpoints. It follows the pattern of +separating business logic from transport-specific code. +""" # Removed direct logging import - usi...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/project_service.py
Document this module using docstrings
import re from abc import ABC, abstractmethod class ProviderErrorAdapter(ABC): @abstractmethod def get_provider_name(self) -> str: pass @abstractmethod def sanitize_error_message(self, message: str) -> str: pass class OpenAIErrorAdapter(ProviderErrorAdapter): def get_provider_...
--- +++ @@ -1,9 +1,16 @@+""" +Provider-agnostic error handling for LLM embedding services. + +Supports OpenAI, Google AI, Anthropic, Ollama, and future providers +with unified error handling and sanitization patterns. +""" import re from abc import ABC, abstractmethod class ProviderErrorAdapter(ABC): + """A...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/embeddings/provider_error_adapters.py
Create docstrings for reusable components
# Removed direct logging import - using unified config from typing import Any from src.server.utils import get_supabase_client from ...config.logfire_config import get_logger logger = get_logger(__name__) class SourceLinkingService: def __init__(self, supabase_client=None): self.supabase_client = sup...
--- +++ @@ -1,3 +1,9 @@+""" +Source Linking Service Module for Archon + +This module provides centralized logic for managing project-source relationships, +handling both technical and business source associations. +""" # Removed direct logging import - using unified config from typing import Any @@ -10,11 +16,19 @@...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/projects/source_linking_service.py
Write docstrings describing each step
import uuid from typing import Any from urllib.parse import urljoin import httpx from ..config.logfire_config import mcp_logger from ..config.service_discovery import get_agents_url, get_api_url class MCPServiceClient: def __init__(self): self.api_url = get_api_url() self.agents_url = get_agen...
--- +++ @@ -1,3 +1,9 @@+""" +MCP Service Client for HTTP-based microservice communication + +This module provides HTTP clients for the MCP service to communicate with +other services (API and Agents) instead of importing their modules directly. +""" import uuid from typing import Any @@ -10,6 +16,10 @@ class MC...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/mcp_service_client.py
Add docstrings to meet PEP guidelines
# Import all functions from new services for backward compatibility import asyncio # Keep some imports that are still needed import os from typing import Optional from ..services.client_manager import get_supabase_client from ..services.embeddings import ( create_embedding, create_embeddings_batch, gener...
--- +++ @@ -1,3 +1,16 @@+""" +Utility functions for the Crawl4AI MCP server - Compatibility Layer + +This file now serves as a compatibility layer, importing functions from +the new service modules to maintain backward compatibility. + +The actual implementations have been moved to: +- services/embeddings/ - Embedding ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/utils/__init__.py
Write docstrings for backend logic
from datetime import datetime from typing import Any from ...config.logfire_config import safe_logfire_error, safe_logfire_info class DatabaseMetricsService: def __init__(self, supabase_client): self.supabase = supabase_client async def get_metrics(self) -> dict[str, Any]: try: ...
--- +++ @@ -1,3 +1,8 @@+""" +Database Metrics Service + +Handles retrieval of database statistics and metrics. +""" from datetime import datetime from typing import Any @@ -6,11 +11,26 @@ class DatabaseMetricsService: + """ + Service for retrieving database metrics and statistics. + """ def __in...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/knowledge/database_metrics_service.py
Add verbose docstrings with examples
from typing import Any from ...config.logfire_config import get_logger, safe_span from .base_storage_service import BaseStorageService from .document_storage_service import add_documents_to_supabase logger = get_logger(__name__) class DocumentStorageService(BaseStorageService): async def upload_document( ...
--- +++ @@ -1,271 +1,324 @@- -from typing import Any - -from ...config.logfire_config import get_logger, safe_span -from .base_storage_service import BaseStorageService -from .document_storage_service import add_documents_to_supabase - -logger = get_logger(__name__) - - -class DocumentStorageService(BaseStorageService)...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/storage/storage_services.py
Add docstrings that explain inputs and outputs
from __future__ import annotations import importlib import types from typing import Any from typing import TYPE_CHECKING if TYPE_CHECKING: from types import TracebackType _INTEGRATION_IMPORT_ERROR_TEMPLATE = ( "\nCould not find `optuna-integration` for `{0}`.\n" "Please run `pip install optuna-integrati...
--- +++ @@ -16,11 +16,23 @@ class _DeferredImportExceptionContextManager: + """Context manager to defer exceptions from imports. + + Catches :exc:`ImportError` and :exc:`SyntaxError`. + If any exception is caught, this class raises an :exc:`ImportError` when being checked. + + """ def __init__(se...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_imports.py
Auto-generate documentation strings for this file
from __future__ import annotations import abc import copy import decimal import json import math from numbers import Real from typing import Any from typing import cast from typing import TYPE_CHECKING from typing import Union from optuna._deprecated import deprecated_class from optuna._warnings import optuna_warn ...
--- +++ @@ -29,23 +29,62 @@ class BaseDistribution(abc.ABC): + """Base class for distributions. + + Note that distribution classes are not supposed to be called by library users. + They are used by :class:`~optuna.trial.Trial` and :class:`~optuna.samplers` internally. + """ def to_external_repr(s...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/distributions.py
Write docstrings describing functionality
from __future__ import annotations import logging from logging import CRITICAL from logging import DEBUG from logging import ERROR from logging import FATAL from logging import INFO from logging import WARN from logging import WARNING import sys import threading import colorlog __all__ = [ "CRITICAL", "DEBU...
--- +++ @@ -29,6 +29,10 @@ def create_default_formatter() -> logging.Formatter: + """Create a default formatter of log messages. + + This function is not supposed to be directly accessed by library users. + """ header = "[%(levelname)1.1s %(asctime)s]" message = "%(message)s" return colorlog...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/logging.py
Write docstrings describing functionality
from __future__ import annotations import math import numpy as np from optuna._hypervolume.wfg import compute_hypervolume def _solve_hssp_2d( rank_i_loss_vals: np.ndarray, rank_i_indices: np.ndarray, subset_size: int, reference_point: np.ndarray, ) -> np.ndarray: # This function can be used for...
--- +++ @@ -49,6 +49,22 @@ reference_point: np.ndarray, hv_selected: float, ) -> np.ndarray: + """Lazy update the hypervolume contributions. + + (1) Lazy update of the hypervolume contributions + S=selected_indices - {indices[max_index]}, T=selected_indices, and S' is a subset of S. + As we would ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_hypervolume/hssp.py
Add docstrings to improve readability
from __future__ import annotations from collections import defaultdict from collections.abc import Callable from collections.abc import Sequence from itertools import combinations_with_replacement from typing import TYPE_CHECKING import numpy as np from optuna.samplers._lazy_random_state import LazyRandomState from ...
--- +++ @@ -42,6 +42,17 @@ self._rng = rng def __call__(self, study: Study, population: list[FrozenTrial]) -> list[FrozenTrial]: + """Select elite population from the given trials by NSGA-III algorithm. + + Args: + study: + Target study object. + populat...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_nsgaiii/_elite_population_selection_strategy.py
Write docstrings for utility functions
from __future__ import annotations import functools import textwrap from typing import Any from typing import TYPE_CHECKING from typing import TypeVar import warnings from optuna._warnings import optuna_warn from optuna.exceptions import ExperimentalWarning if TYPE_CHECKING: from collections.abc import Callable...
--- +++ @@ -52,6 +52,13 @@ version: str, name: str | None = None, ) -> Callable[[Callable[FP, FT]], Callable[FP, FT]]: + """Decorate function as experimental. + + Args: + version: The first version that supports the target feature. + name: The name of the feature. Defaults to fully qualifi...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_experimental.py
Write beginner-friendly docstrings
from __future__ import annotations import binascii import math from typing import TYPE_CHECKING import optuna if TYPE_CHECKING: from collections.abc import Container from optuna import logging from optuna.pruners._base import BasePruner from optuna.pruners._successive_halving import SuccessiveHalvingPruner from...
--- +++ @@ -19,6 +19,131 @@ class HyperbandPruner(BasePruner): + """Pruner using Hyperband. + + As SuccessiveHalving (SHA) requires the number of configurations + :math:`n` as its hyperparameter. For a given finite budget :math:`B`, + all the configurations have the resources of :math:`B \\over n` on a...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/pruners/_hyperband.py
Generate docstrings for each module
from __future__ import annotations import argparse from argparse import ArgumentParser from argparse import Namespace import datetime from enum import Enum import inspect import json import logging import os import sys from typing import Any import sqlalchemy.exc import yaml import optuna from optuna._imports impor...
--- +++ @@ -1,3 +1,6 @@+"""Optuna CLI module. +If you want to add a new command, you also need to update the constant `_COMMANDS` +""" from __future__ import annotations @@ -268,19 +271,41 @@ class _BaseCommand: + """Base class for commands. + + Note that command classes are not intended to be called by ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/cli.py
Add inline docstrings for readability
from __future__ import annotations from dataclasses import asdict from dataclasses import dataclass import json import mimetypes import os from typing import TYPE_CHECKING import uuid from optuna._convert_positional_args import convert_positional_args from optuna.study import Study from optuna.trial import FrozenTria...
--- +++ @@ -24,6 +24,25 @@ @dataclass class ArtifactMeta: + """Meta information for an artifact. + + .. note:: + All the artifact meta linked to a study or trial can be listed by + :func:`~optuna.artifacts.get_all_artifact_meta`. + The artifact meta can be used for :func:`~optuna.artifacts...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/artifacts/_upload.py
Add docstrings for production code
from __future__ import annotations import abc from typing import Any import optuna from optuna.samplers._base import BaseSampler from optuna.trial._frozen import FrozenTrial from optuna.trial._state import TrialState # TODO(gen740): Add the experimental decorator? class BaseGASampler(BaseSampler, abc.ABC): _GE...
--- +++ @@ -11,6 +11,24 @@ # TODO(gen740): Add the experimental decorator? class BaseGASampler(BaseSampler, abc.ABC): + """Base class for Genetic Algorithm (GA) samplers. + + Genetic Algorithm samplers generate new trials by mimicking natural selection, using + generations and populations to iteratively imp...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_ga/_base.py
Add concise docstrings to each method
from __future__ import annotations import numpy as np from optuna.study._multi_objective import _is_pareto_front def _compute_2d(sorted_pareto_sols: np.ndarray, reference_point: np.ndarray) -> float: assert sorted_pareto_sols.shape[1] == reference_point.shape[0] == 2 rect_diag_y = np.concatenate([reference_...
--- +++ @@ -14,6 +14,15 @@ def _compute_3d(sorted_pareto_sols: np.ndarray, reference_point: np.ndarray) -> float: + """ + Compute hypervolume in 3D. Time complexity is O(N^2) where N is sorted_pareto_sols.shape[0]. + If X, Y, Z coordinates are permutations of 0, 1, ..., N-1 and reference_point is (N, N, N)...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_hypervolume/wfg.py
Generate docstrings with parameter types
from __future__ import annotations import logging from typing import Any from typing import TYPE_CHECKING from tqdm.auto import tqdm from optuna import logging as optuna_logging from optuna._warnings import optuna_warn if TYPE_CHECKING: from optuna.study import Study _tqdm_handler: _TqdmLoggingHandler | None ...
--- +++ @@ -30,6 +30,16 @@ class _ProgressBar: + """Progress Bar implementation for :func:`~optuna.study.Study.optimize` on the top of `tqdm`. + + Args: + is_valid: + Whether to show progress bars in :func:`~optuna.study.Study.optimize`. + n_trials: + The number of trials. ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/progress_bar.py
Improve my code by adding docstrings
from __future__ import annotations import math from typing import Any from typing import TYPE_CHECKING import numpy as np from optuna._gp.scipy_blas_thread_patch import single_blas_thread_if_scipy_v1_15_or_newer from optuna._warnings import optuna_warn from optuna.logging import get_logger if TYPE_CHECKING: f...
--- +++ @@ -1,3 +1,21 @@+"""Notations in this Gaussian process implementation + +X_train: Observed parameter values with the shape of (len(trials), len(params)). +y_train: Observed objective values with the shape of (len(trials), ). +x: (Possibly batched) parameter value(s) to evaluate with the shape of (..., len(param...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_gp/gp.py
Improve my code by adding docstrings
from __future__ import annotations import numpy as np from optuna._warnings import optuna_warn from optuna.study._multi_objective import _is_pareto_front def _get_upper_bound_set( sorted_pareto_sols: np.ndarray, ref_point: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: (_, n_objectives) = sorted_pareto_sol...
--- +++ @@ -1,3 +1,23 @@+""" +The functions in this file are mostly based on BoTorch v0.13.0, +but they are refactored significantly from the original version. + +For ``_get_upper_bound_set``, look at: + * https://github.com/pytorch/botorch/blob/v0.13.0/botorch/utils/multi_objective/box_decompositions/utils.py#L101-...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_hypervolume/box_decomposition.py
Add docstrings to my Python code
from __future__ import annotations import abc from typing import cast from typing import TYPE_CHECKING import numpy as np from optuna.search_space import intersection_search_space from optuna.trial import TrialState if TYPE_CHECKING: from collections.abc import Callable from collections.abc import Collecti...
--- +++ @@ -21,6 +21,7 @@ class BaseImportanceEvaluator(abc.ABC): + """Abstract parameter importance evaluator.""" @abc.abstractmethod def evaluate( @@ -30,6 +31,40 @@ *, target: Callable[[FrozenTrial], float] | None = None, ) -> dict[str, float]: + """Evaluate parameter ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/importance/_base.py
Annotate my code with docstrings
from __future__ import annotations from typing import Protocol from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import BinaryIO class ArtifactStore(Protocol): def open_reader(self, artifact_id: str) -> BinaryIO: ... def write(self, artifact_id: str, content_body: BinaryIO) -> No...
--- +++ @@ -9,12 +9,48 @@ class ArtifactStore(Protocol): + """A protocol defining the interface for an artifact backend. + + The methods defined in this protocol are not supposed to be directly called by library users. + + An artifact backend is responsible for managing the storage and retrieval + of ar...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/artifacts/_protocol.py
Add docstrings including usage examples
from __future__ import annotations import math from typing import Any import numpy as np from optuna.distributions import BaseDistribution from optuna.distributions import CategoricalDistribution from optuna.distributions import FloatDistribution from optuna.distributions import IntDistribution class _SearchSpaceT...
--- +++ @@ -12,6 +12,51 @@ class _SearchSpaceTransform: + """Transform a search space and parameter configurations to continuous space. + + The search space bounds and parameter configurations are represented as ``numpy.ndarray``s and + transformed into continuous space. Bounds and parameters associated wi...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_transform.py
Write documentation strings for class attributes
from __future__ import annotations import abc from typing import Any from typing import TYPE_CHECKING import numpy as np from optuna._warnings import optuna_warn from optuna.trial import TrialState if TYPE_CHECKING: from collections.abc import Callable from collections.abc import Sequence from optuna....
--- +++ @@ -30,6 +30,37 @@ class BaseSampler(abc.ABC): + """Base class for samplers. + + Optuna combines two types of sampling strategies, which are called *relative sampling* and + *independent sampling*. + + *The relative sampling* determines values of multiple parameters simultaneously so that + s...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_base.py
Add concise docstrings to each method
class OptunaError(Exception): pass class TrialPruned(OptunaError): pass class CLIUsageError(OptunaError): pass class StorageInternalError(OptunaError): pass class DuplicatedStudyError(OptunaError): pass class UpdateFinishedTrialError(OptunaError, RuntimeError): pass class Exper...
--- +++ @@ -1,33 +1,101 @@ class OptunaError(Exception): + """Base class for Optuna specific errors.""" pass class TrialPruned(OptunaError): + """Exception for pruned trials. + + This error tells a trainer that the current :class:`~optuna.trial.Trial` was pruned. It is + supposed to be raised af...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/exceptions.py
Add docstrings to clarify complex logic
from __future__ import annotations import functools import textwrap from typing import Any from typing import TYPE_CHECKING from typing import TypeVar import warnings from packaging import version from optuna._experimental import _get_docstring_indent from optuna._experimental import _validate_version if TYPE_CHEC...
--- +++ @@ -58,6 +58,29 @@ name: str | None = None, text: str | None = None, ) -> "Callable[[Callable[FP, FT]], Callable[FP, FT]]": + """Decorate function as deprecated. + + Args: + deprecated_version: + The version in which the target feature is deprecated. + removed_version: +...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/_deprecated.py
Add docstrings to incomplete code
from __future__ import annotations import itertools from numbers import Real from typing import Any from typing import TYPE_CHECKING from typing import Union import numpy as np from optuna._warnings import optuna_warn from optuna.logging import get_logger from optuna.samplers import BaseSampler from optuna.samplers....
--- +++ @@ -31,6 +31,81 @@ class GridSampler(BaseSampler): + """Sampler using grid search. + + With :class:`~optuna.samplers.GridSampler`, the trials suggest all combinations of parameters + in the given search space during the study. + + Example: + + .. testcode:: + + import optuna + ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_grid.py
Add docstrings to make code maintainable
import logging from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config from sqlalchemy import pool import optuna.storages._rdb.models # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config #...
--- +++ @@ -31,6 +31,17 @@ def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Cal...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_rdb/alembic/env.py
Help me add docstrings to my project
# This file contains the codes from SciPy project. # # Copyright (c) 2001-2002 Enthought, Inc. 2003-2022, SciPy Developers. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions o...
--- +++ @@ -111,6 +111,7 @@ def _log_gauss_mass(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Log of Gaussian probability mass within an interval""" # Calculations in right tail are inaccurate, so we'll exploit the # symmetry and work only in the left tail @@ -149,6 +150,51 @@ def _ndtri_exp(...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_tpe/_truncnorm.py
Turn comments into proper docstrings
from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING import numpy as np from optuna.samplers.nsgaii._constraints_evaluation import _evaluate_penalty from optuna.samplers.nsgaii._constraints_evaluation import _validate_constraints from optuna.study import StudyDirect...
--- +++ @@ -33,6 +33,17 @@ self._constraints_func = constraints_func def __call__(self, study: Study, population: list[FrozenTrial]) -> list[FrozenTrial]: + """Select elite population from the given trials by NSGA-II algorithm. + + Args: + study: + Target study obj...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/nsgaii/_elite_population_selection_strategy.py
Provide clean and structured docstrings
from __future__ import annotations from collections import UserDict import copy from typing import Any from typing import overload from typing import TYPE_CHECKING import optuna from optuna import distributions from optuna import logging from optuna import pruners from optuna._convert_positional_args import convert_p...
--- +++ @@ -35,6 +35,23 @@ class Trial(BaseTrial): + """A trial is a process of evaluating an objective function. + + This object is passed to an objective function and provides interfaces to get parameter + suggestion, manage the trial's state, and set/get user-defined attributes of the trial. + + Note...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/trial/_trial.py
Add docstrings to meet PEP guidelines
import enum class TrialState(enum.IntEnum): RUNNING = 0 COMPLETE = 1 PRUNED = 2 FAIL = 3 WAITING = 4 __str__ = enum.Enum.__str__ # To show the name of the state. def is_finished(self) -> bool: return self != TrialState.RUNNING and self != TrialState.WAITING
--- +++ @@ -2,6 +2,21 @@ class TrialState(enum.IntEnum): + """State of a :class:`~optuna.trial.Trial`. + + Attributes: + RUNNING: + The :class:`~optuna.trial.Trial` is running. + WAITING: + The :class:`~optuna.trial.Trial` is waiting and unfinished. + COMPLETE: + ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/trial/_state.py
Generate consistent documentation across files
from __future__ import annotations import abc from collections.abc import Container from collections.abc import Sequence from typing import Any from typing import cast from optuna._typing import JSONSerializable from optuna.distributions import BaseDistribution from optuna.exceptions import UpdateFinishedTrialError f...
--- +++ @@ -19,6 +19,32 @@ class BaseStorage(abc.ABC): + """Base class for storages. + + This class is not supposed to be directly accessed by library users. + + This class abstracts a backend database and provides internal interfaces to + read/write histories of studies and trials. + + A storage cla...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_base.py
Replace inline comments with docstrings
from __future__ import annotations import abc from collections.abc import Callable import copy from threading import Event from threading import Thread from types import TracebackType import optuna from optuna._experimental import experimental_func from optuna.storages import BaseStorage from optuna.trial import Froz...
--- +++ @@ -15,21 +15,58 @@ class BaseHeartbeat(metaclass=abc.ABCMeta): + """Base class for heartbeat. + + This class is not supposed to be directly accessed by library users. + + The heartbeat mechanism periodically checks whether each trial process is alive during an + optimization loop. To support th...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_heartbeat.py
Create documentation strings for testing functions
from __future__ import annotations from collections.abc import Callable from collections.abc import Sequence from functools import lru_cache import json import math from typing import Any from typing import cast from typing import TYPE_CHECKING import numpy as np from optuna import _deprecated from optuna._convert_p...
--- +++ @@ -70,6 +70,221 @@ class TPESampler(BaseSampler): + """Sampler using TPE (Tree-structured Parzen Estimator) algorithm. + + On each trial, for each parameter, TPE fits one Gaussian Mixture Model (GMM) ``l(x)`` to + the set of parameter values associated with the best objective values, and another G...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_tpe/sampler.py
Add minimal docstrings for each function
from __future__ import annotations from collections.abc import Container from collections.abc import Sequence import copy import json import threading from typing import Any from typing import TYPE_CHECKING import uuid from optuna._experimental import experimental_class from optuna._imports import _LazyImport from op...
--- +++ @@ -44,6 +44,33 @@ @experimental_class("4.2.0") class GrpcStorageProxy(BaseStorage): + """gRPC client for :func:`~optuna.storages.run_grpc_proxy_server`. + + Example: + + This is a simple example of using :class:`~optuna.storages.GrpcStorageProxy` with + :func:`~optuna.storages.run_grpc_p...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_grpc/client.py
Annotate my code with docstrings
from __future__ import annotations import abc from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from optuna.study import Study class BaseCrossover(abc.ABC): def __str__(self) -> str: return self.__class__.__name__ @property @abc.abstractmethod def n_parents(self) ...
--- +++ @@ -11,6 +11,16 @@ class BaseCrossover(abc.ABC): + """Base class for crossovers. + + A crossover operation is used by :class:`~optuna.samplers.NSGAIISampler` + to create new parameter combination from parameters of ``n`` parent individuals. + + .. note:: + Concrete implementations of this...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/nsgaii/_crossovers/_base.py
Help me document legacy Python code
from __future__ import annotations import copy from typing import TYPE_CHECKING import optuna if TYPE_CHECKING: from optuna.distributions import BaseDistribution from optuna.study import Study def _calculate( trials: list[optuna.trial.FrozenTrial], include_pruned: bool = False, search_space: d...
--- +++ @@ -56,6 +56,23 @@ class IntersectionSearchSpace: + """A class to calculate the intersection search space of a :class:`~optuna.study.Study`. + + Intersection search space contains the intersection of parameter distributions that have been + suggested in the completed trials of the study so far. + ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/search_space/intersection.py
Insert docstrings into my code
from __future__ import annotations import abc from optuna._experimental import experimental_class from optuna.study.study import Study from optuna.terminator.erroreval import BaseErrorEvaluator from optuna.terminator.erroreval import CrossValidationErrorEvaluator from optuna.terminator.erroreval import StaticErrorEva...
--- +++ @@ -15,6 +15,7 @@ class BaseTerminator(metaclass=abc.ABCMeta): + """Base class for terminators.""" @abc.abstractmethod def should_terminate(self, study: Study) -> bool: @@ -23,6 +24,79 @@ @experimental_class("3.2.0") class Terminator(BaseTerminator): + """Automatic stopping mechanism fo...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/terminator/terminator.py
Turn comments into proper docstrings
from __future__ import annotations import datetime import math from typing import Any from typing import cast from typing import overload from typing import TYPE_CHECKING from optuna import distributions from optuna import logging from optuna._convert_positional_args import convert_positional_args from optuna._deprec...
--- +++ @@ -35,6 +35,112 @@ class FrozenTrial(BaseTrial): + """Status and results of a :class:`~optuna.trial.Trial`. + + An object of this class has the same methods as :class:`~optuna.trial.Trial`, but is not + associated with, nor has any references to a :class:`~optuna.study.Study`. + + It is therefo...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/trial/_frozen.py
Document my Python code with docstrings
from __future__ import annotations import abc from typing import cast from typing import TYPE_CHECKING import numpy as np from optuna._experimental import experimental_class from optuna.study import StudyDirection from optuna.trial._state import TrialState if TYPE_CHECKING: from optuna.trial import FrozenTrial...
--- +++ @@ -20,6 +20,7 @@ class BaseErrorEvaluator(metaclass=abc.ABCMeta): + """Base class for error evaluators.""" @abc.abstractmethod def evaluate( @@ -32,12 +33,34 @@ @experimental_class("3.2.0") class CrossValidationErrorEvaluator(BaseErrorEvaluator): + """An error evaluator for objective f...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/terminator/erroreval.py
Add docstrings to clarify complex logic
from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from optuna._warnings import optuna_warn from optuna.samplers._base import _CONSTRAINTS_KEY from optuna.study._multi_objective import _dominates from optuna.trial import TrialState if TYPE_CHECKING: from collections.abc impo...
--- +++ @@ -20,6 +20,15 @@ def _constrained_dominates( trial0: FrozenTrial, trial1: FrozenTrial, directions: Sequence[StudyDirection] ) -> bool: + """Checks constrained-domination. + + A trial x is said to constrained-dominate a trial y, if any of the following conditions is + true: + 1) Trial x is fe...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/nsgaii/_constraints_evaluation.py
Write docstrings including parameters and return values
from __future__ import annotations import abc from collections.abc import Iterable from typing import Any from optuna._deprecated import deprecated_class class BaseJournalBackend(abc.ABC): @abc.abstractmethod def read_logs(self, log_number_from: int) -> Iterable[dict[str, Any]]: raise NotImplement...
--- +++ @@ -8,30 +8,80 @@ class BaseJournalBackend(abc.ABC): + """Base class for Journal storages. + + Storage classes implementing this base class must guarantee process safety. This means, + multiple processes might concurrently call ``read_logs`` and ``append_logs``. If the + backend storage does not...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/journal/_base.py
Add docstrings including usage examples
from __future__ import annotations from collections.abc import Callable from collections.abc import Sequence import json from typing import Any from typing import cast import numpy as np import optuna from optuna._warnings import optuna_warn from optuna.distributions import CategoricalDistribution from optuna.distri...
--- +++ @@ -24,6 +24,18 @@ def is_available() -> bool: + """Returns whether visualization with plotly is available or not. + + .. note:: + + :mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a + supported version of plotly isn't installed in your environment, this...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/visualization/_utils.py
Document helper functions with docstrings
from __future__ import annotations from typing import NamedTuple from typing import Union import numpy as np from optuna.samplers._tpe import _truncnorm class _BatchedCategoricalDistributions(NamedTuple): weights: np.ndarray class _BatchedTruncNormDistributions(NamedTuple): mu: np.ndarray sigma: np.n...
--- +++ @@ -52,6 +52,10 @@ def _unique_inverse_2d(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + This function is a quicker version of: + np.unique(np.concatenate([a[:, None], b[:, None]], axis=-1), return_inverse=True). + """ assert a.shape == b.shape and l...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/samplers/_tpe/probability_distributions.py
Add docstrings with type hints explained
from __future__ import annotations from collections import defaultdict from collections.abc import Callable from collections.abc import Container from collections.abc import Generator from collections.abc import Iterable from collections.abc import Sequence from contextlib import contextmanager import copy from dateti...
--- +++ @@ -104,6 +104,100 @@ class RDBStorage(BaseStorage, BaseHeartbeat): + """Storage class for RDB backend. + + Note that library users can instantiate this class, but the attributes + provided by this class are not supposed to be directly accessed by them. + + Example: + + Create an :class:`...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_rdb/storage.py
Document this code for team use
from __future__ import annotations import abc from collections.abc import Generator from collections.abc import Iterator from contextlib import contextmanager import errno import json import os import time from typing import Any import uuid from optuna._deprecated import deprecated_class from optuna._warnings import ...
--- +++ @@ -24,6 +24,37 @@ class JournalFileBackend(BaseJournalBackend): + """File storage class for Journal log backend. + + Compared to SQLite3, the benefit of this backend is that it is more suitable for + environments where the file system does not support ``fcntl()`` file locking. + For example, as...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/journal/_file.py
Document classes and their methods
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from optuna import _warnings as warnings import optuna.storages._grpc.auto_generated.api_pb2 as api__pb2 GRPC_GENERATED_VERSION = '1.68.1' GRPC_VERSION = grpc.__version__ _version_not_supported = False try: from grpc._utilities imp...
--- +++ @@ -1,4 +1,5 @@ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" import grpc from optuna import _warnings as warnings @@ -25,8 +26,16 @@ class StorageServiceStub(object): + """* + Optuna storage servi...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_grpc/auto_generated/api_pb2_grpc.py
Turn comments into proper docstrings
from __future__ import annotations from collections.abc import Callable from collections.abc import Container from collections.abc import Iterable from collections.abc import Mapping from collections.abc import Sequence import copy from numbers import Real import threading from typing import Any from typing import cas...
--- +++ @@ -65,6 +65,16 @@ class Study: + """A study corresponds to an optimization task, i.e., a set of trials. + + This object provides interfaces to run a new :class:`~optuna.trial.Trial`, access trials' + history, set/get user-defined attributes of the study itself. + + Note that the direct use of t...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/study/study.py
Write docstrings for utility functions
from __future__ import annotations from typing import Any import optuna from optuna._experimental import experimental_class from optuna._experimental import experimental_func from optuna.trial import FrozenTrial @experimental_class("2.8.0") class RetryFailedTrialCallback: def __init__( self, max_retry:...
--- +++ @@ -10,6 +10,51 @@ @experimental_class("2.8.0") class RetryFailedTrialCallback: + """Retry a failed trial up to a maximum number of times. + + When a trial fails, this callback can be used with a class in :mod:`optuna.storages` to + recreate the trial in ``TrialState.WAITING`` to queue up the trial ...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/storages/_callbacks.py
Generate docstrings with examples
from __future__ import annotations import abc from typing import TYPE_CHECKING import numpy as np from optuna._experimental import experimental_class from optuna.distributions import BaseDistribution from optuna.samplers._lazy_random_state import LazyRandomState from optuna.search_space import intersection_search_sp...
--- +++ @@ -56,6 +56,13 @@ optimize_n_samples: int = 2048, rng: np.random.RandomState | None = None, ) -> float: + """ + # In the original paper, f(x) was intended to be minimized, but here we would like to + # maximize f(x). Hence, the following changes happen: + # 1. min(ucb) over top trials...
https://raw.githubusercontent.com/optuna/optuna/HEAD/optuna/terminator/improvement/evaluator.py
Write beginner-friendly docstrings
from hashlib import md5 from random import randint from time import time from src.custom import USERAGENT class XGnarly: _AA = [ 0xFFFFFFFF, 138, 1498001188, 211147047, 253, None, 203, 288, 9, 1196819126, 3212677781, ...
--- +++ @@ -108,10 +108,16 @@ ) def __init__(self): + """ + 初始化 XGnarly 实例,并创建其唯一的 PRNG 状态。 + """ self.St = None self._init_prng_state() def _init_prng_state(self): + """ + 设置 PRNG 的初始状态,此状态将在此实例的生命周期内持续存在。 + """ now_ms = int(time() ...
https://raw.githubusercontent.com/JoeanAmier/TikTokDownloader/HEAD/src/encrypt/xGnarly.py
Document this module using docstrings
from platform import system from re import compile from string import whitespace from emoji import replace_emoji try: from ..translation import _ except ImportError: _ = lambda x: x __all__ = ["Cleaner"] class Cleaner: CONTROL_CHARACTERS = compile(r"[\x00-\x1F\x7F]") def __init__(self): se...
--- +++ @@ -16,10 +16,14 @@ CONTROL_CHARACTERS = compile(r"[\x00-\x1F\x7F]") def __init__(self): + """ + 替换字符串中包含的非法字符,默认根据系统类型生成对应的非法字符字典,也可以自行设置非法字符字典 + """ self.rule = self.default_rule() # 默认非法字符字典 @staticmethod def default_rule(): + """根据系统类型生成默认非法字符字典""...
https://raw.githubusercontent.com/JoeanAmier/TikTokDownloader/HEAD/src/tools/cleaner.py
Replace inline comments with docstrings
from asyncio import sleep from random import randint from typing import TYPE_CHECKING from src.translation import _ if TYPE_CHECKING: from src.tools import ColorfulConsole async def wait() -> None: # 随机延时 await sleep(randint(5, 20) * 0.1) # 固定延时 # await sleep(1) # 取消延时 # pass def failur...
--- +++ @@ -8,6 +8,9 @@ async def wait() -> None: + """ + 设置网络请求间隔时间,仅对获取数据生效,不影响下载文件 + """ # 随机延时 await sleep(randint(5, 20) * 0.1) # 固定延时 @@ -17,6 +20,7 @@ def failure_handling() -> bool: + """批量下载账号作品模式 和 批量下载合集作品模式 获取数据失败时,是否继续执行""" # 询问用户 # return bool(input(_("输入任意字符继续...
https://raw.githubusercontent.com/JoeanAmier/TikTokDownloader/HEAD/src/custom/function.py
Add concise docstrings to each method
from typing import Any, Dict, List, Literal, Optional, TypedDict class MCPConfig(TypedDict, total=False): # Required fields type: Literal["mcp"] name: str # Transport: stdio command: str args: List[str] env: Dict[str, str] cwd: str # Transport: http server_url: str head...
--- +++ @@ -1,8 +1,15 @@+""" +MCP configuration validation and normalization. + +This module provides utilities for validating and normalizing MCP tool +configuration dictionaries passed to aisuite's chat completion API. +""" from typing import Any, Dict, List, Literal, Optional, TypedDict class MCPConfig(Typed...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/mcp/config.py
Add docstrings including usage examples
import os import httpx from aisuite.provider import Provider, LLMError from aisuite.framework import ChatCompletionResponse class LmstudioProvider(Provider): _CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions" _CONNECT_ERROR_MESSAGE = "LM Studio is likely not running. Start LM Studio by running `ollama serve`...
--- +++ @@ -5,11 +5,20 @@ class LmstudioProvider(Provider): + """ + LM Studio Provider that makes HTTP calls. Inspired by OllamaProvider in aisuite. + It uses the /v1/chat/completions endpoint. + Read more here - https://lmstudio.ai/docs/api and on your local instance in the "Developer" tab. + If LMS...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/lmstudio_provider.py
Add minimal docstrings for each function
import os import cohere import json from aisuite.framework import ChatCompletionResponse from aisuite.framework.message import Message, ChatCompletionMessageToolCall, Function from aisuite.provider import Provider, LLMError class CohereMessageConverter: def convert_request(self, messages): converted_mess...
--- +++ @@ -7,8 +7,12 @@ class CohereMessageConverter: + """ + Cohere-specific message converter + """ def convert_request(self, messages): + """Convert framework messages to Cohere format.""" converted_messages = [] for message in messages: @@ -71,6 +75,7 @@ retur...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/cohere_provider.py
Can you add docstrings to this Python file?
import os import httpx from aisuite.provider import Provider, LLMError from aisuite.providers.message_converter import OpenAICompliantMessageConverter class TogetherMessageConverter(OpenAICompliantMessageConverter): pass class TogetherProvider(Provider): BASE_URL = "https://api.together.xyz/v1/chat/comple...
--- +++ @@ -5,15 +5,25 @@ class TogetherMessageConverter(OpenAICompliantMessageConverter): + """ + Together-specific message converter if needed + """ pass class TogetherProvider(Provider): + """ + Together AI Provider using httpx for direct API calls. + """ BASE_URL = "https://...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/together_provider.py
Add docstrings with type hints explained
# Anthropic provider # Links: # Tool calling docs - https://docs.anthropic.com/en/docs/build-with-claude/tool-use import anthropic import json from aisuite.provider import Provider from aisuite.framework import ChatCompletionResponse from aisuite.framework.message import ( Message, ChatCompletionMessageToolCal...
--- +++ @@ -33,11 +33,13 @@ } def convert_request(self, messages): + """Convert framework messages to Anthropic format.""" system_message = self._extract_system_message(messages) converted_messages = [self._convert_single_message(msg) for msg in messages] return system_messa...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/anthropic_provider.py
Generate docstrings with parameter types
import os from aisuite.provider import Provider, LLMError from openai import OpenAI from aisuite.providers.message_converter import OpenAICompliantMessageConverter class SambanovaMessageConverter(OpenAICompliantMessageConverter): pass class SambanovaProvider(Provider): def __init__(self, **config): ...
--- +++ @@ -5,13 +5,23 @@ class SambanovaMessageConverter(OpenAICompliantMessageConverter): + """ + SambaNova-specific message converter. + """ pass class SambanovaProvider(Provider): + """ + SambaNova Provider using OpenAI client for API calls. + """ def __init__(self, **config...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/sambanova_provider.py
Add clean documentation to messy code
import os import json from typing import List, Dict, Any, Optional, Union, BinaryIO, AsyncGenerator import vertexai from vertexai.generative_models import ( GenerativeModel, GenerationConfig, Content, Part, Tool, FunctionDeclaration, ) import pprint from aisuite.framework import ChatCompletio...
--- +++ @@ -1,3 +1,4 @@+"""The interface to Google's Vertex AI.""" import os import json @@ -36,11 +37,13 @@ class GoogleMessageConverter: @staticmethod def convert_user_role_message(message: Dict[str, Any]) -> Content: + """Convert user or system messages to Google Vertex AI format.""" pa...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/google_provider.py
Document all public functions with docstrings
from typing import Literal, Optional, List, AsyncGenerator, Union, Dict, Any from pydantic import BaseModel from dataclasses import dataclass, field class Function(BaseModel): arguments: str name: str class ChatCompletionMessageToolCall(BaseModel): id: str function: Function type: Literal["fu...
--- +++ @@ -1,3 +1,7 @@+""" +Interface to hold contents of api responses when they do not confirm +to the OpenAI style response. +""" from typing import Literal, Optional, List, AsyncGenerator, Union, Dict, Any from pydantic import BaseModel @@ -5,12 +9,14 @@ class Function(BaseModel): + """Represents a func...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/framework/message.py
Add inline docstrings for readability
import os import openai from aisuite.provider import Provider, LLMError from aisuite.providers.message_converter import OpenAICompliantMessageConverter # pylint: disable=too-few-public-methods class DeepseekProvider(Provider): def __init__(self, **config): # Ensure API key is provided either in config o...
--- +++ @@ -1,3 +1,4 @@+"""Deepseek provider for the aisuite.""" import os import openai @@ -7,8 +8,13 @@ # pylint: disable=too-few-public-methods class DeepseekProvider(Provider): + """Provider for Deepseek.""" def __init__(self, **config): + """ + Initialize the DeepSeek provider with t...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/deepseek_provider.py
Provide clean and structured docstrings
import asyncio import json from typing import Any, Callable, Dict, List, Optional from contextlib import contextmanager try: from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client import httpx except ImportError as e: if "mcp" in str(e): raise ImportErro...
--- +++ @@ -1,3 +1,9 @@+""" +MCP Client for aisuite. + +This module provides the MCPClient class that connects to MCP servers and +exposes their tools as Python callables compatible with aisuite's tool system. +""" import asyncio import json @@ -26,6 +32,37 @@ class MCPClient: + """ + Client for connectin...
https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/mcp/client.py